code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.storage.fs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import org.geogit.api.Platform; import org.geogit.api.porcelain.ConfigException; import org.geogit.storage.ConfigDatabase; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import com.google.common.base.Optional; // TODO: Not sure if this belongs in porcelain or integration public class IniFileConfigDatabaseTest { @Rule public ExpectedException exception = ExpectedException.none(); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Before public final void setUp() { } @After public final void tearDown() { } @Test public void testLocal() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); tempFolder.newFolder("mockWorkingDir/.geogit"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); // Test integer and string ini.put("section.int", 1); ini.put("section.string", "2"); final int one = ini.get("section.int", int.class).or(-1); assertEquals(one, 1); final String two = ini.get("section.string").or("-1"); assertEquals(two, "2"); // Test overwriting a value that already exists ini.put("section.string", "3"); final String three = ini.get("section.string").or("-1"); assertEquals(three, "3"); } @Test public void testGlobal() { final File userhome = tempFolder.newFolder("mockUserHomeDir"); final Platform platform = mock(Platform.class); when(platform.getUserHome()).thenReturn(userhome); final ConfigDatabase ini = new IniFileConfigDatabase(platform); // Test integer and string ini.putGlobal("section.int", 1); ini.putGlobal("section.string", "2"); final int one = ini.getGlobal("section.int", int.class).or(-1); assertEquals(one, 1); final String two = ini.getGlobal("section.string").or("-1"); assertEquals(two, "2"); // Test overwriting a value that already exists ini.putGlobal("section.string", "3"); final String three = ini.getGlobal("section.string").or("-1"); assertEquals(three, "3"); } @Test public void testNoDot() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); tempFolder.newFolder("mockWorkingDir/.geogit"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); exception.expect(ConfigException.class); ini.get("nodot"); } @Test public void testNoSection() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); tempFolder.newFolder("mockWorkingDir/.geogit"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); exception.expect(ConfigException.class); ini.get(".int"); } @Test public void testNoKey() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); tempFolder.newFolder("mockWorkingDir/.geogit"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); exception.expect(ConfigException.class); ini.get("section."); } @Test public void testNoRepository() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); exception.expect(ConfigException.class); ini.put("section.int", 1); } @Test public void testNoUserHome() { final Platform platform = mock(Platform.class); when(platform.getUserHome()).thenReturn(null); final ConfigDatabase ini = new IniFileConfigDatabase(platform); exception.expect(ConfigException.class); ini.putGlobal("section.int", 1); } @Test public void testNullSectionKeyPair() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); tempFolder.newFolder("mockWorkingDir/.geogit"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); exception.expect(ConfigException.class); ini.get(null); } @Test public void testNullValue() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); tempFolder.newFolder("mockWorkingDir/.geogit"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); ini.put("section.null", null); Optional<String> str = ini.get("section.null"); assertFalse(str.isPresent()); } @Test public void testNumberFormatException() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); tempFolder.newFolder("mockWorkingDir/.geogit"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); ini.put("section.string", "notanumber"); exception.expect(IllegalArgumentException.class); ini.get("section.string", int.class); } @Test public void testNoValue() { final File workingDir = tempFolder.newFolder("mockWorkingDir"); tempFolder.newFolder("mockWorkingDir/.geogit"); final Platform platform = mock(Platform.class); when(platform.pwd()).thenReturn(workingDir); final ConfigDatabase ini = new IniFileConfigDatabase(platform); Optional<String> str = ini.get("doesnt.exist"); assertFalse(str.isPresent()); } }
markles/GeoGit
src/core/src/test/java/org/geogit/storage/fs/IniFileConfigDatabaseTest.java
Java
bsd-3-clause
6,742
/** * Copyright 2011 Mark ter Maat, Human Media Interaction, University of Twente. * All rights reserved. This program is distributed under the BSD License. */ package hmi.flipper.behaviourselection; import hmi.flipper.behaviourselection.template.Template; import hmi.flipper.behaviourselection.template.TemplateState; import hmi.flipper.behaviourselection.template.effects.Effect; import hmi.flipper.behaviourselection.template.effects.Update; import hmi.flipper.defaultInformationstate.DefaultRecord; import hmi.flipper.exceptions.TemplateRunException; import java.io.IOException; import java.util.ArrayList; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * The TemplateController, as the name suggests, controls Templates. * It is given 1 or more TemplateFiles, uses this to create a list of Templates, and when asked (with a given InformationState), * it checks all Templates and selects a Template to execute. * * It will only execute 1 Template which has a Behaviour, but Templates without Behaviours (InformationState updates), * are always executed. * * @author Mark ter Maat * @version 0.1 * */ public class TemplateController { private static final int RECENCY_SIZE = 5; private static final boolean SHOW_EFFECT_CONFLICTS = false; private static final double HISTORY_MODIFIER = 0.1; /* The TemplateParser to parse Template-files */ private TemplateParser templateParser = new TemplateParser(); /* A list of classes which contain user-specified functions */ private ArrayList<Object> functionClasses = new ArrayList<Object>(); /* A list with all Templates it knows */ protected ArrayList<Template> templates = new ArrayList<Template>(); /* A list with recently executed Templates with Behaviour */ private ArrayList<String> recentRunTemplates = new ArrayList<String>(); protected DefaultRecord internalIS; /** * Creates a new TemplateController */ public TemplateController( boolean useInternalIS ) { if( useInternalIS ) { internalIS = new DefaultRecord(); } else { internalIS = null; } } /** * Creates a new TemplateController */ public TemplateController() { this(false); } /** * Processes the given TemplateFile, asks the parser to Parse it, and adds the returned list of Templates to its own list. * * @param templateFile - the Template-filename * @return true if the parsing was successful, and false if it wasn't. */ public boolean processTemplateFile( String templateFile ) { if( templateFile.length() == 0 ) return false; try { ArrayList<Template> lijst = templateParser.parseFile(templateFile); if( lijst != null ) templates.addAll(lijst); else return false; }catch( ParserConfigurationException e ) { e.printStackTrace(); return false; // TODO: Handle exception }catch( SAXException e ) { e.printStackTrace(); return false; // TODO: Handle exception }catch( IOException e ) { e.printStackTrace(); return false; // TODO: Handle exception } return true; } /** * Given an InformationState, check all known Templates and select 0, 1, or more to execute. * If no Templates are found with all Preconditions fulfilled, none will be executed. * It a Template has all Preconditions except the Triggers fulfilled and contains a Behaviour, this Behaviour will be prepared. * Only 1 Template with a Behaviour will be executed with each call. * Templates without a Behaviour (IS-updates) are always executed. * * @param is - the current InformationState. * @return true if everything went correctly, false if an error occurred. */ public boolean checkTemplates( DefaultRecord is ) { /* Lists of Templates which are only IS-updates, templates that should be prepared, and templates that could be executed */ ArrayList<TemplateState> isUpdates = new ArrayList<TemplateState>(); ArrayList<TemplateState> templatesToPrepare = new ArrayList<TemplateState>(); ArrayList<TemplateState> templatesToRun = new ArrayList<TemplateState>(); /* Check all Templates */ for( Template template : templates ) { TemplateState state = template.checkTemplate(is); if( state.isComparesSatisfied() && state.isIndicatorsSatisfied() ) { if( state.isTriggersSatisfied() ) { if( state.getEffects().size() > 0 && state.getBehaviour() == null ) { isUpdates.add(state); } else { templatesToRun.add(state); } } else if( state.getBehaviour() != null ) { templatesToPrepare.add(state); } } } if( templatesToRun.size() > 0 ) { if( templatesToRun.size() == 1 ) { /* If there is only 1 Template to run, check for conflicting Effects, apply the Effects, and run the Behaviour */ TemplateState state = templatesToRun.get(0); checkConflictingEffects(state.getEffects(),isUpdates); for( Effect effect : state.getEffects() ) { try { effect.apply(is, this); }catch( TemplateRunException e ) { System.err.println("Error while applying effect of Template " +state.getTemplate().getId()+"("+state.getTemplate().getName()+")"); e.printStackTrace(); return false; } } try { state.getBehaviour().execute(is); }catch( TemplateRunException e ) { System.err.println("Error while executing behaviour of Template " +state.getTemplate().getId()+"("+state.getTemplate().getName()+")"); e.printStackTrace(); return false; } addRecentBehaviour(state); } else { /* If there are more than 1 Template to run, select one, heck for conflicting Effects, apply the Effects, and run the selected Behaviour */ /* Modify the quality-values based on the history */ templatesToRun = modifyQualityBasedOnHistory( templatesToRun ); /* Select the Behaviour with the highest quality-value */ TemplateState state = getBestTemplate( templatesToRun ); if(state == null){ state = templatesToRun.get(0); // if failed to find best template, pick first }if(state == null){ System.err.println("Could not select best behaviour to run."); return false; } checkConflictingEffects(state.getEffects(),isUpdates); for( Effect effect : state.getEffects() ) { try { effect.apply(is, this); }catch( TemplateRunException e ) { System.err.println("Error while applying effect of Template " +state.getTemplate().getId()+"("+state.getTemplate().getName()+")"); e.printStackTrace(); return false; } } try { state.getBehaviour().execute(is); }catch( TemplateRunException e ) { System.err.println("Error while executing behaviour of Template " +state.getTemplate().getId()+"("+state.getTemplate().getName()+")"); e.printStackTrace(); return false; } addRecentBehaviour(state); } } else { /* If there are no Behaviours to execute, check for conflicting Effects, * apply the Effects, and prepare the Behaviours that can be prepared */ for( TemplateState state : templatesToPrepare ) { try { state.getBehaviour().prepare(is); }catch( TemplateRunException e ) { System.err.println("Error while preparing behaviour of Template " +state.getTemplate().getId()+"("+state.getTemplate().getName()+")"); e.printStackTrace(); return false; } } checkConflictingEffects(new ArrayList<Effect>(),isUpdates); } /* Apply all Effects of the IS-update Templates */ for( TemplateState state : isUpdates ) { // System.out.println("Running template-update: " + state.getTemplate().getName()); for( Effect effect : state.getEffects() ) { try { effect.apply(is, this); }catch( TemplateRunException e ) { System.err.println("Error while applying effect of Template "+state.getTemplate().getId()+"("+state.getTemplate().getName()+")"); e.printStackTrace(); return false; } } } return true; } public void checkTemplates() { if( internalIS != null ) { checkTemplates(internalIS); } } /** * Update the list of recently executed Behaviours, based on the given TemplateState * @param state */ public void addRecentBehaviour( TemplateState state ) { recentRunTemplates.add(state.getTemplate().getId()); if( recentRunTemplates.size() > RECENCY_SIZE ) { recentRunTemplates.remove(0); } } /** * Searches all given Effects for conflicting Effects, that is, Effects that modify the exact same variable in the InformationState * * @param effects1 * @param states */ private void checkConflictingEffects( ArrayList<Effect> effects1, ArrayList<TemplateState> states ) { ArrayList<String> names = new ArrayList<String>(); for( Effect effect : effects1 ) { if( effect instanceof Update ) { Update u = (Update)effect; String name = u.getName(); if( !names.contains(name) ) { names.add(name); } else { if( SHOW_EFFECT_CONFLICTS ) { System.out.println( "Warning, conflicting InformationState updates, may cause possible unexpected behaviour." ); } } } } for( TemplateState state : states ) { for( Effect effect : state.getEffects() ) { if( effect instanceof Update ) { Update u = (Update)effect; String name = u.getName(); if( !names.contains(name) ) { names.add(name); } else { if( SHOW_EFFECT_CONFLICTS ) { System.out.println( "Warning, conflicting InformationState updates, may cause possible unexpected behaviour." ); } } } } } } /** * Modifies the quality-value of the given TemplateStates based on the behaviour history. * The more recent a certain Behaviour was executed, the more its quality-value will be decreased. * * @param states * @return */ public ArrayList<TemplateState> modifyQualityBasedOnHistory( ArrayList<TemplateState> states ) { for( TemplateState state : states ) { String id = state.getTemplate().getId(); if( recentRunTemplates.contains(id) ) { int index = recentRunTemplates.indexOf(id); state.setQuality(state.getQuality() - ((index+1)*HISTORY_MODIFIER)); } } return states; } /** * Returns the TemplateState which includes the Behaviour with the highest quality-value * @param states * @return */ public TemplateState getBestTemplate( ArrayList<TemplateState> states ) { TemplateState bestState = null; double quality = Double.MIN_VALUE; for( TemplateState state : states ) { if( state.getQuality() > quality ) { quality = state.getQuality(); bestState = state; } } return bestState; } /** * Adds the given Object to the list of classes that contains user-specified functions. * @param obj */ public void addFunction( Object obj) { functionClasses.add(obj); } /** * @return the list of classes tha contain user-specified functions. */ public ArrayList<Object> getFunctionClasses() { return functionClasses; } /** * @return the internal InformationState (could be null) */ public DefaultRecord getIS() { return internalIS; } }
ARIA-VALUSPA/Flipper
src/main/java/hmi/flipper/behaviourselection/TemplateController.java
Java
bsd-3-clause
13,493
package abi43_0_0.expo.modules.medialibrary; import android.content.Context; import android.os.AsyncTask; import android.provider.MediaStore.Images.Media; import abi43_0_0.expo.modules.core.Promise; import static abi43_0_0.expo.modules.medialibrary.MediaLibraryUtils.queryAssetInfo; class GetAssetInfo extends AsyncTask<Void, Void, Void> { private final Context mContext; private final String mAssetId; private final Promise mPromise; public GetAssetInfo(Context context, String assetId, Promise promise) { mContext = context; mAssetId = assetId; mPromise = promise; } @Override protected Void doInBackground(Void... params) { final String selection = Media._ID + "=?"; final String[] selectionArgs = {mAssetId}; queryAssetInfo(mContext, selection, selectionArgs, true, mPromise); return null; } }
exponentjs/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/medialibrary/GetAssetInfo.java
Java
bsd-3-clause
848
/*L * Copyright Moxie Informatics. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/calims/LICENSE.txt for details. */ /** * */ package gov.nih.nci.calims2.ui.administration.namingconvention; import gov.nih.nci.calims2.domain.administration.enumeration.NamingConventionType; /** * Helper interface to get naming conventions for controllers that need naming convention validation in the UI. * * @author viseem * */ public interface NamingConventionHelper { /** * Get the naming conventions as a json string. * * @param type The type of entity * @return The applicable naming conventions as a json object */ String getNamingConventions(NamingConventionType type); }
NCIP/calims
calims2-webapp/src/java/gov/nih/nci/calims2/ui/administration/namingconvention/NamingConventionHelper.java
Java
bsd-3-clause
742
package org.gearman; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import org.gearman.GearmanClient.SubmitCallbackResult; import org.gearman.GearmanJob.Priority; import org.gearman.JobServerPoolAbstract.ConnectionController; import org.gearman.core.GearmanCallbackResult; import org.gearman.core.GearmanConnection; import org.gearman.core.GearmanPacket; import org.gearman.core.GearmanConstants; import org.gearman.util.ByteArray; abstract class ClientConnectionController <K, C extends GearmanCallbackResult> extends ConnectionController<K, C> { private static final int RESPONCE_TIMEOUT = 19000; private static final int IDLE_TIMEOUT = 9000; private Queue<Runnable> multiplexTasks = new LinkedBlockingQueue<Runnable>(); private boolean isMultiplexing = false; /** * The set of executing jobs. The key is the job's handle and the value is the job itself */ private final ConcurrentHashMap<ByteArray, GearmanJob> jobs = new ConcurrentHashMap<ByteArray, GearmanJob>(); private ClientJobSubmission pendingJob = null; private long responceTimeout = Long.MAX_VALUE; private long idleTimeout = Long.MAX_VALUE; ClientConnectionController(final ClientImpl client, final K key) { super(client, key); } public final void timeoutCheck(long time) { if(time-this.responceTimeout>RESPONCE_TIMEOUT) { super.timeout(); } else if(this.jobs.isEmpty() && this.pendingJob==null && time-this.idleTimeout>IDLE_TIMEOUT) { this.closeServer(); } } protected final void close() { if(this.pendingJob!=null) { this.requeueJob(pendingJob); this.pendingJob = null; } Iterator<GearmanJob> it = this.jobs.values().iterator(); while(it.hasNext()) { GearmanJob job = it.next(); it.remove(); job.setResult(GearmanJobResult.DISCONNECT_FAIL); } this.responceTimeout = Long.MAX_VALUE; this.idleTimeout = Long.MAX_VALUE; } protected abstract ClientJobSubmission pollNextJob(); protected abstract void requeueJob(ClientJobSubmission jobSub); protected abstract Gearman getGearman(); protected final boolean grab() { final ClientJobSubmission jobSub; synchronized(this) { if(this.pendingJob!=null) return false; jobSub = this.pollNextJob(); if(jobSub!=null) this.pendingJob = jobSub; else return false; } GearmanJob job = jobSub.job; final Priority p = job.getJobPriority(); final String funcName = job.getFunctionName(); final byte[] uID = job.getUniqueID(); final byte[] data = job.getJobData(); if(jobSub.isBackground) { switch(p) { case LOW_PRIORITY: this.getConnection().sendPacket(GearmanPacket.createSUBMIT_JOB_LOW_BG(funcName, uID, data), null/*TODO*/); break; case HIGH_PRIORITY: this.getConnection().sendPacket(GearmanPacket.createSUBMIT_JOB_HIGH_BG(funcName, uID, data), null/*TODO*/); break; case NORMAL_PRIORITY: this.getConnection().sendPacket(GearmanPacket.createSUBMIT_JOB_BG(funcName, uID, data), null/*TODO*/); break; } } else { switch(p) { case LOW_PRIORITY: this.getConnection().sendPacket(GearmanPacket.createSUBMIT_JOB_LOW(funcName, uID, data), null/*TODO*/); break; case HIGH_PRIORITY: this.getConnection().sendPacket(GearmanPacket.createSUBMIT_JOB_HIGH(funcName, uID, data), null/*TODO*/); break; case NORMAL_PRIORITY: this.getConnection().sendPacket(GearmanPacket.createSUBMIT_JOB(funcName, uID, data), null/*TODO*/); break; } } return true; } @Override public void onPacketReceived(GearmanPacket packet, GearmanConnection<Object> conn) { switch (packet.getPacketType()) { case JOB_CREATED: jobCreated(packet); break; case WORK_STATUS: workStatus(packet); break; case WORK_COMPLETE: workComplete(packet); break; case WORK_FAIL: workFail(packet); break; case ECHO_RES: // Not used assert false; break; case ERROR: error(packet); break; case STATUS_RES: super.onStatusReceived(packet); break; case WORK_EXCEPTION: //workException(packet); //TODO Don't implement yet assert false; break; case OPTION_RES: //TODO break; case WORK_DATA: workData(packet); break; case WORK_WARNING: workWarning(packet); break; default: // Not a client response assert false; } } private final void workWarning(final GearmanPacket packet) { final ByteArray jobHandle = new ByteArray(packet.getArgumentData(0)); final GearmanJob job = this.jobs.get(jobHandle); if(job==null) { // TODO log warning return; } final byte[] warning = packet.getArgumentData(1); Runnable task = new Runnable() { @Override public void run() { try { job.callbackWarning(warning); } catch (Throwable t) { // If the user throws an exception, catch it, print it, and continue. t.printStackTrace(); } finally { taskNext(); } } }; taskAdd(task); } private final void workData(final GearmanPacket packet) { final ByteArray jobHandle = new ByteArray(packet.getArgumentData(0)); final GearmanJob job = this.jobs.get(jobHandle); if(job==null) { // TODO log warning return; } final byte[] data= packet.getArgumentData(1); Runnable task = new Runnable() { @Override public void run() { try { job.callbackData(data); } catch (Throwable t) { // If the user throws an exception, catch it, print it, and continue. t.printStackTrace(); } finally { taskNext(); } } }; taskAdd(task); } /* private final void workException(final GearmanPacket packet) { final ByteArray jobHandle = new ByteArray(packet.getArgumentData(0)); final GearmanJob job = this.jobs.get(jobHandle); if(job==null) { // TODO log warning return; } final byte[] exception = packet.getArgumentData(1); try { job.callbackException(exception); } catch (Throwable t) { // If the user throws an exception, catch it, print it, and continue. t.printStackTrace(); } } */ private final void workFail(final GearmanPacket packet) { final ByteArray jobHandle = new ByteArray(packet.getArgumentData(0)); /* * Note: synchronization is not needed here. */ final GearmanJob job = this.jobs.remove(jobHandle); if(this.jobs.isEmpty()) { this.idleTimeout = System.currentTimeMillis(); } if(job==null) { // TODO log warning return; } Runnable task = new Runnable() { @Override public void run() { try { job.setResult(GearmanJobResult.WORKER_FAIL); } catch (Throwable t) { // If the user throws an exception, catch it, print it, and continue. t.printStackTrace(); } finally { taskNext(); } } }; taskAdd(task); } private final void jobCreated(final GearmanPacket packet) { final ClientJobSubmission jobSub; synchronized(this.jobs) { assert this.pendingJob!=null; jobSub = this.pendingJob; assert jobSub!=null; assert jobSub.job!=null; this.pendingJob = null; } jobSub.onSubmissionComplete(SubmitCallbackResult.SUBMIT_SUCCESSFUL); if(!jobSub.isBackground) { final ByteArray jobHandle = new ByteArray(packet.getArgumentData(0)); jobSub.job.setConnection(this, jobHandle); this.jobs.put(jobHandle, jobSub.job); } this.grab(); } private final void workStatus(final GearmanPacket packet) { final ByteArray jobHandle = new ByteArray(packet.getArgumentData(0)); final GearmanJob job = ClientConnectionController.this.jobs.get(jobHandle); if(job==null) { // TODO log warning return; } try { final long numerator = Long.parseLong(new String(packet.getArgumentData(1),GearmanConstants.UTF_8)); final long denominator = Long.parseLong(new String(packet.getArgumentData(2),GearmanConstants.UTF_8)); Runnable task = new Runnable() { @Override public void run() { try { job.callbackStatus(numerator, denominator); } catch (Throwable t) { // If the user throws an exception, catch it, print it, and continue. t.printStackTrace(); } finally { taskNext(); } } }; taskAdd(task); } catch (NumberFormatException nfe) { // TODO log error } } private final void taskAdd(Runnable task) { synchronized(this.multiplexTasks) { if(this.isMultiplexing) this.multiplexTasks.add(task); else { this.isMultiplexing = true; ClientConnectionController.this.getGearman().getPool().execute(task); } } } private final void taskNext() { synchronized(this.multiplexTasks) { Runnable task = this.multiplexTasks.poll(); if(task==null) { this.isMultiplexing = false; return; } else { ClientConnectionController.this.getGearman().getPool().execute(task); } } } private final void workComplete(final GearmanPacket packet) { final ByteArray jobHandle = new ByteArray(packet.getArgumentData(0)); /* * Note: synchronization is not needed here. */ final GearmanJob job = this.jobs.remove(jobHandle); if(this.jobs.isEmpty()) { this.idleTimeout = System.currentTimeMillis(); } if(job==null) { //TODO log warning return; } final byte[] data = packet.getArgumentData(1); Runnable task = new Runnable() { @Override public void run() { try { job.setResult(GearmanJobResult.workSuccessful(data)); } catch (Throwable t) { // If the user throws an exception, catch it, print it, and continue. t.printStackTrace(); } finally { taskNext(); } } }; taskAdd(task); } private final void error(final GearmanPacket packet) { //TODO log error } }
fwix/java-gearman
src/org/gearman/ClientConnectionController.java
Java
bsd-3-clause
9,737
package net.njcull.collections; import org.junit.Assert; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; /** * Tests for ImmutableArrayMap. * * @author run2000 * @version 8/01/2016. */ public final class TestImmutableArrayMap { @Test public void testEmptyMap() throws Exception { ImmutableArrayMap<String, String> test = ImmutableArrayMap.<String, String>builder().build(); Assert.assertFalse(test.containsKey("3")); Assert.assertSame(test, ImmutableArrayMap.emptyMap()); Assert.assertTrue(test.isEmpty()); Assert.assertEquals(0, test.size()); Assert.assertEquals("{}", test.toString()); Assert.assertEquals(0, test.hashCode()); ArrayBackedCollection<String> keys = test.keySet(); Assert.assertEquals("[]", keys.toString()); Assert.assertEquals(0, keys.hashCode()); Assert.assertEquals(1, keys.asList().hashCode()); } @Test public void testCollector() throws Exception { HashMap<String, String> map1 = new HashMap<>(); map1.put("a", "ac"); map1.put("b", "bc"); map1.put("c", "cc"); map1.put("d", "dx"); map1.put("e", "ec"); map1.put("f", "fc"); map1.put("g", "gc"); map1.put("m", "0ma"); map1.put("n", "0na"); map1.put("o", "Zoa"); map1.put("p", "Zpa"); ImmutableArrayMap<String, String> result = map1.entrySet().stream() .filter(p -> p.getValue().charAt(1) != 'x') .collect(Collectors.toImmutableArrayMap()); Assert.assertEquals(10, result.size()); // Assert.assertEquals("{a=ac, b=bc, c=cc, e=ec, f=fc, g=gc, m=0ma, n=0na, o=Zoa, p=Zpa}", result.toString()); Assert.assertTrue(result.indexOfKey("a") >= 0); Assert.assertTrue(result.indexOfKey("b") >= 0); Assert.assertTrue(result.indexOfKey("c") >= 0); Assert.assertTrue(result.indexOfKey("e") >= 0); Assert.assertTrue(result.indexOfKey("f") >= 0); Assert.assertTrue(result.indexOfKey("g") >= 0); Assert.assertTrue(result.indexOfKey("m") >= 0); Assert.assertTrue(result.indexOfKey("n") >= 0); Assert.assertTrue(result.indexOfKey("o") >= 0); Assert.assertTrue(result.indexOfKey("p") >= 0); Assert.assertFalse(result.indexOfKey("0") >= 0); Assert.assertFalse(result.indexOfKey(null) >= 0); Assert.assertTrue(result.containsKey("a")); Assert.assertTrue(result.containsKey("b")); Assert.assertTrue(result.containsKey("c")); Assert.assertFalse(result.containsKey("d")); Assert.assertTrue(result.containsKey("e")); Assert.assertTrue(result.containsKey("f")); Assert.assertTrue(result.containsKey("g")); Assert.assertTrue(result.containsKey("m")); Assert.assertTrue(result.containsKey("n")); Assert.assertTrue(result.containsKey("o")); Assert.assertTrue(result.containsKey("p")); Assert.assertFalse(result.containsKey("0")); Assert.assertFalse(result.containsKey(null)); Assert.assertTrue(result.containsValue("ac")); Assert.assertTrue(result.containsValue("bc")); Assert.assertTrue(result.containsValue("cc")); Assert.assertFalse(result.containsValue("dx")); Assert.assertTrue(result.containsValue("ec")); Assert.assertTrue(result.containsValue("fc")); Assert.assertTrue(result.containsValue("gc")); Assert.assertTrue(result.containsValue("0ma")); Assert.assertTrue(result.containsValue("0na")); Assert.assertTrue(result.containsValue("Zoa")); Assert.assertTrue(result.containsValue("Zpa")); Assert.assertFalse(result.containsValue("0")); Assert.assertFalse(result.containsValue(null)); Assert.assertTrue(result.indexOfValue("ac") >= 0); Assert.assertTrue(result.indexOfValue("bc") >= 0); Assert.assertTrue(result.indexOfValue("cc") >= 0); Assert.assertTrue(result.indexOfValue("ec") >= 0); Assert.assertTrue(result.indexOfValue("fc") >= 0); Assert.assertTrue(result.indexOfValue("gc") >= 0); Assert.assertTrue(result.indexOfValue("0ma") >= 0); Assert.assertTrue(result.indexOfValue("0na") >= 0); Assert.assertTrue(result.indexOfValue("Zoa") >= 0); Assert.assertTrue(result.indexOfValue("Zpa") >= 0); Assert.assertFalse(result.indexOfValue("0") >= 0); Assert.assertFalse(result.indexOfValue(null) >= 0); Assert.assertTrue(result.lastIndexOfValue("ac") >= 0); Assert.assertTrue(result.lastIndexOfValue("bc") >= 0); Assert.assertTrue(result.lastIndexOfValue("cc") >= 0); Assert.assertTrue(result.lastIndexOfValue("ec") >= 0); Assert.assertTrue(result.lastIndexOfValue("fc") >= 0); Assert.assertTrue(result.lastIndexOfValue("gc") >= 0); Assert.assertTrue(result.lastIndexOfValue("0ma") >= 0); Assert.assertTrue(result.lastIndexOfValue("0na") >= 0); Assert.assertTrue(result.lastIndexOfValue("Zoa") >= 0); Assert.assertTrue(result.lastIndexOfValue("Zpa") >= 0); Assert.assertFalse(result.lastIndexOfValue("0") >= 0); Assert.assertFalse(result.lastIndexOfValue(null) >= 0); Assert.assertEquals("ac", result.get("a")); Assert.assertEquals("bc", result.get("b")); Assert.assertEquals("cc", result.get("c")); Assert.assertEquals("ec", result.get("e")); Assert.assertEquals("fc", result.get("f")); Assert.assertEquals("gc", result.get("g")); Assert.assertEquals("0ma", result.get("m")); Assert.assertEquals("0na", result.get("n")); Assert.assertEquals("Zoa", result.get("o")); Assert.assertEquals("Zpa", result.get("p")); Assert.assertSame(null, result.get("0")); Assert.assertSame(null, result.get(null)); ArrayBackedSet<Map.Entry<String, String>> entrySet = result.entrySet(); Iterator<Map.Entry<String, String>> entryIt = entrySet.iterator(); Assert.assertTrue(entryIt.hasNext()); Assert.assertEquals(10, result.size()); } @Test public void testSplitter() throws Exception { HashMap<String, String> map1 = new HashMap<>(); map1.put("a", "ac"); map1.put("b", "bc"); map1.put("c", "cc"); map1.put("d", "dx"); map1.put("e", "ec"); map1.put("f", "fc"); map1.put("g", "gc"); map1.put("m", "0ma"); map1.put("n", "0na"); map1.put("o", "Zoa"); map1.put("p", "Zpa"); ImmutableArrayMap<String, String> result1 = map1.entrySet().stream() .filter(p -> p.getValue().charAt(1) != 'x') .collect(Collectors.toImmutableArrayMap()); Assert.assertEquals(10, result1.size()); // Stream the results from one map, collect back to another ImmutableArrayMap<String, String> result2 = result1.entrySet().parallelStream() .collect(Collectors.toImmutableArrayMap()); Assert.assertTrue(result2.indexOfKey("a") >= 0); Assert.assertTrue(result2.indexOfKey("b") >= 0); Assert.assertTrue(result2.indexOfKey("c") >= 0); Assert.assertTrue(result2.indexOfKey("e") >= 0); Assert.assertTrue(result2.indexOfKey("f") >= 0); Assert.assertTrue(result2.indexOfKey("g") >= 0); Assert.assertTrue(result2.indexOfKey("m") >= 0); Assert.assertTrue(result2.indexOfKey("n") >= 0); Assert.assertTrue(result2.indexOfKey("o") >= 0); Assert.assertTrue(result2.indexOfKey("p") >= 0); Assert.assertFalse(result2.indexOfKey("0") >= 0); Assert.assertFalse(result2.indexOfKey(null) >= 0); Assert.assertTrue(result2.containsKey("a")); Assert.assertTrue(result2.containsKey("b")); Assert.assertTrue(result2.containsKey("c")); Assert.assertFalse(result2.containsKey("d")); Assert.assertTrue(result2.containsKey("e")); Assert.assertTrue(result2.containsKey("f")); Assert.assertTrue(result2.containsKey("g")); Assert.assertTrue(result2.containsKey("m")); Assert.assertTrue(result2.containsKey("n")); Assert.assertTrue(result2.containsKey("o")); Assert.assertTrue(result2.containsKey("p")); Assert.assertFalse(result2.containsKey("0")); Assert.assertFalse(result2.containsKey(null)); Assert.assertTrue(result2.containsValue("ac")); Assert.assertTrue(result2.containsValue("bc")); Assert.assertTrue(result2.containsValue("cc")); Assert.assertFalse(result2.containsValue("dx")); Assert.assertTrue(result2.containsValue("ec")); Assert.assertTrue(result2.containsValue("fc")); Assert.assertTrue(result2.containsValue("gc")); Assert.assertTrue(result2.containsValue("0ma")); Assert.assertTrue(result2.containsValue("0na")); Assert.assertTrue(result2.containsValue("Zoa")); Assert.assertTrue(result2.containsValue("Zpa")); Assert.assertFalse(result2.containsValue("0")); Assert.assertFalse(result2.containsValue(null)); Assert.assertTrue(result2.indexOfValue("ac") >= 0); Assert.assertTrue(result2.indexOfValue("bc") >= 0); Assert.assertTrue(result2.indexOfValue("cc") >= 0); Assert.assertTrue(result2.indexOfValue("ec") >= 0); Assert.assertTrue(result2.indexOfValue("fc") >= 0); Assert.assertTrue(result2.indexOfValue("gc") >= 0); Assert.assertTrue(result2.indexOfValue("0ma") >= 0); Assert.assertTrue(result2.indexOfValue("0na") >= 0); Assert.assertTrue(result2.indexOfValue("Zoa") >= 0); Assert.assertTrue(result2.indexOfValue("Zpa") >= 0); Assert.assertFalse(result2.indexOfValue("0") >= 0); Assert.assertFalse(result2.indexOfValue(null) >= 0); Assert.assertTrue(result2.lastIndexOfValue("ac") >= 0); Assert.assertTrue(result2.lastIndexOfValue("bc") >= 0); Assert.assertTrue(result2.lastIndexOfValue("cc") >= 0); Assert.assertTrue(result2.lastIndexOfValue("ec") >= 0); Assert.assertTrue(result2.lastIndexOfValue("fc") >= 0); Assert.assertTrue(result2.lastIndexOfValue("gc") >= 0); Assert.assertTrue(result2.lastIndexOfValue("0ma") >= 0); Assert.assertTrue(result2.lastIndexOfValue("0na") >= 0); Assert.assertTrue(result2.lastIndexOfValue("Zoa") >= 0); Assert.assertTrue(result2.lastIndexOfValue("Zpa") >= 0); Assert.assertFalse(result2.lastIndexOfValue("0") >= 0); Assert.assertFalse(result2.lastIndexOfValue(null) >= 0); Assert.assertEquals("ac", result2.get("a")); Assert.assertEquals("bc", result2.get("b")); Assert.assertEquals("cc", result2.get("c")); Assert.assertEquals("ec", result2.get("e")); Assert.assertEquals("fc", result2.get("f")); Assert.assertEquals("gc", result2.get("g")); Assert.assertEquals("0ma", result2.get("m")); Assert.assertEquals("0na", result2.get("n")); Assert.assertEquals("Zoa", result2.get("o")); Assert.assertEquals("Zpa", result2.get("p")); Assert.assertSame(null, result2.get("0")); Assert.assertSame(null, result2.get(null)); ArrayBackedSet<Map.Entry<String, String>> entrySet = result2.entrySet(); Iterator<Map.Entry<String, String>> entryIt = entrySet.iterator(); Assert.assertTrue(entryIt.hasNext()); Assert.assertEquals(10, result2.size()); } @Test public void testKeySplitter() throws Exception { ImmutableArrayMapBuilder<String, String> builder = new ImmutableArrayMapBuilder<>(); builder.with("a", "ac"); builder.with("b", "bc"); builder.with("c", "cc"); builder.with("e", "ec"); builder.with("f", "fc"); builder.with("g", "gc"); builder.with("m", "0ma"); builder.with("n", "0na"); builder.with("o", "Zoa"); builder.with("p", "Zpa"); ImmutableArrayMap<String, String> result1 = builder.build(); Assert.assertEquals(10, builder.size()); builder.clear(); Assert.assertEquals(0, builder.size()); Assert.assertEquals(10, result1.size()); Assert.assertEquals("{a=ac, b=bc, c=cc, e=ec, f=fc, g=gc, m=0ma, n=0na, o=Zoa, p=Zpa}", result1.toString()); // Stream the results from one map, collect back to a result list ArrayList<String> result2 = result1.keySet().parallelStream() .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); Assert.assertEquals(10, result2.size()); Assert.assertEquals("[a, b, c, e, f, g, m, n, o, p]", result2.toString()); Assert.assertEquals(0, result2.indexOf("a")); Assert.assertEquals(1,result2.indexOf("b")); Assert.assertEquals(2, result2.indexOf("c")); Assert.assertEquals(3, result2.indexOf("e")); Assert.assertEquals(4, result2.indexOf("f")); Assert.assertEquals(5, result2.indexOf("g")); Assert.assertEquals(6, result2.indexOf("m")); Assert.assertEquals(7, result2.indexOf("n")); Assert.assertEquals(8, result2.indexOf("o")); Assert.assertEquals(9, result2.indexOf("p")); Assert.assertEquals(-1, result2.indexOf("0")); Assert.assertEquals(-1, result2.indexOf(null)); Assert.assertTrue(result2.contains("a")); Assert.assertTrue(result2.contains("b")); Assert.assertTrue(result2.contains("c")); Assert.assertFalse(result2.contains("d")); Assert.assertTrue(result2.contains("e")); Assert.assertTrue(result2.contains("f")); Assert.assertTrue(result2.contains("g")); Assert.assertTrue(result2.contains("m")); Assert.assertTrue(result2.contains("n")); Assert.assertTrue(result2.contains("o")); Assert.assertTrue(result2.contains("p")); Assert.assertFalse(result2.contains("0")); Assert.assertFalse(result2.contains(null)); } @Test public void testValueSplitter() throws Exception { ImmutableArrayMapBuilder<String, String> builder = new ImmutableArrayMapBuilder<>(); builder.with("a", "ac"); builder.with("b", "bc"); builder.with("c", "cc"); builder.with("e", "ec"); builder.with("f", "fc"); builder.with("g", "gc"); builder.with("m", "0ma"); builder.with("n", "0na"); builder.with("o", "Zoa"); builder.with("p", "Zpa"); ImmutableArrayMap<String, String> result1 = builder.build(); Assert.assertEquals(10, builder.size()); builder.clear(); Assert.assertEquals(0, builder.size()); Assert.assertEquals(10, result1.size()); Assert.assertEquals("{a=ac, b=bc, c=cc, e=ec, f=fc, g=gc, m=0ma, n=0na, o=Zoa, p=Zpa}", result1.toString()); // Stream the results from one map, collect back to a result list ArrayList<String> result2 = result1.values().parallelStream() .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); Assert.assertEquals(10, result2.size()); Assert.assertEquals("[ac, bc, cc, ec, fc, gc, 0ma, 0na, Zoa, Zpa]", result2.toString()); Assert.assertTrue(result2.contains("ac")); Assert.assertTrue(result2.contains("bc")); Assert.assertTrue(result2.contains("cc")); Assert.assertFalse(result2.contains("dx")); Assert.assertTrue(result2.contains("ec")); Assert.assertTrue(result2.contains("fc")); Assert.assertTrue(result2.contains("gc")); Assert.assertTrue(result2.contains("0ma")); Assert.assertTrue(result2.contains("0na")); Assert.assertTrue(result2.contains("Zoa")); Assert.assertTrue(result2.contains("Zpa")); Assert.assertFalse(result2.contains("0")); Assert.assertFalse(result2.contains(null)); Assert.assertEquals(0, result2.indexOf("ac")); Assert.assertEquals(1, result2.indexOf("bc")); Assert.assertEquals(2, result2.indexOf("cc")); Assert.assertEquals(3, result2.indexOf("ec")); Assert.assertEquals(4, result2.indexOf("fc")); Assert.assertEquals(5, result2.indexOf("gc")); Assert.assertEquals(6, result2.indexOf("0ma")); Assert.assertEquals(7, result2.indexOf("0na")); Assert.assertEquals(8, result2.indexOf("Zoa")); Assert.assertEquals(9, result2.indexOf("Zpa")); Assert.assertEquals(-1, result2.indexOf("0")); Assert.assertEquals(-1, result2.indexOf(null)); Assert.assertTrue(result2.lastIndexOf("ac") >= 0); Assert.assertTrue(result2.lastIndexOf("bc") >= 0); Assert.assertTrue(result2.lastIndexOf("cc") >= 0); Assert.assertTrue(result2.lastIndexOf("ec") >= 0); Assert.assertTrue(result2.lastIndexOf("fc") >= 0); Assert.assertTrue(result2.lastIndexOf("gc") >= 0); Assert.assertTrue(result2.lastIndexOf("0ma") >= 0); Assert.assertTrue(result2.lastIndexOf("0na") >= 0); Assert.assertTrue(result2.lastIndexOf("Zoa") >= 0); Assert.assertTrue(result2.lastIndexOf("Zpa") >= 0); Assert.assertFalse(result2.lastIndexOf("0") >= 0); Assert.assertFalse(result2.lastIndexOf(null) >= 0); } @Test public void testMerge() throws Exception { HashMap<String, String> map1 = new HashMap<>(); map1.put("a", "ac"); map1.put("b", "bc"); map1.put("c", "cc"); map1.put("d", "dx"); map1.put("e", "ec"); map1.put("f", "fc"); map1.put("g", "gc"); HashMap<String, String> map2 = new HashMap<>(); map2.put("m", "ma"); map2.put("n", "na"); map2.put("o", "oa"); map2.put("p", "pa"); ImmutableArrayMapBuilder<String, String> builder1 = new ImmutableArrayMapBuilder<>(); ImmutableArrayMapBuilder<String, String> builder2 = new ImmutableArrayMapBuilder<>(); builder1.with(map1.entrySet()); map2.entrySet().forEach(builder2::with); builder1.merge(builder2); Assert.assertEquals(4, builder2.size()); builder2.clear(); Assert.assertEquals(0, builder2.size()); ArrayBackedMap<String, String> result = builder1.build(); Assert.assertEquals(11, result.size()); } @Test public void testBuilder() throws Exception { ImmutableArrayMap<String, String> map = ImmutableArrayMap.<String, String>builder() .with("c", "5", "d", "4", "e", "3") .with("a", "7", "b", "96") .with("f", "2", "g", "1").build(); Assert.assertEquals(7, map.size()); Assert.assertFalse(map.containsKey("0")); Assert.assertEquals("7", map.get("a")); Assert.assertFalse(map.containsKey("ab")); Assert.assertFalse(map.containsKey("da")); Assert.assertEquals("1", map.get("g")); Assert.assertFalse(map.containsKey("zz")); Assert.assertEquals("5", map.getOrDefault("c", "")); Assert.assertEquals("", map.getOrDefault("z", "")); StringBuilder builder = new StringBuilder(); map.forEach((k,v) -> builder.append(k)); Assert.assertEquals("cdeabfg", builder.toString()); ArrayBackedSet<String> keySet = map.keySet(); Assert.assertFalse(keySet.isEmpty()); Assert.assertEquals(7, keySet.size()); Assert.assertEquals("[c, d, e, a, b, f, g]", keySet.toString()); Assert.assertTrue(keySet.contains("a")); Assert.assertFalse(keySet.contains("p")); List<String> elements = Arrays.asList("a", "b", "c"); Assert.assertTrue(keySet.containsAll(elements)); Assert.assertEquals("c", keySet.getAtIndex(0)); Assert.assertEquals("d", keySet.getAtIndex(1)); Assert.assertEquals("e", keySet.getAtIndex(2)); Assert.assertEquals("a", keySet.getAtIndex(3)); Assert.assertEquals("b", keySet.getAtIndex(4)); Assert.assertEquals("f", keySet.getAtIndex(5)); Assert.assertEquals("g", keySet.getAtIndex(6)); Assert.assertEquals(0, keySet.indexOf("c")); Assert.assertEquals(1, keySet.indexOf("d")); Assert.assertEquals(2, keySet.indexOf("e")); Assert.assertEquals(3, keySet.indexOf("a")); Assert.assertEquals(4, keySet.indexOf("b")); Assert.assertEquals(5, keySet.indexOf("f")); Assert.assertEquals(6, keySet.indexOf("g")); Assert.assertEquals(-1, keySet.indexOfRange("c", 2, 7)); Assert.assertEquals(-1, keySet.indexOfRange("d", 2, 7)); Assert.assertEquals(2, keySet.indexOfRange("e", 2, 7)); Assert.assertEquals(3, keySet.indexOfRange("a", 2, 7)); Assert.assertEquals(4, keySet.indexOfRange("b", 2, 7)); Assert.assertEquals(5, keySet.indexOfRange("f", 2, 7)); Assert.assertEquals(6, keySet.indexOfRange("g", 2, 7)); Assert.assertEquals(-1, keySet.indexOfRange(null, 2, 7)); // toArray() Object[] arrAct = keySet.toArray(); Object[] arrExp = new Object[] { "c", "d", "e", "a", "b", "f", "g" }; Assert.assertArrayEquals(arrExp, arrAct); // toArray(String[]) -- three cases to consider String[] arrAct1 = new String[6]; String[] arrExp1 = new String[] { "c", "d", "e", "a", "b", "f", "g" }; String[] arrAct1a = keySet.toArray(arrAct1); Assert.assertNotSame(arrAct, arrAct1); Assert.assertArrayEquals(arrExp1, arrAct1a); String[] arrAct2 = new String[7]; String[] arrAct2a = keySet.toArray(arrAct2); Assert.assertSame(arrAct2, arrAct2a); Assert.assertArrayEquals(arrExp1, arrAct2); String[] arrAct3 = new String[8]; String[] arrExp3 = new String[] { "c", "d", "e", "a", "b", "f", "g", null }; String[] arrAct3a = keySet.toArray(arrAct3); Assert.assertSame(arrAct3, arrAct3a); Assert.assertArrayEquals(arrExp3, arrAct3); // New methods in 1.8 - forEach, removeIf Assert.assertFalse(keySet.removeIf(e -> e.length() > 1)); // Key set as list List<String> keyList = keySet.asList(); Assert.assertFalse(keyList.isEmpty()); Assert.assertEquals(7, keyList.size()); Assert.assertEquals("[c, d, e, a, b, f, g]", keyList.toString()); List<String> subKeys = keyList.subList(2, 5); Assert.assertFalse(subKeys.isEmpty()); Assert.assertEquals(3, subKeys.size()); Assert.assertEquals("[e, a, b]", subKeys.toString()); ArrayBackedCollection<String> keyColl = (ArrayBackedCollection<String>)keyList; Assert.assertEquals("c", keyColl.getAtIndex(0)); Assert.assertEquals("d", keyColl.getAtIndex(1)); Assert.assertEquals("e", keyColl.getAtIndex(2)); Assert.assertEquals("a", keyColl.getAtIndex(3)); Assert.assertEquals("b", keyColl.getAtIndex(4)); Assert.assertEquals("f", keyColl.getAtIndex(5)); Assert.assertEquals("g", keyColl.getAtIndex(6)); Assert.assertEquals(3, keyColl.indexOfRange("a", 2, 5)); Assert.assertEquals(4, keyColl.indexOfRange("b", 2, 5)); Assert.assertEquals(2, keyColl.indexOfRange("e", 2, 5)); Assert.assertEquals(-1, keyColl.indexOfRange(null, 2, 5)); ArrayBackedSet<Map.Entry<String, String>> entrySet = map.entrySet(); Assert.assertFalse(entrySet.isEmpty()); Assert.assertEquals(7, entrySet.size()); Assert.assertEquals("[c=5, d=4, e=3, a=7, b=96, f=2, g=1]", entrySet.toString()); List<Map.Entry<String, String>> entryList = entrySet.asList(); Assert.assertFalse(entryList.isEmpty()); Assert.assertEquals(7, entryList.size()); Assert.assertEquals("[c=5, d=4, e=3, a=7, b=96, f=2, g=1]", entryList.toString()); ArrayBackedCollection<String> values = map.values(); Assert.assertFalse(values.isEmpty()); Assert.assertEquals(7, values.size()); Assert.assertEquals("[5, 4, 3, 7, 96, 2, 1]", values.toString()); Assert.assertTrue(values.contains("5")); Assert.assertFalse(values.contains("21")); elements = Arrays.asList("7", "5", "2"); Assert.assertTrue(values.containsAll(elements)); Assert.assertEquals("5", values.getAtIndex(0)); Assert.assertEquals("4", values.getAtIndex(1)); Assert.assertEquals("3", values.getAtIndex(2)); Assert.assertEquals("7", values.getAtIndex(3)); Assert.assertEquals("96", values.getAtIndex(4)); Assert.assertEquals("2", values.getAtIndex(5)); Assert.assertEquals("1", values.getAtIndex(6)); Assert.assertEquals(0, values.indexOf("5")); Assert.assertEquals(1, values.indexOf("4")); Assert.assertEquals(2, values.indexOf("3")); Assert.assertEquals(3, values.indexOf("7")); Assert.assertEquals(4, values.indexOf("96")); Assert.assertEquals(5, values.indexOf("2")); Assert.assertEquals(6, values.indexOf("1")); Assert.assertEquals(-1, values.indexOfRange("5", 2, 7)); Assert.assertEquals(-1, values.indexOfRange("4", 2, 7)); Assert.assertEquals(2, values.indexOfRange("3", 2, 7)); Assert.assertEquals(3, values.indexOfRange("7", 2, 7)); Assert.assertEquals(4, values.indexOfRange("96", 2, 7)); Assert.assertEquals(5, values.indexOfRange("2", 2, 7)); Assert.assertEquals(6, values.indexOfRange("1", 2, 7)); Assert.assertEquals(-1, values.indexOfRange(null, 2, 7)); // toArray() arrAct = values.toArray(); arrExp = new Object[] { "5", "4", "3", "7", "96", "2", "1" }; Assert.assertArrayEquals(arrExp, arrAct); // toArray(String[]) -- three cases to consider arrAct1 = new String[6]; arrExp1 = new String[] { "5", "4", "3", "7", "96", "2", "1" }; arrAct1a = values.toArray(arrAct1); Assert.assertNotSame(arrAct, arrAct1); Assert.assertArrayEquals(arrExp1, arrAct1a); arrAct2 = new String[7]; arrAct2a = values.toArray(arrAct2); Assert.assertSame(arrAct2, arrAct2a); Assert.assertArrayEquals(arrExp1, arrAct2); arrAct3 = new String[8]; arrExp3 = new String[] { "5", "4", "3", "7", "96", "2", "1", null }; arrAct3a = values.toArray(arrAct3); Assert.assertSame(arrAct3, arrAct3a); Assert.assertArrayEquals(arrExp3, arrAct3); Iterator<String> valIt = values.iterator(); StringBuilder builder1 = new StringBuilder(); while(valIt.hasNext()) { builder1.append(valIt.next()); if(valIt.hasNext()) { builder1.append(':'); } } Assert.assertEquals("5:4:3:7:96:2:1", builder1.toString()); // New methods in 1.8 - forEach, removeIf Assert.assertFalse(values.removeIf(e -> e.length() > 2)); // Values as list List<String> valueList = values.asList(); Assert.assertFalse(valueList.isEmpty()); Assert.assertEquals(7, valueList.size()); Assert.assertEquals("[5, 4, 3, 7, 96, 2, 1]", valueList.toString()); Assert.assertEquals(1, map.indexOfValue("4")); } @Test public void testSubMap() throws Exception { ImmutableArrayMapBuilder<String, String> builder = new ImmutableArrayMapBuilder<>(); builder.with("a", "ac"); builder.with("b", "bc"); builder.with("c", "cc"); builder.with("d", "dx"); builder.with("e", "ec"); builder.with("f", "fc"); builder.with("g", "gc"); ImmutableArrayMap<String, String> map = builder.build(); List<Map.Entry<String,String>> list = map.entrySet().asList(); List<Map.Entry<String, String>> subList = list.subList(2, 3); List<Map.Entry<String, String>> emptySubMap = list.subList(1, 1); List<Map.Entry<String, String>> fullSubMap = list.subList(0, 7); Assert.assertEquals(1, subList.size()); Assert.assertTrue(emptySubMap.isEmpty()); Assert.assertEquals(7, fullSubMap.size()); } @Test public void testCopyOf() throws Exception { HashMap<String, String> map1 = new HashMap<>(); map1.put("a", "ac"); map1.put("b", "bc"); map1.put("c", "cc"); map1.put("d", "dx"); map1.put("e", "ec"); map1.put("f", "fc"); map1.put("g", "gc"); map1.put("m", "0ma"); map1.put("n", "0na"); map1.put("o", "Zoa"); map1.put("p", "Zpa"); ImmutableArrayMap<String,String> result = ImmutableArrayMap.copyOf(map1); Assert.assertTrue(result.indexOfKey("a") >= 0); Assert.assertTrue(result.indexOfKey("b") >= 0); Assert.assertTrue(result.indexOfKey("c") >= 0); Assert.assertTrue(result.indexOfKey("e") >= 0); Assert.assertTrue(result.indexOfKey("f") >= 0); Assert.assertTrue(result.indexOfKey("g") >= 0); Assert.assertTrue(result.indexOfKey("m") >= 0); Assert.assertTrue(result.indexOfKey("n") >= 0); Assert.assertTrue(result.indexOfKey("o") >= 0); Assert.assertTrue(result.indexOfKey("p") >= 0); Assert.assertFalse(result.indexOfKey("0") >= 0); Assert.assertTrue(result.containsValue("ac")); Assert.assertTrue(result.containsValue("bc")); Assert.assertTrue(result.containsValue("cc")); Assert.assertTrue(result.containsValue("dx")); Assert.assertTrue(result.containsValue("ec")); Assert.assertTrue(result.containsValue("fc")); Assert.assertTrue(result.containsValue("gc")); Assert.assertTrue(result.containsValue("0ma")); Assert.assertTrue(result.containsValue("0na")); Assert.assertTrue(result.containsValue("Zoa")); Assert.assertTrue(result.containsValue("Zpa")); Assert.assertFalse(result.containsValue("0")); ImmutableArrayMap<String,String> result2 = ImmutableArrayMap.copyOf(result); Assert.assertSame(result, result2); SortedMap<String, String> map2 = new TreeMap<>(); map2.put("a", "ac"); map2.put("b", "bc"); map2.put("c", "cc"); map2.put("d", "dx"); map2.put("e", "ec"); map2.put("f", "fc"); map2.put("g", "gc"); map2.put("m", "0ma"); map2.put("n", "0na"); map2.put("o", "Zoa"); map2.put("p", "Zpa"); ImmutableArrayMap<String,String> result3 = ImmutableArrayMap.copyOfBiMap(map2); Assert.assertTrue(result3.indexOfKey("a") >= 0); Assert.assertTrue(result3.indexOfKey("b") >= 0); Assert.assertTrue(result3.indexOfKey("c") >= 0); Assert.assertTrue(result3.indexOfKey("e") >= 0); Assert.assertTrue(result3.indexOfKey("f") >= 0); Assert.assertTrue(result3.indexOfKey("g") >= 0); Assert.assertTrue(result3.indexOfKey("m") >= 0); Assert.assertTrue(result3.indexOfKey("n") >= 0); Assert.assertTrue(result3.indexOfKey("o") >= 0); Assert.assertTrue(result3.indexOfKey("p") >= 0); Assert.assertFalse(result3.indexOfKey("0") >= 0); Assert.assertTrue(result3.containsValue("ac")); Assert.assertTrue(result3.containsValue("bc")); Assert.assertTrue(result3.containsValue("cc")); Assert.assertTrue(result3.containsValue("dx")); Assert.assertTrue(result3.containsValue("ec")); Assert.assertTrue(result3.containsValue("fc")); Assert.assertTrue(result3.containsValue("gc")); Assert.assertTrue(result3.containsValue("0ma")); Assert.assertTrue(result3.containsValue("0na")); Assert.assertTrue(result3.containsValue("Zoa")); Assert.assertTrue(result3.containsValue("Zpa")); Assert.assertFalse(result3.containsValue("0")); ImmutableArrayMap<String,String> result4 = ImmutableArrayMap.copyOfBiMap(result3); Assert.assertSame(result3, result4); ImmutableArrayMap<String,String> result5 = ImmutableArrayMap.copyOfBiMap(result2); Assert.assertNotSame(result2, result5); } @Test public void testExceptions() throws Exception { ImmutableArrayMap<String, String> map = ImmutableArrayMap.<String, String>builder() .with("c", "5", "d", "4", "e", "3") .with("a", "7", "b", "96") .with("f", "2", "g", "1").build(); Assert.assertEquals(7, map.size()); try { Assert.assertEquals("5", map.remove("c")); Assert.fail("Remove of existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Assert.assertNull(map.put("q", "26")); Assert.fail("Put operation for new item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Assert.assertEquals("4", map.put("d", "27")); Assert.fail("Put operation for existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { map.clear(); Assert.fail("Clear operation for non-empty set should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Map<String, String> s = Collections.singletonMap("j", "j"); map.putAll(s); Assert.fail("putAll operation should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Assert.assertTrue(map.keySet().add("k")); Assert.fail("Add operation for new item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Assert.assertTrue(map.keySet().add("c")); Assert.fail("Add operation for existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Set<String> s = Collections.singleton("j"); map.keySet().addAll(s); Assert.fail("addAll operation should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Assert.assertTrue(map.keySet().remove("c")); Assert.fail("Remove of existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { List<String> s = Collections.singletonList("g"); map.keySet().removeAll(s); Assert.fail("Remove of existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { List<String> s = Collections.singletonList("e"); map.keySet().retainAll(s); Assert.fail("Retain of existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Assert.assertTrue(map.values().remove("5")); Assert.fail("Remove of existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { List<String> s = Collections.singletonList("4"); map.values().removeAll(s); Assert.fail("Remove of existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { List<String> s = Collections.singletonList("3"); map.values().retainAll(s); Assert.fail("Retain of existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Assert.assertTrue(map.values().add("8")); Assert.fail("Add operation for new item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Assert.assertTrue(map.values().add("3")); Assert.fail("Add operation for existing item should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { Set<String> s = Collections.singleton("12"); map.values().addAll(s); Assert.fail("addAll operation should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } try { map.values().clear(); Assert.fail("Clear operation should fail"); } catch (UnsupportedOperationException e) { Assert.assertNotNull(e); } // No exception, since no elements removed List<String> s = Collections.singletonList("k"); Assert.assertFalse(map.keySet().removeAll(s)); // No exception, since all elements retained s = Arrays.<String>asList("a", "b", "c", "d", "e", "f", "g"); Assert.assertFalse(map.keySet().retainAll(s)); // No exception, since no elements removed s = Collections.singletonList("9"); Assert.assertFalse(map.values().removeAll(s)); // No exception, since all elements retained s = Arrays.<String>asList("1", "2", "3", "4", "5", "7", "96"); Assert.assertFalse(map.values().retainAll(s)); // No exception, since clearing an empty collection does nothing ImmutableArrayMap.emptyMap().clear(); // The list returned from keySet().asList() is itself an ArrayBackedCollection ArrayBackedCollection<String> keys1 = (ArrayBackedCollection<String>)map.keySet().asList(); List<String> keys2 = keys1.asList(); Assert.assertSame(keys1, keys2); } @SuppressWarnings("unchecked") @Test public void testSerialization() throws Exception { ImmutableArrayMap<String, Integer> map = ImmutableArrayMap.<String, Integer>builder() .with("c", 5, "d", 4, "e", 3) .with("a", 7, "b", 96) .with("f", 2, "g", 1).build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(map); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); ImmutableArrayMap<String, Integer> map2 = (ImmutableArrayMap<String, Integer>) ois.readObject(); Assert.assertEquals(7, map2.size()); Assert.assertEquals("{c=5, d=4, e=3, a=7, b=96, f=2, g=1}", map2.toString()); Assert.assertEquals(Integer.valueOf(4), map2.get("d")); Assert.assertEquals(Integer.valueOf(1), map2.get("g")); // Keysets baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); ArrayBackedSet<String> keySet = map.keySet(); oos.writeObject(keySet); bais = new ByteArrayInputStream(baos.toByteArray()); ois = new ObjectInputStream(bais); ArrayBackedSet<String> keySet2 = (ArrayBackedSet<String>) ois.readObject(); Assert.assertEquals(keySet, keySet2); Assert.assertEquals(7, keySet2.size()); Assert.assertEquals("[c, d, e, a, b, f, g]", keySet2.toString()); // Values baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); ArrayBackedCollection<Integer> values = map.values(); oos.writeObject(values); bais = new ByteArrayInputStream(baos.toByteArray()); ois = new ObjectInputStream(bais); ArrayBackedCollection<Integer> values2 = (ArrayBackedCollection<Integer>) ois.readObject(); Assert.assertEquals(values, values2); Assert.assertEquals(7, values2.size()); Assert.assertEquals("[5, 4, 3, 7, 96, 2, 1]", values2.toString()); // Entrysets baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); ArrayBackedSet<Map.Entry<String,Integer>> entrySet = map.entrySet(); oos.writeObject(entrySet); bais = new ByteArrayInputStream(baos.toByteArray()); ois = new ObjectInputStream(bais); ArrayBackedSet<Map.Entry<String,Integer>> entrySet2 = (ArrayBackedSet<Map.Entry<String,Integer>>) ois.readObject(); Assert.assertEquals(entrySet, entrySet2); Assert.assertEquals(7, entrySet2.size()); Assert.assertEquals("[c=5, d=4, e=3, a=7, b=96, f=2, g=1]", entrySet2.toString()); // Test empty map baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(ImmutableArrayMap.emptyMap()); bais = new ByteArrayInputStream(baos.toByteArray()); ois = new ObjectInputStream(bais); map2 = (ImmutableArrayMap<String, Integer>) ois.readObject(); Assert.assertEquals("{}", map2.toString()); Assert.assertEquals(0, map2.size()); Assert.assertSame(ImmutableArrayMap.emptyMap(), map2); } }
run2000/java-immutable-collections
testsrc/net/njcull/collections/TestImmutableArrayMap.java
Java
bsd-3-clause
43,086
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license *******************************************************************************/ package org.caleydo.view.relationshipexplorer.ui.collection; import java.util.HashSet; import java.util.Set; import org.caleydo.core.id.IDMappingManager; import org.caleydo.core.id.IDMappingManagerRegistry; import org.caleydo.core.id.IDType; import org.caleydo.core.util.base.ILabeled; import org.caleydo.core.view.opengl.layout2.GLElement; import org.caleydo.view.relationshipexplorer.ui.ConTourElement; import org.caleydo.view.relationshipexplorer.ui.column.IEntityRepresentation; import org.caleydo.view.relationshipexplorer.ui.column.factory.IColumnFactory; import org.caleydo.view.relationshipexplorer.ui.detail.DetailViewFactories; import org.caleydo.view.relationshipexplorer.ui.detail.DetailViewWindow; import org.caleydo.view.relationshipexplorer.ui.detail.IDetailViewFactory; import org.caleydo.view.relationshipexplorer.ui.list.IColumnModel; import com.google.common.collect.Sets; /** * @author Christian * */ public abstract class AEntityCollection implements IEntityCollection { protected final ConTourElement contour; protected String label = ""; protected Set<Object> allElementIDs = new HashSet<>(); protected Set<Object> filteredElementIDs = new HashSet<>(); protected Set<Object> selectedElementIDs = new HashSet<>(); protected Set<Object> highlightElementIDs = new HashSet<>(); protected Set<IEntityRepresentation> representations = new HashSet<>(); protected IColumnFactory columnFactory; protected IDetailViewFactory detailViewFactory; public AEntityCollection(ConTourElement relationshipExplorer) { this.contour = relationshipExplorer; } @Override public Set<Object> getAllElementIDs() { return allElementIDs; } @Override public Set<Object> getFilteredElementIDs() { return filteredElementIDs; } @Override public Set<Object> getSelectedElementIDs() { return selectedElementIDs; } @Override public Set<Object> getHighlightElementIDs() { return highlightElementIDs; } @Override public void setFilteredItems(Set<Object> elementIDs) { this.filteredElementIDs = new HashSet<>(Sets.intersection(elementIDs, allElementIDs)); // notifyFilterUpdate(updateSource); } @Override public void filterChanged(Set<Object> ids, IDType idType, ILabeled updateSource) { for (IEntityRepresentation rep : representations) { rep.filterChanged(filteredElementIDs, updateSource); } } @Override public void setHighlightItems(Set<Object> elementIDs) { this.highlightElementIDs = new HashSet<>(Sets.intersection(elementIDs, allElementIDs)); } @Override public void highlightChanged(Set<Object> ids, IDType idType, ILabeled updateSource) { for (IEntityRepresentation rep : representations) { rep.highlightChanged(highlightElementIDs, updateSource); } } @Override public void setSelectedItems(Set<Object> elementIDs) { this.selectedElementIDs = new HashSet<>(Sets.intersection(elementIDs, allElementIDs)); // notifySelectionUpdate(updateSource); } @Override public void selectionChanged(Set<Object> ids, IDType idType, ILabeled updateSource) { for (IEntityRepresentation rep : representations) { rep.selectionChanged(selectedElementIDs, updateSource); } } @Override public Set<Object> getBroadcastingIDsFromElementIDs(Set<Object> elementIDs) { Set<Object> myElementIDs = new HashSet<>(Sets.intersection(elementIDs, allElementIDs)); Set<Object> broadcastIDs = new HashSet<>(); for (Object elementID : myElementIDs) { broadcastIDs.addAll(getBroadcastingIDsFromElementID(elementID)); } return broadcastIDs; } @Override public Set<Object> getElementIDsFromForeignIDs(Set<Object> foreignIDs, IDType foreignIDType) { IDMappingManager mappingManager = IDMappingManagerRegistry.get().getIDMappingManager(getBroadcastingIDType()); Set<Object> elementIDs = new HashSet<>(); Set<Object> broadcastIDs = mappingManager.getIDTypeMapper(foreignIDType, getBroadcastingIDType()).apply( foreignIDs); for (Object bcID : broadcastIDs) { elementIDs.addAll(getElementIDsFromBroadcastID(bcID)); } return new HashSet<>(Sets.intersection(elementIDs, allElementIDs)); } @Override public Set<Object> getBroadcastingIDsFromElementID(Object elementID) { if (!allElementIDs.contains(elementID)) return new HashSet<>(); return getBroadcastIDsFromElementID(elementID); } protected abstract Set<Object> getBroadcastIDsFromElementID(Object elementID); @Override public Set<Object> getElementIDsFromBroadcastingID(Object broadcastingID) { Set<Object> elementIDs = getElementIDsFromBroadcastID(broadcastingID); return new HashSet<>(Sets.intersection(elementIDs, allElementIDs)); } protected abstract Set<Object> getElementIDsFromBroadcastID(Object broadcastID); @Override public String getLabel() { return label; } /** * @param label * setter, see {@link label} */ public void setLabel(String label) { this.label = label; } @Override public void addEntityRepresentation(IEntityRepresentation rep) { representations.add(rep); } @Override public void removeEntityRepresentation(IEntityRepresentation rep) { representations.remove(rep); } @Override public void reset() { restoreAllEntities(); highlightElementIDs.clear(); selectedElementIDs.clear(); representations.clear(); } /** * @return the representations, see {@link #representations} */ public Set<IEntityRepresentation> getRepresentations() { return new HashSet<IEntityRepresentation>(representations); } @Override public void restoreAllEntities() { filteredElementIDs = new HashSet<>(allElementIDs.size()); filteredElementIDs.addAll(allElementIDs); } @Override public IColumnModel createColumnModel() { if (columnFactory == null) columnFactory = getDefaultColumnFactory(); return columnFactory.create(this, contour); } /** * @param columnFactory * setter, see {@link columnFactory} */ public void setColumnFactory(IColumnFactory columnFactory) { this.columnFactory = columnFactory; } /** * @return the detailViewFactory, see {@link #detailViewFactory} */ public IDetailViewFactory getDetailViewFactory() { if (detailViewFactory == null) { detailViewFactory = DetailViewFactories.createDefaultDetailViewFactory(); } return detailViewFactory; } @Override public DetailViewWindow createDetailViewWindow() { if (detailViewFactory == null) detailViewFactory = DetailViewFactories.createDefaultDetailViewFactory(); return detailViewFactory.createWindow(this, contour); } /** * @param detailViewFactory * setter, see {@link detailViewFactory} */ public void setDetailViewFactory(IDetailViewFactory detailViewFactory) { this.detailViewFactory = detailViewFactory; } @Override public GLElement createDetailView(DetailViewWindow window) { if (detailViewFactory == null) detailViewFactory = DetailViewFactories.createDefaultDetailViewFactory(); return detailViewFactory.createDetailView(this, window, contour); } protected abstract IColumnFactory getDefaultColumnFactory(); /** * @return the columnFactory, see {@link #columnFactory} */ public IColumnFactory getColumnFactory() { return columnFactory; } }
Caleydo/org.caleydo.view.contour
src/main/java/org/caleydo/view/relationshipexplorer/ui/collection/AEntityCollection.java
Java
bsd-3-clause
7,529
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cz.ascaria.network.central.utils; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.math.Vector4f; import com.jme3.network.serializing.Serializable; import cz.ascaria.network.central.Main; import java.util.logging.Level; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * * @author Ascaria Quynn */ @Serializable public class PropertiesHelper { private JSONObject properties = new JSONObject(); /** * Creates json helper from multiple properties strings. Each must start with { and must have length greater than 1. * If keys match, then the later value for that key will overwrite the previous one. * @param propss */ public PropertiesHelper(String... propss) { JSONParser jsonParser = new JSONParser(); try { for(String props : propss) { try { if(props instanceof String && props.length() > 1 && props.startsWith("{")) { JSONObject jsonProps = (JSONObject)jsonParser.parse(props); properties.putAll((JSONObject)jsonProps); } } catch(Exception ex) { Main.LOG.log(Level.SEVERE, props, ex); throw ex; } } } catch(Exception ex) { properties.clear(); } } public boolean hasNumber(String name) { if(properties.containsKey(name)) { Object number = properties.get(name); return number instanceof Number; } return false; } public float getFloat(String name, float defaultValue) { if(hasNumber(name)) { return ((Number)properties.get(name)).floatValue(); } return defaultValue; } public double getDouble(String name, float defaultValue) { if(hasNumber(name)) { return ((Number)properties.get(name)).doubleValue(); } return defaultValue; } public boolean hasVector3f(String name) { if(properties.containsKey(name)) { Object jsonArray = properties.get(name); if(jsonArray instanceof JSONArray && ((JSONArray)jsonArray).size() == 3) { for(Object number : (JSONArray)jsonArray) { if(!(number instanceof Number)) { return false; } return true; } } } return false; } public Vector3f getVector3f(String name, Vector3f defaultValue) { if(hasVector3f(name)) { JSONArray jsonArray = (JSONArray)properties.get(name); return new Vector3f( ((Number)jsonArray.get(0)).floatValue(), ((Number)jsonArray.get(1)).floatValue(), ((Number)jsonArray.get(2)).floatValue() ); } return defaultValue; } public boolean hasVector4f(String name) { if(properties.containsKey(name)) { Object jsonArray = properties.get(name); if(jsonArray instanceof JSONArray && ((JSONArray)jsonArray).size() == 4) { for(Object number : (JSONArray)jsonArray) { if(!(number instanceof Number)) { return false; } return true; } } } return false; } public Vector4f getVector4f(String name, Vector4f defaultValue) { if(hasVector4f(name)) { JSONArray jsonArray = (JSONArray)properties.get(name); return new Vector4f( ((Number)jsonArray.get(0)).floatValue(), ((Number)jsonArray.get(1)).floatValue(), ((Number)jsonArray.get(2)).floatValue(), ((Number)jsonArray.get(3)).floatValue() ); } return defaultValue; } public boolean hasColorRGBA(String name) { if(properties.containsKey(name)) { Object jsonArray = properties.get(name); if(jsonArray instanceof JSONArray && ((JSONArray)jsonArray).size() == 4) { for(Object number : (JSONArray)jsonArray) { if(!(number instanceof Number)) { return false; } return true; } } } return false; } public ColorRGBA getColorRGBA(String name, ColorRGBA defaultValue) { if(hasColorRGBA(name)) { JSONArray jsonArray = (JSONArray)properties.get(name); return new ColorRGBA( ((Number)jsonArray.get(0)).floatValue(), ((Number)jsonArray.get(1)).floatValue(), ((Number)jsonArray.get(2)).floatValue(), ((Number)jsonArray.get(3)).floatValue() ); } return defaultValue; } }
AscariaQuynn/ZoneOfUprising-Central
src/cz/ascaria/network/central/utils/PropertiesHelper.java
Java
bsd-3-clause
5,109
package org.pgscala.converters; import org.joda.convert.*; /** Do not edit - generated in Builder / PGNullableShortConverterBuilder.scala */ public enum PGNullableShortConverter implements StringConverter<Short> { INSTANCE; public static final String pgType = "smallint"; @ToString public static String shortToString(final Short s) { return null == s ? null : Short.toString(s); } @FromString public static Short stringToShort(final String s) { return null == s ? null : Short.valueOf(s); } // ----------------------------------------------------------------------------- public String convertToString(final Short s) { return shortToString(s); } public Short convertFromString(final Class<? extends Short> clazz, final String s) { return stringToShort(s); } }
melezov/pgscala
converters-java/src/generated/java/org/pgscala/converters/PGNullableShortConverter.java
Java
bsd-3-clause
849
package expo.modules.notifications.permissions; import android.app.NotificationManager; import android.content.Context; import android.os.Build; import android.os.Bundle; import expo.modules.core.ExportedModule; import expo.modules.core.Promise; import expo.modules.core.arguments.ReadableArguments; import expo.modules.core.interfaces.ExpoMethod; import androidx.core.app.NotificationManagerCompat; import expo.modules.interfaces.permissions.PermissionsStatus; import static expo.modules.interfaces.permissions.PermissionsResponse.CAN_ASK_AGAIN_KEY; import static expo.modules.interfaces.permissions.PermissionsResponse.EXPIRES_KEY; import static expo.modules.interfaces.permissions.PermissionsResponse.GRANTED_KEY; import static expo.modules.interfaces.permissions.PermissionsResponse.PERMISSION_EXPIRES_NEVER; import static expo.modules.interfaces.permissions.PermissionsResponse.STATUS_KEY; public class NotificationPermissionsModule extends ExportedModule { private static final String EXPORTED_NAME = "ExpoNotificationPermissionsModule"; private static final String ANDROID_RESPONSE_KEY = "android"; private static final String IMPORTANCE_KEY = "importance"; private static final String INTERRUPTION_FILTER_KEY = "interruptionFilter"; public NotificationPermissionsModule(Context context) { super(context); } @Override public String getName() { return EXPORTED_NAME; } @ExpoMethod public void getPermissionsAsync(final Promise promise) { promise.resolve(getPermissionsBundle()); } @ExpoMethod public void requestPermissionsAsync(@SuppressWarnings("unused") final ReadableArguments permissionsTypes, final Promise promise) { promise.resolve(getPermissionsBundle()); } private Bundle getPermissionsBundle() { NotificationManagerCompat managerCompat = NotificationManagerCompat.from(getContext()); boolean areEnabled = managerCompat.areNotificationsEnabled(); PermissionsStatus status = areEnabled ? PermissionsStatus.GRANTED : PermissionsStatus.DENIED; Bundle permissions = new Bundle(); permissions.putString(EXPIRES_KEY, PERMISSION_EXPIRES_NEVER); permissions.putBoolean(CAN_ASK_AGAIN_KEY, areEnabled); permissions.putString(STATUS_KEY, status.getStatus()); permissions.putBoolean(GRANTED_KEY, PermissionsStatus.GRANTED == status); Bundle platformPermissions = new Bundle(); platformPermissions.putInt(IMPORTANCE_KEY, managerCompat.getImportance()); NotificationManager manager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && manager != null) { platformPermissions.putInt(INTERRUPTION_FILTER_KEY, manager.getCurrentInterruptionFilter()); } permissions.putBundle(ANDROID_RESPONSE_KEY, platformPermissions); return permissions; } }
exponentjs/exponent
packages/expo-notifications/android/src/main/java/expo/modules/notifications/permissions/NotificationPermissionsModule.java
Java
bsd-3-clause
2,862
/*L * Copyright SAIC, Ellumen and RSNA (CTP) * * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details. */ package gov.nih.nci.nbia.searchresult; import junit.framework.TestCase; public class SearchCriteriaDTOTestCase extends TestCase { public void testSearchCriteriaDTO() { SearchCriteriaDTO searchCriteriaDTO = new SearchCriteriaDTO(); searchCriteriaDTO.setType("type1"); searchCriteriaDTO.setSubType("subtype1"); searchCriteriaDTO.setValue("val1"); assertTrue(searchCriteriaDTO.getType().equals("type1")); assertTrue(searchCriteriaDTO.getSubType().equals("subtype1")); assertTrue(searchCriteriaDTO.getValue().equals("val1")); } }
NCIP/national-biomedical-image-archive
software/nbia-dao/test/gov/nih/nci/nbia/searchresult/SearchCriteriaDTOTestCase.java
Java
bsd-3-clause
764
/* * Copyright (c) Nmote Ltd. 2015. All rights reserved. * See LICENSE doc in a root of project folder for additional information. */ package com.nmote.oembed.ext; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.nmote.oembed.About; import com.nmote.oembed.BasicOEmbed; /** * Mix Club oEmbed extension. * * @author vnesek */ @JsonIgnoreProperties("embed") public class MixCloudEmbed extends BasicOEmbed { private static final long serialVersionUID = About.SERIAL_VERSION_UID; /** * Getter for extension property. * * @return property value */ public String getImageUrl() { return imageUrl; } /** * Setter for extension property. * * @param imageUrl * property value */ public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } @JsonProperty("width") public void setWidthExt(String width) { try { super.setWidth(Integer.parseInt(width)); } catch (NumberFormatException e) { System.err.println("Invalid width: " + width); } } @JsonProperty("image") private String imageUrl; }
vnesek/nmote-oembed
src/main/java/com/nmote/oembed/ext/MixCloudEmbed.java
Java
bsd-3-clause
1,159
package edu.washington.escience.myria.operator; import com.google.common.base.Preconditions; /** * An abstraction for a unary operator. * * */ public abstract class UnaryOperator extends Operator { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * The child. */ private Operator child; /** * @param child the single child of this operator. */ public UnaryOperator(final Operator child) { this.child = child; } @Override public final Operator[] getChildren() { if (child == null) { return null; } return new Operator[] {child}; } /** * @return the child. */ public final Operator getChild() { return child; } /** * @param child the child. */ public final void setChild(final Operator child) { setChildren(new Operator[] {child}); } @Override public final void setChildren(final Operator[] children) { Integer opId = getOpId(); Preconditions.checkArgument( child == null, "Operator opid=%s called setChildren(), but children have already been set", opId); Preconditions.checkNotNull(children, "Unary operator opId=%s has null children", opId); Preconditions.checkArgument( children.length == 1, "Operator opId=%s setChildren() must be called with an array of length 1", opId); Preconditions.checkNotNull( children[0], "Unary operator opId=%s has its child to be null", opId); child = children[0]; } }
uwescience/myria
src/edu/washington/escience/myria/operator/UnaryOperator.java
Java
bsd-3-clause
1,528
/*L * Copyright Oracle Inc * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details. */ /* * eXist Open Source Native XML Database * Copyright (C) 2001-04 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.storage; import java.io.StringReader; import junit.framework.TestCase; import junit.textui.TestRunner; import org.exist.collections.Collection; import org.exist.collections.IndexInfo; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentSet; import org.exist.security.SecurityManager; import org.exist.security.xacml.AccessContext; import org.exist.storage.lock.Lock; import org.exist.storage.serializers.Serializer; import org.exist.storage.txn.TransactionManager; import org.exist.storage.txn.Txn; import org.exist.test.TestConstants; import org.exist.util.Configuration; import org.exist.xmldb.CollectionManagementServiceImpl; import org.exist.xupdate.Modification; import org.exist.xupdate.XUpdateProcessor; import org.xml.sax.InputSource; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Database; import org.xmldb.api.base.Resource; import org.xmldb.api.modules.XUpdateQueryService; /** * Tests recovery of XUpdate operations. * * @author wolf * */ public class UpdateRecoverTest extends TestCase { public static void main(String[] args) { TestRunner.run(UpdateRecoverTest.class); } private static String TEST_XML = "<?xml version=\"1.0\"?>" + "<products>" + " <product id=\"0\">" + " <description>Milk</description>" + " <price>22.50</price>" + " </product>" + "</products>"; public void testStore() { BrokerPool.FORCE_CORRUPTION = true; BrokerPool pool = null; DBBroker broker = null; try { pool = startDB(); assertNotNull(pool); broker = pool.get(SecurityManager.SYSTEM_USER); assertNotNull(broker); TransactionManager transact = pool.getTransactionManager(); assertNotNull(transact); Txn transaction = transact.beginTransaction(); assertNotNull(transaction); System.out.println("Transaction started ..."); Collection root = broker.getOrCreateCollection(transaction, TestConstants.TEST_COLLECTION_URI); assertNotNull(root); broker.saveCollection(transaction, root); Collection test2 = broker.getOrCreateCollection(transaction, TestConstants.TEST_COLLECTION_URI2); assertNotNull(test2); broker.saveCollection(transaction, test2); IndexInfo info = test2.validateXMLResource(transaction, broker, TestConstants.TEST_XML_URI, TEST_XML); assertNotNull(info); //TODO : unlock the collection here ? test2.store(transaction, broker, info, TEST_XML, false); transact.commit(transaction); System.out.println("Transaction commited ..."); transaction = transact.beginTransaction(); assertNotNull(transaction); System.out.println("Transaction started ..."); DocumentSet docs = new DocumentSet(); docs.add(info.getDocument()); XUpdateProcessor proc = new XUpdateProcessor(broker, docs, AccessContext.TEST); assertNotNull(proc); String xupdate; Modification modifications[]; System.out.println("Inserting new items ..."); // insert some nodes for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:insert-before select=\"/products/product[1]\">" + " <product>" + " <description>Product " + i + "</description>" + " <price>" + (i * 2.5) + "</price>" + " <stock>" + (i * 10) + "</stock>" + " </product>" + " </xu:insert-before>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); modifications[0].process(transaction); proc.reset(); } System.out.println("Adding attributes ..."); // add attribute for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:append select=\"/products/product[" + i + "]\">" + " <xu:attribute name=\"id\">" + i + "</xu:attribute>" + " </xu:append>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); modifications[0].process(transaction); proc.reset(); } System.out.println("Replacing elements ..."); // replace some for (int i = 1; i <= 100; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:replace select=\"/products/product[" + i + "]\">" + " <product id=\"" + i + "\">" + " <description>Replaced product</description>" + " <price>" + (i * 0.75) + "</price>" + " </product>" + " </xu:replace>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); long mods = modifications[0].process(transaction); System.out.println("Modifications: " + mods); proc.reset(); } System.out.println("Removing some elements ..."); // remove some for (int i = 1; i <= 100; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:remove select=\"/products/product[last()]\"/>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); modifications[0].process(transaction); proc.reset(); } System.out.println("Appending some elements ..."); for (int i = 1; i <= 100; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:append select=\"/products\">" + " <product>" + " <xu:attribute name=\"id\"><xu:value-of select=\"count(/products/product) + 1\"/></xu:attribute>" + " <description>Product " + i + "</description>" + " <price>" + (i * 2.5) + "</price>" + " <stock>" + (i * 10) + "</stock>" + " </product>" + " </xu:append>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); modifications[0].process(transaction); proc.reset(); } System.out.println("Renaming elements ..."); // rename element "description" to "descript" xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:rename select=\"/products/product/description\">descript</xu:rename>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); modifications[0].process(transaction); proc.reset(); System.out.println("Updating attribute values ..."); // update attribute values for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:update select=\"/products/product[" + i + "]/@id\">" + i + "u</xu:update>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); long mods = modifications[0].process(transaction); System.out.println(mods + " records modified."); proc.reset(); } System.out.println("Append new element to each item ..."); // append new element to records for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:append select=\"/products/product[" + i + "]\">" + " <date><xu:value-of select=\"current-dateTime()\"/></date>" + " </xu:append>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); modifications[0].process(transaction); proc.reset(); } System.out.println("Updating element content ..."); // update element content for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:update select=\"/products/product[" + i + "]/price\">19.99</xu:update>" + "</xu:modifications>"; proc.setBroker(broker); proc.setDocumentSet(docs); modifications = proc.parse(new InputSource(new StringReader(xupdate))); assertNotNull(modifications); long mods = modifications[0].process(transaction); System.out.println(mods + " records modified."); proc.reset(); } transact.commit(transaction); System.out.println("Transaction commited ..."); } catch (Exception e) { fail(e.getMessage()); } finally { if (pool!= null) pool.release(broker); } } public void testRead() { BrokerPool.FORCE_CORRUPTION = false; BrokerPool pool = null; DBBroker broker = null; try { System.out.println("testRead() ...\n"); pool = startDB(); assertNotNull(pool); broker = pool.get(SecurityManager.SYSTEM_USER); assertNotNull(broker); Serializer serializer = broker.getSerializer(); assertNotNull(serializer); serializer.reset(); DocumentImpl doc = broker.getXMLResource(TestConstants.TEST_COLLECTION_URI2.append(TestConstants.TEST_XML_URI), Lock.READ_LOCK); assertNotNull("Document '" + DBBroker.ROOT_COLLECTION + "/test/test2/test.xml' should not be null", doc); String data = serializer.serialize(doc); assertNotNull(data); System.out.println(data); doc.getUpdateLock().release(Lock.READ_LOCK); } catch (Exception e) { fail(e.getMessage()); } finally { if (pool!= null) pool.release(broker); } } public void testXMLDBStore() { BrokerPool.FORCE_CORRUPTION = false; BrokerPool pool = null; try { pool = startDB(); assertNotNull(pool); org.xmldb.api.base.Collection root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", ""); assertNotNull(root); CollectionManagementServiceImpl mgr = (CollectionManagementServiceImpl) root.getService("CollectionManagementService", "1.0"); assertNotNull(mgr); org.xmldb.api.base.Collection test = root.getChildCollection("test"); if (test == null) test = mgr.createCollection(TestConstants.TEST_COLLECTION_URI.toString()); assertNotNull(test); org.xmldb.api.base.Collection test2 = test.getChildCollection("test2"); if (test2 == null) test2 = mgr.createCollection(TestConstants.TEST_COLLECTION_URI2.toString()); assertNotNull(test2); Resource res = test2.createResource("test_xmldb.xml", "XMLResource"); assertNotNull(res); res.setContent(TEST_XML); test2.storeResource(res); XUpdateQueryService service = (XUpdateQueryService) test2.getService("XUpdateQueryService", "1.0"); assertNotNull(service); String xupdate; System.out.println("Inserting new items ..."); // insert some nodes for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:insert-before select=\"/products/product[1]\">" + " <product>" + " <description>Product " + i + "</description>" + " <price>" + (i * 2.5) + "</price>" + " <stock>" + (i * 10) + "</stock>" + " </product>" + " </xu:insert-before>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); } System.out.println("Adding attributes ..."); // add attribute for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:append select=\"/products/product[" + i + "]\">" + " <xu:attribute name=\"id\">" + i + "</xu:attribute>" + " </xu:append>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); } System.out.println("Replacing elements ..."); // replace some for (int i = 1; i <= 100; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:replace select=\"/products/product[" + i + "]\">" + " <product id=\"" + i + "\">" + " <description>Replaced product</description>" + " <price>" + (i * 0.75) + "</price>" + " </product>" + " </xu:replace>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); } System.out.println("Removing some elements ..."); // remove some for (int i = 1; i <= 100; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:remove select=\"/products/product[last()]\"/>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); } System.out.println("Appending some elements ..."); for (int i = 1; i <= 100; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:append select=\"/products\">" + " <product>" + " <xu:attribute name=\"id\"><xu:value-of select=\"count(/products/product) + 1\"/></xu:attribute>" + " <description>Product " + i + "</description>" + " <price>" + (i * 2.5) + "</price>" + " <stock>" + (i * 10) + "</stock>" + " </product>" + " </xu:append>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); } System.out.println("Renaming elements ..."); // rename element "description" to "descript" xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:rename select=\"/products/product/description\">descript</xu:rename>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); System.out.println("Updating attribute values ..."); // update attribute values for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:update select=\"/products/product[" + i + "]/@id\">" + i + "u</xu:update>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); } System.out.println("Append new element to each item ..."); // append new element to records for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:append select=\"/products/product[" + i + "]\">" + " <date><xu:value-of select=\"current-dateTime()\"/></date>" + " </xu:append>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); } System.out.println("Updating element content ..."); // update element content for (int i = 1; i <= 200; i++) { xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"http://www.xmldb.org/xupdate\">" + " <xu:update select=\"/products/product[" + i + "]/price\">19.99</xu:update>" + "</xu:modifications>"; service.updateResource("test_xmldb.xml", xupdate); } } catch (Exception e) { fail(e.getMessage()); } } public void testXMLDBRead() { BrokerPool.FORCE_CORRUPTION = false; try { org.xmldb.api.base.Collection test2 = DatabaseManager.getCollection("xmldb:exist://" + TestConstants.TEST_COLLECTION_URI2, "admin", ""); assertNotNull(test2); Resource res = test2.getResource("test_xmldb.xml"); assertNotNull("Document should not be null", res); System.out.println(res.getContent()); org.xmldb.api.base.Collection root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", ""); assertNotNull(root); CollectionManagementServiceImpl mgr = (CollectionManagementServiceImpl) root.getService("CollectionManagementService", "1.0"); assertNotNull(mgr); mgr.removeCollection("test"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } protected BrokerPool startDB() { try { Configuration config = new Configuration(); BrokerPool.configure(1, 5, config); // initialize driver Database database = (Database) Class.forName("org.exist.xmldb.DatabaseImpl").newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); return BrokerPool.getInstance(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } return null; } protected void tearDown() { BrokerPool.stopAll(false); } }
NCIP/cadsr-cgmdr-nci-uk
test/src/org/exist/storage/UpdateRecoverTest.java
Java
bsd-3-clause
22,636
package synergyviewcore.media.ui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Frame; import java.awt.Panel; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import synergyviewcore.media.model.AbstractMedia; import synergyviewcore.resource.ResourceLoader; /** * The Class MediaSwtAwtComposite. */ public class MediaSwtAwtComposite extends Composite { /** The Constant MEDIA_DURATION_LABEL_HEIGHT. */ private static final int MEDIA_DURATION_LABEL_HEIGHT = 20; /** The Constant PADDING. */ private static final int PADDING = 5; /** The awt frame. */ private Frame awtFrame; /** The media. */ private AbstractMedia media; /** The video_ sw t_ aw t_container. */ private Composite video_SWT_AWT_container; /** The video duration. */ private Label videoDuration; /** The video preview container. */ private Composite videoPreviewContainer; /** * Instantiates a new media swt awt composite. * * @param parent * the parent * @param style * the style */ public MediaSwtAwtComposite(Composite parent, int style) { super(parent, style); setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_BLACK)); GridLayout layout = new GridLayout(1, false); setLayout(layout); videoPreviewContainer = new Composite(this, SWT.NONE); videoPreviewContainer.setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_BLACK)); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; videoPreviewContainer.setLayoutData(data); videoPreviewContainer.setLayout(new GridLayout(1, false)); videoPreviewContainer.addControlListener(new ControlListener() { public void controlMoved(ControlEvent e) { // } public void controlResized(ControlEvent e) { if (awtFrame != null) { GridData swtAwtGridData = (GridData) video_SWT_AWT_container.getLayoutData(); Dimension d = calculateVideoSize(new Dimension(videoPreviewContainer.getBounds().width, videoPreviewContainer.getBounds().height)); swtAwtGridData.heightHint = (int) d.getHeight(); swtAwtGridData.widthHint = (int) d.getWidth(); videoPreviewContainer.layout(); } } }); video_SWT_AWT_container = new Composite(videoPreviewContainer, SWT.EMBEDDED | SWT.NO_BACKGROUND); GridData swtAwtGridData = new GridData(); swtAwtGridData.horizontalAlignment = SWT.FILL; swtAwtGridData.grabExcessHorizontalSpace = true; swtAwtGridData.verticalAlignment = SWT.FILL; swtAwtGridData.grabExcessVerticalSpace = true; video_SWT_AWT_container.setLayoutData(swtAwtGridData); videoDuration = new Label(this, SWT.SHADOW_IN); data = new GridData(); data.horizontalAlignment = GridData.CENTER; data.grabExcessHorizontalSpace = true; data.heightHint = MEDIA_DURATION_LABEL_HEIGHT; videoDuration.setLayoutData(data); videoDuration.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_WHITE)); videoDuration.setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_BLACK)); videoDuration.setText("No media available."); } /** * Adds the media. * * @param mediaValue * the media value */ public void addMedia(AbstractMedia mediaValue) { removeMedia(); this.media = mediaValue; this.media.addPropertyChangeListener(AbstractMedia.PROP_TIME, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { updateTimes(); } }); updateTimes(); this.media.prepareMedia(); awtFrame = SWT_AWT.new_Frame(video_SWT_AWT_container); Panel awtPanel = new Panel(); awtPanel.setLayout(new BorderLayout()); awtPanel.add(this.media.getUIComponent(), BorderLayout.CENTER); awtFrame.add(awtPanel); GridData swtAwtGridData = (GridData) video_SWT_AWT_container.getLayoutData(); Dimension d = calculateVideoSize(new Dimension(videoPreviewContainer.getBounds().width, videoPreviewContainer.getBounds().height)); swtAwtGridData.widthHint = d.width; swtAwtGridData.heightHint = d.height; swtAwtGridData.horizontalAlignment = SWT.CENTER; swtAwtGridData.grabExcessHorizontalSpace = true; swtAwtGridData.verticalAlignment = SWT.CENTER; swtAwtGridData.grabExcessVerticalSpace = true; videoPreviewContainer.layout(); this.layout(); updateTimes(); } /** * Calculate video size. * * @param parentDimension * the parent dimension * @return the dimension */ private Dimension calculateVideoSize(Dimension parentDimension) { Dimension d = media.getSize(); final double movieratio = d.getHeight() / d.getWidth(); double windowratio = (double) parentDimension.height / (double) parentDimension.width; if (windowratio < movieratio) { if (d.height != 0) { int width = (int) ((parentDimension.height * d.width) / d.height); return new Dimension(width - PADDING, parentDimension.height - PADDING); } else { return new Dimension(0, 0); // For audio only media } } else { if (d.width != 0) { int height = (int) ((parentDimension.width * d.height) / d.width); return new Dimension(parentDimension.width - PADDING, height - PADDING); } else { return new Dimension(0, 0); // For audio only media } } } /* * (non-Javadoc) * * @see org.eclipse.swt.widgets.Widget#dispose() */ @Override public void dispose() { removeMedia(); super.dispose(); } /** * Dispose video awt frame. */ private void disposeVideoAwtFrame() { Thread closeMediaASAP = new Thread(new Runnable() { public void run() { if (awtFrame != null) { awtFrame.dispose(); awtFrame = null; } } }); closeMediaASAP.start(); } /** * Removes the media. */ public void removeMedia() { disposeVideoAwtFrame(); if (media != null) { media.dispose(); media = null; } if (!video_SWT_AWT_container.isDisposed()) { GridData swtAwtGridData = (GridData) video_SWT_AWT_container.getLayoutData(); swtAwtGridData.horizontalAlignment = SWT.FILL; swtAwtGridData.grabExcessHorizontalSpace = true; swtAwtGridData.verticalAlignment = SWT.FILL; swtAwtGridData.grabExcessVerticalSpace = true; videoDuration.setText(ResourceLoader.getString("MEDIA_PREVIEW_NO_MEDIA_MESSAGE")); videoPreviewContainer.layout(true); this.layout(true); this.redraw(); this.update(); } } /** * Update times. */ private void updateTimes() { Display.getDefault().syncExec(new Runnable() { public void run() { if (MediaSwtAwtComposite.this.isDisposed()) { return; } videoDuration.setText(String.format("%s/%s", media.getFormattedTime(), media.getFormattedDuration())); } }); } }
synergynet/synergyview
synergyview-core/src/synergyviewcore/media/ui/MediaSwtAwtComposite.java
Java
bsd-3-clause
7,282
package synergynet3.web.commons.client.ui; import java.util.ArrayList; import java.util.List; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; /** * The Class SimpleListBox. */ public class SimpleListBox extends VerticalPanel { /** The allows selection. */ private boolean allowsSelection = true; /** The multiple select. */ private boolean multipleSelect = false; /** * Instantiates a new simple list box. */ public SimpleListBox() { super(); setStylePrimaryName("simpleListBox"); } // *** managing items *** /** * Adds the click handler. * * @param handler * the handler * @return the handler registration */ public HandlerRegistration addClickHandler(final ClickHandler handler) { return addDomHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (allowsSelection) { handler.onClick(event); } } }, ClickEvent.getType()); } /** * Adds the item. * * @param item * the item */ public void addItem(String item) { addLabel(item); } /** * Gets the item at index. * * @param index * the index * @return the item at index */ public String getItemAtIndex(int index) { Label labelForIndex = getLabelAtIndex(index); return labelForIndex.getText(); } /** * Gets the item count. * * @return the item count */ public int getItemCount() { return getWidgetCount(); } // *** item selection *** /** * Gets the selected index. * * @return the selected index */ public int getSelectedIndex() { for (int i = 0; i < getItemCount(); i++) { if (isItemSelectedAtIndex(i)) { return i; } } return -1; } /** * Gets the selected item. * * @return the selected item */ public String getSelectedItem() { int selectedIndex = getSelectedIndex(); if (selectedIndex == -1) { return null; } return getItemAtIndex(selectedIndex); } /** * Gets the selected items. * * @return the selected items */ public List<String> getSelectedItems() { List<String> list = new ArrayList<String>(); for (int i = 0; i < getItemCount(); i++) { if (isItemSelectedAtIndex(i)) { list.add(getItemAtIndex(i)); } } return list; } /** * Checks if is multiple select. * * @return true, if is multiple select */ public boolean isMultipleSelect() { return this.multipleSelect; } /** * Checks if is selected. * * @param index * the index * @return true, if is selected */ public boolean isSelected(int index) { return isItemSelectedAtIndex(index); } /** * Removes the all items. */ public void removeAllItems() { removeAllWidgets(); } /** * Select all. */ public void selectAll() { if (!allowsSelection) { return; } if (!multipleSelect) { return; } makeAllLabelsSelected(); } /** * Sets the allows selection. * * @param allowsSelection * the new allows selection */ public void setAllowsSelection(boolean allowsSelection) { this.allowsSelection = allowsSelection; if (!allowsSelection) { makeAllLabelsUnselected(); } } // *** handlers *** /** * Sets the multiple select. * * @param isMultipleSelect * the new multiple select */ public void setMultipleSelect(boolean isMultipleSelect) { this.multipleSelect = isMultipleSelect; makeAllLabelsUnselected(); } // *** private methods *** /** * Adds the label. * * @param item * the item */ private void addLabel(String item) { final Label label = new Label(item); label.setStylePrimaryName("simpleListBoxItem"); label.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { itemClicked(label); } }); this.add(label); } /** * Gets the label at index. * * @param index * the index * @return the label at index */ private Label getLabelAtIndex(int index) { return (Label) this.getWidget(index); } /** * Checks if is item selected at index. * * @param i * the i * @return true, if is item selected at index */ private boolean isItemSelectedAtIndex(int i) { Label labelAtIndex = getLabelAtIndex(i); return labelIsSelected(labelAtIndex); } // *** private event handling *** /** * Label is selected. * * @param label * the label * @return true, if successful */ private boolean labelIsSelected(Label label) { return label.getStyleName().contains("selected"); } /** * Make all labels selected. */ private void makeAllLabelsSelected() { for (int i = 0; i < getItemCount(); i++) { Label labelAtIndex = getLabelAtIndex(i); makeLabelSelected(labelAtIndex); } } /** * Make all labels unselected. */ private void makeAllLabelsUnselected() { for (int i = 0; i < getItemCount(); i++) { Label labelAtIndex = getLabelAtIndex(i); makeLabelUnselected(labelAtIndex); } } /** * Make label selected. * * @param label * the label */ private void makeLabelSelected(Label label) { label.setStyleDependentName("selected", true); } /** * Make labels unselected except for. * * @param label * the label */ private void makeLabelsUnselectedExceptFor(Label label) { for (int i = 0; i < getItemCount(); i++) { Label labelAtIndex = getLabelAtIndex(i); if (labelAtIndex != label) { makeLabelUnselected(labelAtIndex); } } } /** * Make label unselected. * * @param label * the label */ private void makeLabelUnselected(Label label) { label.removeStyleDependentName("selected"); } /** * Removes the all widgets. */ private void removeAllWidgets() { this.clear(); } /** * Item clicked. * * @param label * the label */ protected void itemClicked(Label label) { if (!this.allowsSelection) { return; } if (!labelIsSelected(label)) { makeLabelSelected(label); } else { makeLabelUnselected(label); } if (!multipleSelect) { makeLabelsUnselectedExceptFor(label); } } }
synergynet/synergynet3.1
synergynet3.1-parent/synergynet3-web-commons/src/main/java/synergynet3/web/commons/client/ui/SimpleListBox.java
Java
bsd-3-clause
6,360
package au.gov.ga.geodesy.support.mapper.orika.geodesyml; import au.gov.ga.geodesy.domain.model.sitelog.FrequencyStandardLogItem; import au.gov.ga.geodesy.port.adapter.geodesyml.GeodesyMLMarshaller; import au.gov.ga.geodesy.port.adapter.geodesyml.GeodesyMLUtils; import au.gov.ga.geodesy.support.TestResources; import au.gov.ga.geodesy.support.marshalling.moxy.GeodesyMLMoxy; import au.gov.ga.geodesy.support.spring.UnitTest; import au.gov.ga.geodesy.support.utils.GMLDateUtils; import au.gov.xml.icsm.geodesyml.v_0_4.FrequencyStandardType; import au.gov.xml.icsm.geodesyml.v_0_4.GeodesyMLType; import au.gov.xml.icsm.geodesyml.v_0_4.SiteLogType; import net.opengis.gml.v_3_2_1.TimePeriodType; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import org.springframework.beans.factory.annotation.Autowired; public class FrequencyStandardMapperTest extends UnitTest { private GeodesyMLMarshaller marshaller = new GeodesyMLMoxy(); @Autowired private FrequencyStandardMapper mapper; @Test public void testMapping() throws Exception { GeodesyMLType mobs = marshaller.unmarshal(TestResources.customGeodesyMLSiteLogReader("MOBS"), GeodesyMLType.class) .getValue(); SiteLogType siteLog = GeodesyMLUtils.getElementFromJAXBElements(mobs.getElements(), SiteLogType.class) .findFirst() .get(); FrequencyStandardType frequencyStandardTypeA = siteLog.getFrequencyStandards().get(0).getFrequencyStandard(); FrequencyStandardLogItem logItem = mapper.to(frequencyStandardTypeA); assertThat(logItem.getType(), equalTo(frequencyStandardTypeA.getStandardType().getValue())); assertThat(logItem.getInputFrequency(), equalTo(String.valueOf(frequencyStandardTypeA.getInputFrequency()))); assertThat(logItem.getNotes(), equalTo(frequencyStandardTypeA.getNotes())); assertThat(logItem.getEffectiveDates().getFrom(), equalTo(GMLDateUtils.stringToDateMultiParsers( ((TimePeriodType) frequencyStandardTypeA.getValidTime().getAbstractTimePrimitive().getValue()) .getBeginPosition().getValue().get(0)) )); FrequencyStandardType frequencyStandardTypeB = mapper.from(logItem); assertThat(frequencyStandardTypeB.getStandardType().getValue(), equalTo(logItem.getType())); assertThat(frequencyStandardTypeB.getStandardType().getCodeSpace(), equalTo("eGeodesy/frequencyStandardType")); assertThat(frequencyStandardTypeB.getNotes(), equalTo(logItem.getNotes())); assertThat(GMLDateUtils.stringToDateMultiParsers( ((TimePeriodType) frequencyStandardTypeB.getValidTime().getAbstractTimePrimitive().getValue()) .getBeginPosition().getValue().get(0)), equalTo(logItem.getEffectiveDates().getFrom())); } }
GeoscienceAustralia/geodesy-domain-model
gws-core/src/test/java/au/gov/ga/geodesy/support/mapper/orika/geodesyml/FrequencyStandardMapperTest.java
Java
bsd-3-clause
2,927
package org.xsaas.xstat.dao; import java.util.List; import org.xsaas.xstat.po.AddressCatalogInfo; public interface IAddressCatalogInfoDao { /** * ±£´æͨѶ¼·ÖÀàÐÅÏ¢ * @param data ͨѶ¼·ÖÀàÐÅÏ¢ */ public void saveAddressCatalogInfo(AddressCatalogInfo data); /** * ¸üÐÂͨѶ¼·ÖÀàÐÅÏ¢ * @param data ͨѶ¼·ÖÀàÐÅÏ¢ */ public void updateAddressCatalogInfo(AddressCatalogInfo data); /** * ɾ³ýͨѶ¼·ÖÀàÐÅÏ¢ * @param data ͨѶ¼·ÖÀàÐÅÏ¢ */ public void deleteAddressCatalogInfo(AddressCatalogInfo data); /** * »ñȡͨѶ¼·ÖÀàÐÅÏ¢ * @param acID Îʾí±àºÅ * @return ͨѶ¼·ÖÀàÐÅÏ¢ */ public AddressCatalogInfo getAddressCatalogInfo(Long acID); /** * »ñȡͨѶ¼·ÖÀàÐÅÏ¢Áбí * @return ͨѶ¼·ÖÀàÐÅÏ¢Áбí */ public List<AddressCatalogInfo> getAddressCatalogInfoList(); /** * ÐÅÏ¢×ÜÊý * @return ÊýÁ¿ */ public int getAddressCatalogInfoTotal(); /** * ·ÖÒ³ÐÅÏ¢ * @param firstResult ¿ªÊ¼Êý * @param maxResult ×î´óÊý * @return ÐÅÏ¢½á¹û */ public List<AddressCatalogInfo> findAddressCatalogInfoByPage(final int firstResult, final int maxResult); /** * ÐÅÏ¢×ÜÊý * @return ÊýÁ¿ */ public int getTotalByDelStatus(); /** * ·ÖÒ³ÐÅÏ¢ * @param firstResult ¿ªÊ¼Êý * @param maxResult ×î´óÊý * @return ÐÅÏ¢½á¹û */ public List<AddressCatalogInfo> findPageByDelStatus(final int firstResult, final int maxResult); }
wangxin39/xstat
XStatAPI/src/org/xsaas/xstat/dao/IAddressCatalogInfoDao.java
Java
bsd-3-clause
1,373
package com.github.phenomics.ontolib.io.obo; /** * Representation of a stanza entry starting with <code>is_cyclic</code>. * * @author <a href="mailto:manuel.holtgrewe@bihealth.de">Manuel Holtgrewe</a> */ public final class StanzaEntryIsCyclic extends StanzaEntry { /** Boolean value of the stanza entry. */ private final boolean value; /** * Constructor. * * @param value The boolean value of the stanza. * @param trailingModifier Optional {@link TrailingModifier} of the stanza entry, * <code>null</code> for none. * @param comment Optional comment string of the stanza entry, <code>null</code> for none. */ public StanzaEntryIsCyclic(boolean value, TrailingModifier trailingModifier, String comment) { super(StanzaEntryType.IS_CYCLIC, trailingModifier, comment); this.value = value; } /** * @return The entry's boolean value. */ public boolean getValue() { return value; } @Override public String toString() { return "StanzaEntryIsCyclic [value=" + value + ", getType()=" + getType() + ", getTrailingModifier()=" + getTrailingModifier() + ", getComment()=" + getComment() + "]"; } }
Phenomics/ontolib
ontolib-io/src/main/java/com/github/phenomics/ontolib/io/obo/StanzaEntryIsCyclic.java
Java
bsd-3-clause
1,183
package com.vtence.mario; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class BrowserDriver implements WebElementLocator { private final Prober prober; private final WebDriver webDriver; private final GesturePerformer gesturePerformer; public BrowserDriver(Prober prober, WebDriver webDriver) { this.prober = prober; this.webDriver = webDriver; this.gesturePerformer = new WebRobot(webDriver); } public WebDriver.Navigation navigate() { return webDriver.navigate(); } public WebElementDriver element(By criteria) { return new WebElementDriver(new ElementFinder(webDriver, criteria), prober, gesturePerformer); } /** * For those times you can't avoid it */ public void pause(long millis) { gesturePerformer.perform(UserGestures.pause(millis)); } /** * For those times you don't know better */ public WebDriver wrappedDriver() { return webDriver; } public void quit() { webDriver.quit(); } }
testinfected/mario
src/main/java/com/vtence/mario/BrowserDriver.java
Java
bsd-3-clause
1,081
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; import android.content.Context; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.GuardedRunnable; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactMarker; import com.facebook.react.bridge.ReactMarkerConstants; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.common.ReactConstants; import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.modules.appregistry.AppRegistry; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.modules.deviceinfo.DeviceInfoModule; import com.facebook.react.uimanager.DisplayMetricsHolder; import com.facebook.react.uimanager.JSTouchDispatcher; import com.facebook.react.uimanager.MeasureSpecProvider; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.RootView; import com.facebook.react.uimanager.SizeMonitoringFrameLayout; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.systrace.Systrace; import javax.annotation.Nullable; /** * Default root view for catalyst apps. Provides the ability to listen for size changes so that a UI * manager can re-layout its elements. It delegates handling touch events for itself and child views * and sending those events to JS by using JSTouchDispatcher. This view is overriding {@link * ViewGroup#onInterceptTouchEvent} method in order to be notified about the events for all of its * children and it's also overriding {@link ViewGroup#requestDisallowInterceptTouchEvent} to make * sure that {@link ViewGroup#onInterceptTouchEvent} will get events even when some child view start * intercepting it. In case when no child view is interested in handling some particular touch event * this view's {@link View#onTouchEvent} will still return true in order to be notified about all * subsequent touch events related to that gesture (in case when JS code want to handle that * gesture). */ public class ReactRootView extends SizeMonitoringFrameLayout implements RootView, MeasureSpecProvider { /** * Listener interface for react root view events */ public interface ReactRootViewEventListener { /** * Called when the react context is attached to a ReactRootView. */ void onAttachedToReactInstance(ReactRootView rootView); } private @Nullable ReactInstanceManager mReactInstanceManager; private @Nullable String mJSModuleName; private @Nullable Bundle mAppProperties; private @Nullable CustomGlobalLayoutListener mCustomGlobalLayoutListener; private @Nullable ReactRootViewEventListener mRootViewEventListener; private int mRootViewTag; private boolean mIsAttachedToInstance; private boolean mShouldLogContentAppeared; private final JSTouchDispatcher mJSTouchDispatcher = new JSTouchDispatcher(this); private boolean mWasMeasured = false; private int mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); private int mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); public ReactRootView(Context context) { super(context); } public ReactRootView(Context context, AttributeSet attrs) { super(context, attrs); } public ReactRootView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.onMeasure"); try { mWidthMeasureSpec = widthMeasureSpec; mHeightMeasureSpec = heightMeasureSpec; int width = 0; int height = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); int childSize = child.getLeft() + child.getMeasuredWidth() + child.getPaddingLeft() + child.getPaddingRight(); width = Math.max(width, childSize); } } else { width = MeasureSpec.getSize(widthMeasureSpec); } int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); int childSize = child.getTop() + child.getMeasuredHeight() + child.getPaddingTop() + child.getPaddingBottom(); height = Math.max(height, childSize); } } else { height = MeasureSpec.getSize(heightMeasureSpec); } setMeasuredDimension(width, height); mWasMeasured = true; // Check if we were waiting for onMeasure to attach the root view. if (mReactInstanceManager != null && !mIsAttachedToInstance) { attachToReactInstanceManager(); } else { updateRootLayoutSpecs(mWidthMeasureSpec, mHeightMeasureSpec); } enableLayoutCalculation(); } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } } @Override public int getWidthMeasureSpec() { if (!mWasMeasured && getLayoutParams() != null && getLayoutParams().width > 0) { return MeasureSpec.makeMeasureSpec(getLayoutParams().width, MeasureSpec.EXACTLY); } return mWidthMeasureSpec; } @Override public int getHeightMeasureSpec() { if (!mWasMeasured && getLayoutParams() != null && getLayoutParams().height > 0) { return MeasureSpec.makeMeasureSpec(getLayoutParams().height, MeasureSpec.EXACTLY); } return mHeightMeasureSpec; } @Override public void onChildStartedNativeGesture(MotionEvent androidEvent) { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( ReactConstants.TAG, "Unable to dispatch touch to JS as the catalyst instance has not been attached"); return; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class) .getEventDispatcher(); mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, eventDispatcher); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { dispatchJSTouchEvent(ev); return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent ev) { dispatchJSTouchEvent(ev); super.onTouchEvent(ev); // In case when there is no children interested in handling touch event, we return true from // the root view in order to receive subsequent events related to that gesture return true; } private void dispatchJSTouchEvent(MotionEvent event) { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( ReactConstants.TAG, "Unable to dispatch touch to JS as the catalyst instance has not been attached"); return; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class) .getEventDispatcher(); mJSTouchDispatcher.handleTouchEvent(event, eventDispatcher); } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // Override in order to still receive events to onInterceptTouchEvent even when some other // views disallow that, but propagate it up the tree if possible. if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(disallowIntercept); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { // No-op since UIManagerModule handles actually laying out children. } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mIsAttachedToInstance) { getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener()); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mIsAttachedToInstance) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { getViewTreeObserver().removeOnGlobalLayoutListener(getCustomGlobalLayoutListener()); } else { getViewTreeObserver().removeGlobalOnLayoutListener(getCustomGlobalLayoutListener()); } } } @Override public void onViewAdded(View child) { super.onViewAdded(child); if (mShouldLogContentAppeared) { mShouldLogContentAppeared = false; if (mJSModuleName != null) { ReactMarker.logMarker(ReactMarkerConstants.CONTENT_APPEARED, mJSModuleName, mRootViewTag); } } } /** * {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle)} */ public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName) { startReactApplication(reactInstanceManager, moduleName, null); } /** * Schedule rendering of the react component rendered by the JS application from the given JS * module (@{param moduleName}) using provided {@param reactInstanceManager} to attach to the * JS context of that manager. Extra parameter {@param launchOptions} can be used to pass initial * properties for the react component. */ public void startReactApplication( ReactInstanceManager reactInstanceManager, String moduleName, @Nullable Bundle initialProperties) { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "startReactApplication"); try { UiThreadUtil.assertOnUiThread(); // TODO(6788889): Use POJO instead of bundle here, apparently we can't just use WritableMap // here as it may be deallocated in native after passing via JNI bridge, but we want to reuse // it in the case of re-creating the catalyst instance Assertions.assertCondition( mReactInstanceManager == null, "This root view has already been attached to a catalyst instance manager"); mReactInstanceManager = reactInstanceManager; mJSModuleName = moduleName; mAppProperties = initialProperties; if (!mReactInstanceManager.hasStartedCreatingInitialContext()) { mReactInstanceManager.createReactContextInBackground(); } attachToReactInstanceManager(); } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } } private void enableLayoutCalculation() { if (mReactInstanceManager == null) { FLog.w( ReactConstants.TAG, "Unable to enable layout calculation for uninitialized ReactInstanceManager"); return; } final ReactContext reactApplicationContext = mReactInstanceManager.getCurrentReactContext(); if (reactApplicationContext != null) { reactApplicationContext .getCatalystInstance() .getNativeModule(UIManagerModule.class) .getUIImplementation() .enableLayoutCalculationForRootNode(getRootViewTag()); } } private void updateRootLayoutSpecs(final int widthMeasureSpec, final int heightMeasureSpec) { if (mReactInstanceManager == null) { FLog.w( ReactConstants.TAG, "Unable to update root layout specs for uninitialized ReactInstanceManager"); return; } final ReactContext reactApplicationContext = mReactInstanceManager.getCurrentReactContext(); if (reactApplicationContext != null) { reactApplicationContext.runUIBackgroundRunnable( new GuardedRunnable(reactApplicationContext) { @Override public void runGuarded() { reactApplicationContext .getCatalystInstance() .getNativeModule(UIManagerModule.class) .updateRootLayoutSpecs(getRootViewTag(), widthMeasureSpec, heightMeasureSpec); } }); } } /** * Unmount the react application at this root view, reclaiming any JS memory associated with that * application. If {@link #startReactApplication} is called, this method must be called before the * ReactRootView is garbage collected (typically in your Activity's onDestroy, or in your * Fragment's onDestroyView). */ public void unmountReactApplication() { if (mReactInstanceManager != null && mIsAttachedToInstance) { mReactInstanceManager.detachRootView(this); mIsAttachedToInstance = false; } mShouldLogContentAppeared = false; } public void onAttachedToReactInstance() { if (mRootViewEventListener != null) { mRootViewEventListener.onAttachedToReactInstance(this); } } public void setEventListener(ReactRootViewEventListener eventListener) { mRootViewEventListener = eventListener; } /* package */ String getJSModuleName() { return Assertions.assertNotNull(mJSModuleName); } public @Nullable Bundle getAppProperties() { return mAppProperties; } public void setAppProperties(@Nullable Bundle appProperties) { UiThreadUtil.assertOnUiThread(); mAppProperties = appProperties; if (getRootViewTag() != 0) { runApplication(); } } /** * Calls into JS to start the React application. Can be called multiple times with the * same rootTag, which will re-render the application from the root. */ /* package */ void runApplication() { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.runApplication"); try { if (mReactInstanceManager == null || !mIsAttachedToInstance) { return; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); if (reactContext == null) { return; } CatalystInstance catalystInstance = reactContext.getCatalystInstance(); WritableNativeMap appParams = new WritableNativeMap(); appParams.putDouble("rootTag", getRootViewTag()); @Nullable Bundle appProperties = getAppProperties(); if (appProperties != null) { appParams.putMap("initialProps", Arguments.fromBundle(appProperties)); } mShouldLogContentAppeared = true; String jsAppModuleName = getJSModuleName(); catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams); } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } } /** * Is used by unit test to setup mIsAttachedToWindow flags, that will let this * view to be properly attached to catalyst instance by startReactApplication call */ @VisibleForTesting /* package */ void simulateAttachForTesting() { mIsAttachedToInstance = true; } private CustomGlobalLayoutListener getCustomGlobalLayoutListener() { if (mCustomGlobalLayoutListener == null) { mCustomGlobalLayoutListener = new CustomGlobalLayoutListener(); } return mCustomGlobalLayoutListener; } private void attachToReactInstanceManager() { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachToReactInstanceManager"); try { if (mIsAttachedToInstance) { return; } mIsAttachedToInstance = true; Assertions.assertNotNull(mReactInstanceManager).attachRootView(this); getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener()); } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } } @Override protected void finalize() throws Throwable { super.finalize(); Assertions.assertCondition( !mIsAttachedToInstance, "The application this ReactRootView was rendering was not unmounted before the " + "ReactRootView was garbage collected. This usually means that your application is " + "leaking large amounts of memory. To solve this, make sure to call " + "ReactRootView#unmountReactApplication in the onDestroy() of your hosting Activity or in " + "the onDestroyView() of your hosting Fragment."); } public int getRootViewTag() { return mRootViewTag; } public void setRootViewTag(int rootViewTag) { mRootViewTag = rootViewTag; } @Nullable public ReactInstanceManager getReactInstanceManager() { return mReactInstanceManager; } private class CustomGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener { private final Rect mVisibleViewArea; private final int mMinKeyboardHeightDetected; private int mKeyboardHeight = 0; private int mDeviceRotation = 0; private DisplayMetrics mWindowMetrics = new DisplayMetrics(); private DisplayMetrics mScreenMetrics = new DisplayMetrics(); /* package */ CustomGlobalLayoutListener() { DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(getContext().getApplicationContext()); mVisibleViewArea = new Rect(); mMinKeyboardHeightDetected = (int) PixelUtil.toPixelFromDIP(60); } @Override public void onGlobalLayout() { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { return; } checkForKeyboardEvents(); checkForDeviceOrientationChanges(); checkForDeviceDimensionsChanges(); } private void checkForKeyboardEvents() { getRootView().getWindowVisibleDisplayFrame(mVisibleViewArea); final int heightDiff = DisplayMetricsHolder.getWindowDisplayMetrics().heightPixels - mVisibleViewArea.bottom; if (mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected) { // keyboard is now showing, or the keyboard height has changed mKeyboardHeight = heightDiff; WritableMap params = Arguments.createMap(); WritableMap coordinates = Arguments.createMap(); coordinates.putDouble("screenY", PixelUtil.toDIPFromPixel(mVisibleViewArea.bottom)); coordinates.putDouble("screenX", PixelUtil.toDIPFromPixel(mVisibleViewArea.left)); coordinates.putDouble("width", PixelUtil.toDIPFromPixel(mVisibleViewArea.width())); coordinates.putDouble("height", PixelUtil.toDIPFromPixel(mKeyboardHeight)); params.putMap("endCoordinates", coordinates); sendEvent("keyboardDidShow", params); } else if (mKeyboardHeight != 0 && heightDiff <= mMinKeyboardHeightDetected) { // keyboard is now hidden mKeyboardHeight = 0; sendEvent("keyboardDidHide", null); } } private void checkForDeviceOrientationChanges() { final int rotation = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay().getRotation(); if (mDeviceRotation == rotation) { return; } mDeviceRotation = rotation; emitOrientationChanged(rotation); } private void checkForDeviceDimensionsChanges() { // Get current display metrics. DisplayMetricsHolder.initDisplayMetrics(getContext()); // Check changes to both window and screen display metrics since they may not update at the same time. if (!areMetricsEqual(mWindowMetrics, DisplayMetricsHolder.getWindowDisplayMetrics()) || !areMetricsEqual(mScreenMetrics, DisplayMetricsHolder.getScreenDisplayMetrics())) { mWindowMetrics.setTo(DisplayMetricsHolder.getWindowDisplayMetrics()); mScreenMetrics.setTo(DisplayMetricsHolder.getScreenDisplayMetrics()); emitUpdateDimensionsEvent(); } } private boolean areMetricsEqual(DisplayMetrics displayMetrics, DisplayMetrics otherMetrics) { if (Build.VERSION.SDK_INT >= 17) { return displayMetrics.equals(otherMetrics); } else { // DisplayMetrics didn't have an equals method before API 17. // Check all public fields manually. return displayMetrics.widthPixels == otherMetrics.widthPixels && displayMetrics.heightPixels == otherMetrics.heightPixels && displayMetrics.density == otherMetrics.density && displayMetrics.densityDpi == otherMetrics.densityDpi && displayMetrics.scaledDensity == otherMetrics.scaledDensity && displayMetrics.xdpi == otherMetrics.xdpi && displayMetrics.ydpi == otherMetrics.ydpi; } } private void emitOrientationChanged(final int newRotation) { String name; double rotationDegrees; boolean isLandscape = false; switch (newRotation) { case Surface.ROTATION_0: name = "portrait-primary"; rotationDegrees = 0.0; break; case Surface.ROTATION_90: name = "landscape-primary"; rotationDegrees = -90.0; isLandscape = true; break; case Surface.ROTATION_180: name = "portrait-secondary"; rotationDegrees = 180.0; break; case Surface.ROTATION_270: name = "landscape-secondary"; rotationDegrees = 90.0; isLandscape = true; break; default: return; } WritableMap map = Arguments.createMap(); map.putString("name", name); map.putDouble("rotationDegrees", rotationDegrees); map.putBoolean("isLandscape", isLandscape); sendEvent("namedOrientationDidChange", map); } private void emitUpdateDimensionsEvent() { mReactInstanceManager .getCurrentReactContext() .getNativeModule(DeviceInfoModule.class) .emitUpdateDimensionsEvent(); } private void sendEvent(String eventName, @Nullable WritableMap params) { if (mReactInstanceManager != null) { mReactInstanceManager.getCurrentReactContext() .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } } } }
cdlewis/react-native
ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
Java
bsd-3-clause
23,061
/******************************************************************************* * Copyright (c) 2016 AT&T Intellectual Property. All rights reserved. *******************************************************************************/ package com.att.rosetta.marshal; import java.util.Iterator; import java.util.List; import com.att.rosetta.Ladder; import com.att.rosetta.Marshal; import com.att.rosetta.ParseException; import com.att.rosetta.Parsed; public abstract class FieldArray<T,S> extends Marshal<T> { private DataWriter<S> dataWriter; private String name; public FieldArray(String name, DataWriter<S> dw) { this.name = name; dataWriter = dw; } @SuppressWarnings("unchecked") @Override public Parsed<State> parse(T t, Parsed<State> parsed) throws ParseException { Ladder<Iterator<?>> ladder = parsed.state.ladder; Iterator<?> iter = ladder.peek(); if(iter==null) { List<S> list = data(t); if(list.isEmpty() && parsed.state.smallest) { ladder.push(DONE_ITERATOR); } else { ladder.push(new ListIterator<S>(list)); parsed.event = START_ARRAY; parsed.name = name; } } else if (DONE_ITERATOR.equals(iter)) { } else { ladder.ascend(); // look at field info Iterator<?> memIter = ladder.peek(); ListIterator<S> mems = (ListIterator<S>)iter; S mem; if(memIter==null) { mem=mems.next(); } else if(!DONE_ITERATOR.equals(memIter)) { mem=mems.peek(); } else if(iter.hasNext()) { mem=null; ladder.push(null); } else { mem=null; } if(mem!=null) { parsed.isString=dataWriter.write(mem, parsed.sb); parsed.event = NEXT; } ladder.descend(); if(mem==null) { if(iter.hasNext()) { parsed.event = NEXT; } else { parsed.event = END_ARRAY; ladder.push(DONE_ITERATOR); } } } return parsed; // if unchanged, then it will end process } protected abstract List<S> data(T t); }
att/AAF
inno/rosetta/src/main/java/com/att/rosetta/marshal/FieldArray.java
Java
bsd-3-clause
1,940
package org.apollo.update; import org.jboss.netty.channel.Channel; /** * A specialised request which contains a channel as well as the request object * itself. * @author Graham * @param <T> The type of request. */ public final class ChannelRequest<T> implements Comparable<ChannelRequest<T>> { /** * The channel. */ private final Channel channel; /** * The request. */ private final T request; /** * Creates a new channel request. * @param channel The channel. * @param request The request. */ public ChannelRequest(Channel channel, T request) { this.channel = channel; this.request = request; } /** * Gets the channel. * @return The channel. */ public Channel getChannel() { return channel; } /** * Gets the request. * @return The request. */ public T getRequest() { return request; } @SuppressWarnings("unchecked") @Override public int compareTo(ChannelRequest<T> o) { if (request instanceof Comparable<?> && o.request instanceof Comparable<?>) { return ((Comparable<T>) request).compareTo(o.request); } return 0; } }
AWildridge/ProtoScape
src/org/apollo/update/ChannelRequest.java
Java
isc
1,096
package AsposeCellsExamples.TechnicalArticles; import java.io.ByteArrayInputStream; import com.aspose.cells.Cells; import com.aspose.cells.ConditionalFormattingIcon; import com.aspose.cells.IconSetType; import com.aspose.cells.Workbook; import com.aspose.cells.Worksheet; import AsposeCellsExamples.Utils; public class AddConditionalIconsSet { public static void main(String[] args) throws Exception { // The path to the documents directory. String dataDir = Utils.getSharedDataDir(AddConditionalIconsSet.class) + "TechnicalArticles/"; // Instantiate an instance of Workbook Workbook workbook = new Workbook(); // Get the first worksheet (default worksheet) in the workbook Worksheet worksheet = workbook.getWorksheets().get(0); // Get the cells Cells cells = worksheet.getCells(); // Set the columns widths (A, B and C) worksheet.getCells().setColumnWidth(0, 24); worksheet.getCells().setColumnWidth(1, 24); worksheet.getCells().setColumnWidth(2, 24); // Input date into the cells cells.get("A1").setValue("KPIs"); cells.get("A2").setValue("Total Turnover (Sales at List)"); cells.get("A3").setValue("Total Gross Margin %"); cells.get("A4").setValue("Total Net Margin %"); cells.get("B1").setValue("UA Contract Size Group 4"); cells.get("B2").setValue(19551794); cells.get("B3").setValue(11.8070745566204); cells.get("B4").setValue(11.858589818569); cells.get("C1").setValue("UA Contract Size Group 3"); cells.get("C2").setValue(8150131.66666667); cells.get("C3").setValue(10.3168384396244); cells.get("C4").setValue(11.3326931937091); // Get the conditional icon's image data byte[] imagedata = ConditionalFormattingIcon.getIconImageData(IconSetType.TRAFFIC_LIGHTS_31, 0); // Create a stream based on the image data ByteArrayInputStream stream = new ByteArrayInputStream(imagedata); // Add the picture to the cell based on the stream worksheet.getPictures().add(1, 1, stream); // Get the conditional icon's image data byte[] imagedata1 = ConditionalFormattingIcon.getIconImageData(IconSetType.ARROWS_3, 2); // Create a stream based on the image data ByteArrayInputStream stream1 = new ByteArrayInputStream(imagedata1); // Add the picture to the cell based on the stream worksheet.getPictures().add(1, 2, stream1); // Get the conditional icon's image data byte[] imagedata2 = ConditionalFormattingIcon.getIconImageData(IconSetType.SYMBOLS_3, 0); // Create a stream based on the image data ByteArrayInputStream stream2 = new ByteArrayInputStream(imagedata2); // Add the picture to the cell based on the stream worksheet.getPictures().add(2, 1, stream2); // Get the conditional icon's image data byte[] imagedata3 = ConditionalFormattingIcon.getIconImageData(IconSetType.STARS_3, 0); // Create a stream based on the image data ByteArrayInputStream stream3 = new ByteArrayInputStream(imagedata3); // Add the picture to the cell based on the stream worksheet.getPictures().add(2, 2, stream3); // Get the conditional icon's image data byte[] imagedata4 = ConditionalFormattingIcon.getIconImageData(IconSetType.BOXES_5, 1); // Create a stream based on the image data ByteArrayInputStream stream4 = new ByteArrayInputStream(imagedata4); // Add the picture to the cell based on the stream worksheet.getPictures().add(3, 1, stream4); // Get the conditional icon's image data byte[] imagedata5 = ConditionalFormattingIcon.getIconImageData(IconSetType.FLAGS_3, 1); // Create a stream based on the image data ByteArrayInputStream stream5 = new ByteArrayInputStream(imagedata5); // Add the picture to the cell based on the stream worksheet.getPictures().add(3, 2, stream5); // Save the Excel file workbook.save(dataDir + "ACIconsSet_out.xlsx"); } }
aspose-cells/Aspose.Cells-for-Java
Examples/src/AsposeCellsExamples/TechnicalArticles/AddConditionalIconsSet.java
Java
mit
3,778
package cn.edu.gdut.zaoying.Option.yAxis.nameTextStyle; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FontStyleString { String value() default ""; }
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/yAxis/nameTextStyle/FontStyleString.java
Java
mit
349
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.cosmos.models; import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Connection string for the Cosmos DB account. */ @Immutable public final class DatabaseAccountConnectionString { @JsonIgnore private final ClientLogger logger = new ClientLogger(DatabaseAccountConnectionString.class); /* * Value of the connection string */ @JsonProperty(value = "connectionString", access = JsonProperty.Access.WRITE_ONLY) private String connectionString; /* * Description of the connection string */ @JsonProperty(value = "description", access = JsonProperty.Access.WRITE_ONLY) private String description; /** * Get the connectionString property: Value of the connection string. * * @return the connectionString value. */ public String connectionString() { return this.connectionString; } /** * Get the description property: Description of the connection string. * * @return the description value. */ public String description() { return this.description; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
selvasingh/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-cosmos/src/main/java/com/azure/resourcemanager/cosmos/models/DatabaseAccountConnectionString.java
Java
mit
1,587
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * 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 * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. 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 * nbbuild/licenses/CDDL-GPL-2-CP. 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. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * 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 do not 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 org.netbeans.modules.web.project.ant; import java.util.ArrayList; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.Localizer; /** * Ant task that extends org.apache.jasper.JspC and dumps smap for easier error reporting. * * @author Petr Jiricka */ public class JspC extends org.apache.jasper.JspC { private static final String SOURCE_VM = "-compilerSourceVM"; // NOI18N private static final String TARGET_VM = "-compilerTargetVM"; // NOI18N private static final String JAVA_ENCODING = "-javaEncoding"; // NOI18N private static final String SCHEMAS = "-schemas"; // NOI18N private static final String DTDS = "-dtds"; // NOI18N private static final String SYS_CLASSPATH = "-sysClasspath"; // NOI18N public static void main(String arg[]) { if (arg.length == 0) { System.out.println(Localizer.getMessage("jspc.usage")); // NOI18N } else { try { JspC jspc = new JspC(); ArrayList args = new ArrayList(); for (int i = 0; i < arg.length; i++) { String oldArg = arg[i]; if (oldArg.contains(TARGET_VM)) { String version = oldArg.substring(TARGET_VM.length()).trim(); version = adjustVersion(version); jspc.setCompilerTargetVM(version); } else if (oldArg.contains(SOURCE_VM)) { String version = oldArg.substring(SOURCE_VM.length()).trim(); version = adjustVersion(version); jspc.setCompilerSourceVM(version); } else if (oldArg.contains(JAVA_ENCODING)) { String javaEncoding = oldArg.substring(JAVA_ENCODING.length()).trim(); jspc.setJavaEncoding(javaEncoding); } else if (oldArg.contains(SCHEMAS)) { String schemas = oldArg.substring(SCHEMAS.length()).trim(); JspC.setSchemaResourcePrefix(schemas); } else if (oldArg.contains(DTDS)) { String dtds = oldArg.substring(DTDS.length()).trim(); JspC.setDtdResourcePrefix(dtds); } else if (oldArg.contains(SYS_CLASSPATH)) { String sysClassPath = oldArg.substring(SYS_CLASSPATH.length()).trim(); jspc.setSystemClassPath(sysClassPath); } else { args.add(oldArg); } } String[] newArgs = new String[args.size()]; newArgs = (String[]) args.toArray(newArgs); jspc.setArgs(newArgs); jspc.execute(); } catch (JasperException je) { System.err.println(je); //System.err.println(je.getMessage()); System.exit(1); } } } // #135568 private static String adjustVersion(String version) { if ("1.6".equals(version)) { // NOI18N return "1.5"; // NOI18N } return version; } public boolean isSmapSuppressed() { return false; } public boolean isSmapDumped() { return true; } public boolean getMappedFile() { return true; } }
wolfoux/soleil
web/NetBeans 7.3.1/enterprise/ant/sources/org/netbeans/modules/web/project/ant/JspC.java
Java
mit
5,666
package seedu.address.logic.commands; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_PHONE_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND; import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.logic.commands.CommandTestUtil.showFirstPersonOnly; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_PERSON; import static seedu.address.testutil.TypicalIndexes.INDEX_SECOND_PERSON; import static seedu.address.testutil.TypicalPersons.getTypicalAddressBook; import org.junit.Test; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.CommandHistory; import seedu.address.logic.UndoRedoStack; import seedu.address.logic.commands.EditCommand.EditPersonDescriptor; import seedu.address.model.AddressBook; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.person.Person; import seedu.address.model.person.ReadOnlyPerson; import seedu.address.testutil.EditPersonDescriptorBuilder; import seedu.address.testutil.PersonBuilder; /** * Contains integration tests (interaction with the Model) and unit tests for EditCommand. */ public class EditCommandTest { private Model model = new ModelManager(getTypicalAddressBook(), new UserPrefs()); @Test public void execute_allFieldsSpecifiedUnfilteredList_success() throws Exception { Person editedPerson = new PersonBuilder().build(); EditPersonDescriptor descriptor = new EditPersonDescriptorBuilder(editedPerson).build(); EditCommand editCommand = prepareCommand(INDEX_FIRST_PERSON, descriptor); String expectedMessage = String.format(EditCommand.MESSAGE_EDIT_PERSON_SUCCESS, editedPerson); Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()), new UserPrefs()); expectedModel.updatePerson(model.getFilteredPersonList().get(0), editedPerson); assertCommandSuccess(editCommand, model, expectedMessage, expectedModel); } @Test public void execute_someFieldsSpecifiedUnfilteredList_success() throws Exception { Index indexLastPerson = Index.fromOneBased(model.getFilteredPersonList().size()); ReadOnlyPerson lastPerson = model.getFilteredPersonList().get(indexLastPerson.getZeroBased()); PersonBuilder personInList = new PersonBuilder(lastPerson); Person editedPerson = personInList.withName(VALID_NAME_BOB).withPhone(VALID_PHONE_BOB) .withTags(VALID_TAG_HUSBAND).build(); EditPersonDescriptor descriptor = new EditPersonDescriptorBuilder().withName(VALID_NAME_BOB) .withPhone(VALID_PHONE_BOB).withTags(VALID_TAG_HUSBAND).build(); EditCommand editCommand = prepareCommand(indexLastPerson, descriptor); String expectedMessage = String.format(EditCommand.MESSAGE_EDIT_PERSON_SUCCESS, editedPerson); Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()), new UserPrefs()); expectedModel.updatePerson(lastPerson, editedPerson); assertCommandSuccess(editCommand, model, expectedMessage, expectedModel); } @Test public void execute_noFieldSpecifiedUnfilteredList_success() { EditCommand editCommand = prepareCommand(INDEX_FIRST_PERSON, new EditPersonDescriptor()); ReadOnlyPerson editedPerson = model.getFilteredPersonList().get(INDEX_FIRST_PERSON.getZeroBased()); String expectedMessage = String.format(EditCommand.MESSAGE_EDIT_PERSON_SUCCESS, editedPerson); Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()), new UserPrefs()); assertCommandSuccess(editCommand, model, expectedMessage, expectedModel); } @Test public void execute_filteredList_success() throws Exception { showFirstPersonOnly(model); ReadOnlyPerson personInFilteredList = model.getFilteredPersonList().get(INDEX_FIRST_PERSON.getZeroBased()); Person editedPerson = new PersonBuilder(personInFilteredList).withName(VALID_NAME_BOB).build(); EditCommand editCommand = prepareCommand(INDEX_FIRST_PERSON, new EditPersonDescriptorBuilder().withName(VALID_NAME_BOB).build()); String expectedMessage = String.format(EditCommand.MESSAGE_EDIT_PERSON_SUCCESS, editedPerson); Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()), new UserPrefs()); expectedModel.updatePerson(model.getFilteredPersonList().get(0), editedPerson); assertCommandSuccess(editCommand, model, expectedMessage, expectedModel); } @Test public void execute_duplicatePersonUnfilteredList_failure() { Person firstPerson = new Person(model.getFilteredPersonList().get(INDEX_FIRST_PERSON.getZeroBased())); EditPersonDescriptor descriptor = new EditPersonDescriptorBuilder(firstPerson).build(); EditCommand editCommand = prepareCommand(INDEX_SECOND_PERSON, descriptor); assertCommandFailure(editCommand, model, EditCommand.MESSAGE_DUPLICATE_PERSON); } @Test public void execute_duplicatePersonFilteredList_failure() { showFirstPersonOnly(model); // edit person in filtered list into a duplicate in address book ReadOnlyPerson personInList = model.getAddressBook().getPersonList().get(INDEX_SECOND_PERSON.getZeroBased()); EditCommand editCommand = prepareCommand(INDEX_FIRST_PERSON, new EditPersonDescriptorBuilder(personInList).build()); assertCommandFailure(editCommand, model, EditCommand.MESSAGE_DUPLICATE_PERSON); } @Test public void execute_invalidPersonIndexUnfilteredList_failure() { Index outOfBoundIndex = Index.fromOneBased(model.getFilteredPersonList().size() + 1); EditPersonDescriptor descriptor = new EditPersonDescriptorBuilder().withName(VALID_NAME_BOB).build(); EditCommand editCommand = prepareCommand(outOfBoundIndex, descriptor); assertCommandFailure(editCommand, model, Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } /** * Edit filtered list where index is larger than size of filtered list, * but smaller than size of address book */ @Test public void execute_invalidPersonIndexFilteredList_failure() { showFirstPersonOnly(model); Index outOfBoundIndex = INDEX_SECOND_PERSON; // ensures that outOfBoundIndex is still in bounds of address book list assertTrue(outOfBoundIndex.getZeroBased() < model.getAddressBook().getPersonList().size()); EditCommand editCommand = prepareCommand(outOfBoundIndex, new EditPersonDescriptorBuilder().withName(VALID_NAME_BOB).build()); assertCommandFailure(editCommand, model, Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } @Test public void equals() { final EditCommand standardCommand = new EditCommand(INDEX_FIRST_PERSON, DESC_AMY); // same values -> returns true EditPersonDescriptor copyDescriptor = new EditPersonDescriptor(DESC_AMY); EditCommand commandWithSameValues = new EditCommand(INDEX_FIRST_PERSON, copyDescriptor); assertTrue(standardCommand.equals(commandWithSameValues)); // same object -> returns true assertTrue(standardCommand.equals(standardCommand)); // null -> returns false assertFalse(standardCommand.equals(null)); // different types -> returns false assertFalse(standardCommand.equals(new ClearCommand())); // different index -> returns false assertFalse(standardCommand.equals(new EditCommand(INDEX_SECOND_PERSON, DESC_AMY))); // different descriptor -> returns false assertFalse(standardCommand.equals(new EditCommand(INDEX_FIRST_PERSON, DESC_BOB))); } /** * Returns an {@code EditCommand} with parameters {@code index} and {@code descriptor} */ private EditCommand prepareCommand(Index index, EditPersonDescriptor descriptor) { EditCommand editCommand = new EditCommand(index, descriptor); editCommand.setData(model, new CommandHistory(), new UndoRedoStack()); return editCommand; } }
damithc/addressbook-level4
src/test/java/seedu/address/logic/commands/EditCommandTest.java
Java
mit
8,698
package com.wantedtech.common.xpresso.web.service; /* * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.*; class ChunkedInputStream extends LeftOverInputStream { ChunkedInputStream (ExchangeImpl t, InputStream src) { super (t, src); } private int remaining; /* true when a chunk header needs to be read */ private boolean needToReadHeader = true; final static char CR = '\r'; final static char LF = '\n'; /* * Maximum chunk header size of 2KB + 2 bytes for CRLF */ private final static int MAX_CHUNK_HEADER_SIZE = 2050; private int numeric (char[] arr, int nchars) throws IOException { assert arr.length >= nchars; int len = 0; for (int i=0; i<nchars; i++) { char c = arr[i]; int val=0; if (c>='0' && c <='9') { val = c - '0'; } else if (c>='a' && c<= 'f') { val = c - 'a' + 10; } else if (c>='A' && c<= 'F') { val = c - 'A' + 10; } else { throw new IOException ("invalid chunk length"); } len = len * 16 + val; } return len; } /* read the chunk header line and return the chunk length * any chunk extensions are ignored */ private int readChunkHeader () throws IOException { boolean gotCR = false; int c; char[] len_arr = new char [16]; int len_size = 0; boolean end_of_len = false; int read = 0; while ((c=in.read())!= -1) { char ch = (char) c; read++; if ((len_size == len_arr.length -1) || (read > MAX_CHUNK_HEADER_SIZE)) { throw new IOException ("invalid chunk header"); } if (gotCR) { if (ch == LF) { int l = numeric (len_arr, len_size); return l; } else { gotCR = false; } if (!end_of_len) { len_arr[len_size++] = ch; } } else { if (ch == CR) { gotCR = true; } else if (ch == ';') { end_of_len = true; } else if (!end_of_len) { len_arr[len_size++] = ch; } } } throw new IOException ("end of stream reading chunk header"); } protected int readImpl (byte[]b, int off, int len) throws IOException { if (eof) { return -1; } if (needToReadHeader) { remaining = readChunkHeader(); if (remaining == 0) { eof = true; consumeCRLF(); t.getServerImpl().requestCompleted (t.getConnection()); return -1; } needToReadHeader = false; } if (len > remaining) { len = remaining; } int n = in.read(b, off, len); if (n > -1) { remaining -= n; } if (remaining == 0) { needToReadHeader = true; consumeCRLF(); } return n; } private void consumeCRLF () throws IOException { char c; c = (char)in.read(); /* CR */ if (c != CR) { throw new IOException ("invalid chunk end"); } c = (char)in.read(); /* LF */ if (c != LF) { throw new IOException ("invalid chunk end"); } } /** * returns the number of bytes available to read in the current chunk * which may be less than the real amount, but we'll live with that * limitation for the moment. It only affects potential efficiency * rather than correctness. */ public int available () throws IOException { if (eof || closed) { return 0; } int n = in.available(); return n > remaining? remaining: n; } /* called after the stream is closed to see if bytes * have been read from the underlying channel * and buffered internally */ public boolean isDataBuffered () throws IOException { assert eof; return in.available() > 0; } public boolean markSupported () {return false;} public void mark (int l) { } public void reset () throws IOException { throw new IOException ("mark/reset not supported"); } }
WantedTechnologies/xpresso
src/main/java/com/wantedtech/common/xpresso/web/service/ChunkedInputStream.java
Java
mit
5,701
package Dec2020Leetcode; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; public class _0867TransposeMatrix { public static void main(String[] args) { int[][] out = transpose(new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } }); for (int i = 0; i < out.length; i++) { System.out.println(Arrays.toString(out[i])); } out = transpose(new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 } }); for (int i = 0; i < out.length; i++) { System.out.println(Arrays.toString(out[i])); } } public static int[][] transpose(int[][] A) { if (A == null || A.length == 0) return A; int rows = A.length - 1; int cols = A[0].length - 1; int[][] output = new int[cols + 1][rows + 1]; Queue<Integer> q = new LinkedList<Integer>(); int currCol = 0; while (currCol <= cols) { for (int i = 0; i <= rows; i++) { q.offer(A[i][currCol]); } currCol++; } for (int i = 0; i < output.length; i++) { for (int j = 0; j < output[0].length; j++) { output[i][j] = q.poll(); } } return output; } }
darshanhs90/Java-Coding
src/Dec2020Leetcode/_0867TransposeMatrix.java
Java
mit
1,103
package com.example.winxos.net_server; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.DataSetObserver; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CheckedTextView; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class main extends Activity { private EditText ep,em,eip; private ListView lv; private DatagramSocket ds; private MulticastSocket ms; public static final String BROAD="WS.BROAD"; private InetAddress lip=null; private String msg=""; private List<String> ips; ArrayAdapter<String> aa; final int port= 10001; CheckBox cb; @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); //判断wifi是否开启 if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); } WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); try { lip=InetAddress.getByName((ipAddress & 0xFF ) + "." + ((ipAddress >> 8 ) & 0xFF) + "." + ((ipAddress >> 16 ) & 0xFF) + "." + ( ipAddress >> 24 & 0xFF) ); } catch (UnknownHostException e) { e.printStackTrace(); } String ip = "local ip:"+lip.toString() ; Toast.makeText(this,ip,Toast.LENGTH_LONG).show(); ep = (EditText) super.findViewById(R.id.editText3); em = (EditText) super.findViewById(R.id.editText); lv=(ListView)super.findViewById(R.id.listView); ips=new ArrayList<String>(); aa=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, ips); lv.setAdapter(aa); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private Handler update_view=new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle data=msg.getData(); String s=data.getString("value"); for(int i=0;i<aa.getCount();i++) { if(aa.getItem(i).equals(s)) return; } aa.add(s); aa.notifyDataSetChanged(); } }; public void listen(View v) { if(ms==null) try { ms=new MulticastSocket(port); } catch (IOException e) { e.printStackTrace(); } new Thread(new Runnable(){ //receive @Override public void run() { try { while(true) { byte [] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); ms.receive(dp); if(ip_equal(dp.getAddress().getAddress(),lip.getAddress())){ //local data continue; } Message m=new Message(); Bundle data=new Bundle(); String ts=dp.getAddress().toString(); data.putString("value",ts.substring(1,ts.length())); //start , end m.setData(data); update_view.sendMessage(m); Intent ii=new Intent(BROAD); msg=dp.getAddress().toString()+":"+new String(buf); ii.putExtra("msg",msg); sendBroadcast(ii);//update other activity } } catch (Exception e) { e.printStackTrace(); } } }).start(); } public boolean ip_equal(byte[]a,byte[]b) { return a[0]==b[0] && a[1]==b[1] && a[2]==b[2] && a[3]==b[3]; } public void sendto(View v) { new Thread(new Runnable() { @Override public void run() { String msg = em.getText().toString(); for(int i=0;i<aa.getCount();i++) { View vb=lv.getChildAt(i); CheckedTextView tv = (CheckedTextView)vb.findViewById(android.R.id.text1); if(tv.isChecked()) { try { ms.send(new DatagramPacket(msg.getBytes(), msg.length(), InetAddress.getByName(aa.getItem(i)), port)); } catch (IOException e) { e.printStackTrace(); } } } } }).start(); } public void broadcast(View v) { try { ms=new MulticastSocket(port); //broadcast ms.setTimeToLive(3); //retry times Timer mTimer=new Timer(); mTimer.schedule(new TimerTask() {//broad cast @Override public void run() { String msg="server"; try { ms.send(new DatagramPacket( msg.getBytes(), msg.length(), InetAddress.getByName("255.255.255.255"), port)); } catch (IOException e) { e.printStackTrace(); } } }, 0, 1000); } catch (IOException e) { e.printStackTrace(); } } public void viewlogs(View v) { Intent ii=new Intent(); ii.setClass(this,logs.class); startActivity(ii); } }
winxos/android
net_server/app/src/main/java/com/example/winxos/net_server/main.java
Java
mit
7,382
/** * 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.v2018_07_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * The ARP table associated with the ExpressRouteCircuit. */ public class ExpressRouteCircuitArpTable { /** * Entry age in minutes. */ @JsonProperty(value = "age") private Integer age; /** * Interface address. */ @JsonProperty(value = "interface") private String interfaceProperty; /** * The IP address. */ @JsonProperty(value = "ipAddress") private String ipAddress; /** * The MAC address. */ @JsonProperty(value = "macAddress") private String macAddress; /** * Get entry age in minutes. * * @return the age value */ public Integer age() { return this.age; } /** * Set entry age in minutes. * * @param age the age value to set * @return the ExpressRouteCircuitArpTable object itself. */ public ExpressRouteCircuitArpTable withAge(Integer age) { this.age = age; return this; } /** * Get interface address. * * @return the interfaceProperty value */ public String interfaceProperty() { return this.interfaceProperty; } /** * Set interface address. * * @param interfaceProperty the interfaceProperty value to set * @return the ExpressRouteCircuitArpTable object itself. */ public ExpressRouteCircuitArpTable withInterfaceProperty(String interfaceProperty) { this.interfaceProperty = interfaceProperty; return this; } /** * Get the IP address. * * @return the ipAddress value */ public String ipAddress() { return this.ipAddress; } /** * Set the IP address. * * @param ipAddress the ipAddress value to set * @return the ExpressRouteCircuitArpTable object itself. */ public ExpressRouteCircuitArpTable withIpAddress(String ipAddress) { this.ipAddress = ipAddress; return this; } /** * Get the MAC address. * * @return the macAddress value */ public String macAddress() { return this.macAddress; } /** * Set the MAC address. * * @param macAddress the macAddress value to set * @return the ExpressRouteCircuitArpTable object itself. */ public ExpressRouteCircuitArpTable withMacAddress(String macAddress) { this.macAddress = macAddress; return this; } }
navalev/azure-sdk-for-java
sdk/network/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/ExpressRouteCircuitArpTable.java
Java
mit
2,773
package org.sidoh.peak_detection; /** * Something that gets notified when a peak has been detected. * * @author chris * */ public interface PeakListener { public void peakDetected(int index, double value); }
sidoh/song_recognition
src/java/org/sidoh/peak_detection/PeakListener.java
Java
mit
216
package org.osiam.addons.administration.model.command; import java.util.ArrayList; import java.util.List; import org.hibernate.validator.constraints.NotEmpty; import org.osiam.resources.scim.Group; import org.osiam.resources.scim.MemberRef; import org.osiam.resources.scim.UpdateGroup; /** * Command object for the group update view. */ public class UpdateGroupCommand { private String id; @NotEmpty private String displayName; private String externalId; private List<String> memberIds = new ArrayList<String>(); /** * Creates a new UpdateGroupCommand based on the given {@link Group}. * * @param group * the user */ public UpdateGroupCommand(Group group) { setId(group.getId()); setExternalId(group.getExternalId()); setDisplayName(group.getDisplayName()); if (group.getMembers() != null) { for (MemberRef ref : group.getMembers()) { memberIds.add(ref.getValue()); } } } /** * Creates a new UpdateGroupCommand. */ public UpdateGroupCommand() { } /** * Returns the displayname. * * @return the the displayname */ public String getDisplayName() { return displayName; } /** * Sets the displayname. * * @param displayName * the displayname to set */ public void setDisplayName(String displayName) { this.displayName = displayName; } public List<String> getMemberIds() { return memberIds; } public void setMemberIds(List<String> memberIds) { this.memberIds = memberIds; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } /** * Returns a SCIM {@link UpdateGroup} based on this command. * * @return the requested {@link UpdateGroup} */ public UpdateGroup getAsUpdateGroup() { UpdateGroup.Builder builder = new UpdateGroup.Builder(); builder.updateDisplayName(getDisplayName()); if (getExternalId() != null && getExternalId().equals("")) { builder.deleteExternalId(); } else { builder.updateExternalId(getExternalId()); } builder.deleteMembers(); for (String member : memberIds) { builder.addMember(member); } return builder.build(); } }
tkrille/osiam-addon-administration
src/main/java/org/osiam/addons/administration/model/command/UpdateGroupCommand.java
Java
mit
2,623
/* * Copyright (c) 2010-2015 Jakub Białek * * 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.google.code.ssm.aop.counter; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.code.ssm.aop.support.AnnotationData; import com.google.code.ssm.aop.support.AnnotationDataBuilder; import com.google.code.ssm.api.counter.UpdateCounterInCache; /** * * @author Jakub Białek * @since 2.0.0 * */ @Aspect public class UpdateCounterInCacheAdvice extends CounterInCacheBase { private static final Logger LOG = LoggerFactory.getLogger(UpdateCounterInCacheAdvice.class); @Pointcut("@annotation(com.google.code.ssm.api.counter.UpdateCounterInCache)") public void updateCounter() { /* pointcut definition */ } @AfterReturning(pointcut = "updateCounter()", returning = "retVal") public void cacheCounterInCache(final JoinPoint jp, final Object retVal) throws Throwable { if (isDisabled()) { getLogger().info("Cache disabled"); return; } // For Update*Cache, an AfterReturning aspect is fine. We will only // apply our caching after the underlying method completes successfully, and we will have // the same access to the method params. String cacheKey = null; UpdateCounterInCache annotation; try { Method methodToCache = getCacheBase().getMethodToCache(jp); annotation = methodToCache.getAnnotation(UpdateCounterInCache.class); AnnotationData data = AnnotationDataBuilder.buildAnnotationData(annotation, UpdateCounterInCache.class, methodToCache); cacheKey = getCacheBase().getCacheKeyBuilder().getCacheKey(data, jp.getArgs(), methodToCache.toString()); Object dataObject = getCacheBase().getUpdateData(data, methodToCache, jp.getArgs(), retVal); if (checkData(dataObject, jp)) { long value = ((Number) dataObject).longValue(); getCacheBase().getCache(data).setCounter(cacheKey, annotation.expiration(), value); } } catch (Exception ex) { warn(ex, "Updating counter [%s] in cache via %s aborted due to an error.", cacheKey, jp.toShortString()); } } @Override protected Logger getLogger() { return LOG; } }
amuzhou/simple-spring-memcached
simple-spring-memcached/src/main/java/com/google/code/ssm/aop/counter/UpdateCounterInCacheAdvice.java
Java
mit
3,554
package gov.va.contentlib.controllers; import gov.va.contentlib.util.CalendarEventScheduler; import java.util.Arrays; import java.util.Calendar; import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.net.Uri; import android.provider.CalendarContract; import android.provider.CalendarContract.Events; import android.util.Log; public class ScheduleToolController2 extends EventEditorController { public ScheduleToolController2(Context ctx) { super(ctx); eventType = "tool"; } }
VAHacker/familycoach-catalyze
android/daelib/src/gov/va/contentlib/controllers/ScheduleToolController2.java
Java
mit
727
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.TShortDoubleHashMap; import gnu.trove.TShortDoubleIterator; import java.io.*; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map.Entry; import java.util.Map; import java.util.Set; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Wrapper class to make a TShortDoubleHashMap conform to the <tt>java.util.Map</tt> API. * This class simply decorates an underlying TShortDoubleHashMap and translates the Object-based * APIs into their Trove primitive analogs. * <p/> * <p/> * Note that wrapping and unwrapping primitive values is extremely inefficient. If * possible, users of this class should override the appropriate methods in this class * and use a table of canonical values. * </p> * <p/> * Created: Mon Sep 23 22:07:40 PDT 2002 * * @author Eric D. Friedman * @author Rob Eden */ public class TShortDoubleHashMapDecorator extends AbstractMap<Short, Double> implements Map<Short, Double>, Externalizable, Cloneable { /** the wrapped primitive map */ protected TShortDoubleHashMap _map; /** * FOR EXTERNALIZATION ONLY!! */ public TShortDoubleHashMapDecorator() {} /** * Creates a wrapper that decorates the specified primitive map. */ public TShortDoubleHashMapDecorator(TShortDoubleHashMap map) { super(); this._map = map; } /** * Returns a reference to the map wrapped by this decorator. */ public TShortDoubleHashMap getMap() { return _map; } /** * Clones the underlying trove collection and returns the clone wrapped in a new * decorator instance. This is a shallow clone except where primitives are * concerned. * * @return a copy of the receiver */ public TShortDoubleHashMapDecorator clone() { try { TShortDoubleHashMapDecorator copy = (TShortDoubleHashMapDecorator) super.clone(); copy._map = (TShortDoubleHashMap)_map.clone(); return copy; } catch (CloneNotSupportedException e) { // assert(false); throw new InternalError(); // we are cloneable, so this does not happen } } /** * Inserts a key/value pair into the map. * * @param key an <code>Object</code> value * @param value an <code>Object</code> value * @return the previous value associated with <tt>key</tt>, * or Double(0) if none was found. */ public Double put(Short key, Double value) { return wrapValue(_map.put(unwrapKey(key), unwrapValue(value))); } /** * Retrieves the value for <tt>key</tt> * * @param key an <code>Object</code> value * @return the value of <tt>key</tt> or null if no such mapping exists. */ public Double get(Short key) { short k = unwrapKey(key); double v = _map.get(k); // 0 may be a false positive since primitive maps // cannot return null, so we have to do an extra // check here. if (v == 0) { return _map.containsKey(k) ? wrapValue(v) : null; } else { return wrapValue(v); } } /** * Empties the map. */ public void clear() { this._map.clear(); } /** * Deletes a key/value pair from the map. * * @param key an <code>Object</code> value * @return the removed value, or Double(0) if it was not found in the map */ public Double remove(Short key) { return wrapValue(_map.remove(unwrapKey(key))); } /** * Returns a Set view on the entries of the map. * * @return a <code>Set</code> value */ public Set<Map.Entry<Short,Double>> entrySet() { return new AbstractSet<Map.Entry<Short,Double>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TShortDoubleHashMapDecorator.this.isEmpty(); } public boolean contains(Object o) { if (o instanceof Map.Entry) { Object k = ((Map.Entry) o).getKey(); Object v = ((Map.Entry) o).getValue(); return TShortDoubleHashMapDecorator.this.containsKey(k) && TShortDoubleHashMapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator<Map.Entry<Short,Double>> iterator() { return new Iterator<Map.Entry<Short,Double>>() { private final TShortDoubleIterator it = _map.iterator(); public Map.Entry<Short,Double> next() { it.advance(); final Short key = wrapKey(it.key()); final Double v = wrapValue(it.value()); return new Map.Entry<Short,Double>() { private Double val = v; public boolean equals(Object o) { return o instanceof Map.Entry && ((Map.Entry) o).getKey().equals(key) && ((Map.Entry) o).getValue().equals(val); } public Short getKey() { return key; } public Double getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Double setValue(Double value) { val = value; return put(key, value); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add(Double o) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends Map.Entry<Short, Double>> c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } public void clear() { TShortDoubleHashMapDecorator.this.clear(); } }; } /** * Checks for the presence of <tt>val</tt> in the values of the map. * * @param val an <code>Object</code> value * @return a <code>boolean</code> value */ public boolean containsValue(Object val) { return _map.containsValue(unwrapValue(val)); } /** * Checks for the present of <tt>key</tt> in the keys of the map. * * @param key an <code>Object</code> value * @return a <code>boolean</code> value */ public boolean containsKey(Object key) { return _map.containsKey(unwrapKey(key)); } /** * Returns the number of entries in the map. * * @return the map's size. */ public int size() { return this._map.size(); } /** * Indicates whether map has any entries. * * @return true if the map is empty */ public boolean isEmpty() { return size() == 0; } /** * Copies the key/value mappings in <tt>map</tt> into this map. * Note that this will be a <b>deep</b> copy, as storage is by * primitive value. * * @param map a <code>Map</code> value */ public void putAll(Map<? extends Short, ? extends Double> map) { Iterator<? extends Entry<? extends Short,? extends Double>> it = map.entrySet().iterator(); for (int i = map.size(); i-- > 0;) { Entry<? extends Short,? extends Double> e = it.next(); this.put(e.getKey(), e.getValue()); } } /** * Wraps a key * * @param k key in the underlying map * @return an Object representation of the key */ protected Short wrapKey(short k) { return Short.valueOf(k); } /** * Unwraps a key * * @param key wrapped key * @return an unwrapped representation of the key */ protected short unwrapKey(Object key) { return ((Short)key).shortValue(); } /** * Wraps a value * * @param k value in the underlying map * @return an Object representation of the value */ protected Double wrapValue(double k) { return Double.valueOf(k); } /** * Unwraps a value * * @param value wrapped value * @return an unwrapped representation of the value */ protected double unwrapValue(Object value) { return ((Double)value).doubleValue(); } // Implements Externalizable public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // MAP _map = (TShortDoubleHashMap) in.readObject(); } // Implements Externalizable public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte(0); // MAP out.writeObject(_map); } } // TShortDoubleHashMapDecorator
jgaltidor/VarJ
analyzed_libs/trove-2.1.0/src/gnu/trove/decorator/TShortDoubleHashMapDecorator.java
Java
mit
11,026
/** * 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. * def */ package com.microsoft.azure.management.network.v2019_09_01.implementation; import com.microsoft.azure.arm.resources.collection.implementation.GroupableResourcesCoreImpl; import com.microsoft.azure.management.network.v2019_09_01.ServiceEndpointPolicies; import com.microsoft.azure.management.network.v2019_09_01.ServiceEndpointPolicy; import rx.Observable; import rx.Completable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import com.microsoft.azure.arm.resources.ResourceUtilsCore; import com.microsoft.azure.arm.utils.RXMapper; import rx.functions.Func1; import com.microsoft.azure.PagedList; import com.microsoft.azure.Page; class ServiceEndpointPoliciesImpl extends GroupableResourcesCoreImpl<ServiceEndpointPolicy, ServiceEndpointPolicyImpl, ServiceEndpointPolicyInner, ServiceEndpointPoliciesInner, NetworkManager> implements ServiceEndpointPolicies { protected ServiceEndpointPoliciesImpl(NetworkManager manager) { super(manager.inner().serviceEndpointPolicies(), manager); } @Override protected Observable<ServiceEndpointPolicyInner> getInnerAsync(String resourceGroupName, String name) { ServiceEndpointPoliciesInner client = this.inner(); return client.getByResourceGroupAsync(resourceGroupName, name); } @Override protected Completable deleteInnerAsync(String resourceGroupName, String name) { ServiceEndpointPoliciesInner client = this.inner(); return client.deleteAsync(resourceGroupName, name).toCompletable(); } @Override public Observable<String> deleteByIdsAsync(Collection<String> ids) { if (ids == null || ids.isEmpty()) { return Observable.empty(); } Collection<Observable<String>> observables = new ArrayList<>(); for (String id : ids) { final String resourceGroupName = ResourceUtilsCore.groupFromResourceId(id); final String name = ResourceUtilsCore.nameFromResourceId(id); Observable<String> o = RXMapper.map(this.inner().deleteAsync(resourceGroupName, name), id); observables.add(o); } return Observable.mergeDelayError(observables); } @Override public Observable<String> deleteByIdsAsync(String...ids) { return this.deleteByIdsAsync(new ArrayList<String>(Arrays.asList(ids))); } @Override public void deleteByIds(Collection<String> ids) { if (ids != null && !ids.isEmpty()) { this.deleteByIdsAsync(ids).toBlocking().last(); } } @Override public void deleteByIds(String...ids) { this.deleteByIds(new ArrayList<String>(Arrays.asList(ids))); } @Override public PagedList<ServiceEndpointPolicy> listByResourceGroup(String resourceGroupName) { ServiceEndpointPoliciesInner client = this.inner(); return this.wrapList(client.listByResourceGroup(resourceGroupName)); } @Override public Observable<ServiceEndpointPolicy> listByResourceGroupAsync(String resourceGroupName) { ServiceEndpointPoliciesInner client = this.inner(); return client.listByResourceGroupAsync(resourceGroupName) .flatMapIterable(new Func1<Page<ServiceEndpointPolicyInner>, Iterable<ServiceEndpointPolicyInner>>() { @Override public Iterable<ServiceEndpointPolicyInner> call(Page<ServiceEndpointPolicyInner> page) { return page.items(); } }) .map(new Func1<ServiceEndpointPolicyInner, ServiceEndpointPolicy>() { @Override public ServiceEndpointPolicy call(ServiceEndpointPolicyInner inner) { return wrapModel(inner); } }); } @Override public PagedList<ServiceEndpointPolicy> list() { ServiceEndpointPoliciesInner client = this.inner(); return this.wrapList(client.list()); } @Override public Observable<ServiceEndpointPolicy> listAsync() { ServiceEndpointPoliciesInner client = this.inner(); return client.listAsync() .flatMapIterable(new Func1<Page<ServiceEndpointPolicyInner>, Iterable<ServiceEndpointPolicyInner>>() { @Override public Iterable<ServiceEndpointPolicyInner> call(Page<ServiceEndpointPolicyInner> page) { return page.items(); } }) .map(new Func1<ServiceEndpointPolicyInner, ServiceEndpointPolicy>() { @Override public ServiceEndpointPolicy call(ServiceEndpointPolicyInner inner) { return wrapModel(inner); } }); } @Override public ServiceEndpointPolicyImpl define(String name) { return wrapModel(name); } @Override protected ServiceEndpointPolicyImpl wrapModel(ServiceEndpointPolicyInner inner) { return new ServiceEndpointPolicyImpl(inner.name(), inner, manager()); } @Override protected ServiceEndpointPolicyImpl wrapModel(String name) { return new ServiceEndpointPolicyImpl(name, new ServiceEndpointPolicyInner(), this.manager()); } }
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_09_01/src/main/java/com/microsoft/azure/management/network/v2019_09_01/implementation/ServiceEndpointPoliciesImpl.java
Java
mit
5,354
/* * MIT License * * Copyright (c) 2016 BotMill.io * * 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.aurasphere.botmill.fb.model.incoming.callback; import java.io.Serializable; /** * Model for a plugin opt-in callback. <br> * <br> * This callback will occur when the <a href= * "https://developers.facebook.com/docs/messenger-platform/plugin-reference/send-to-messenger" * >Send-to-Messenger</a> plugin has been tapped. The optin.ref parameter is set * by the data-ref field on the "Send to Messenger" plugin. This field can be * used by the developer to associate a click event on the plugin with a * callback. You can subscribe to this callback by selecting the * messaging_optins field when <a href= * "https://developers.facebook.com/docs/messenger-platform/webhook-reference#setup" * >setting up</a> your webhook. * * @author Donato Rimenti * @see <a href= * "https://developers.facebook.com/docs/messenger-platform/webhook-reference/optins" * >Facebook's Messenger Platform Plugin Opt-in Callback Documentation</a> * @see <a href= * "https://developers.facebook.com/docs/messenger-platform/plugin-reference/send-to-messenger" * >Facebook's Messenger Platform Send-to-Messenger Documentation</a> * @see <a href= * "https://developers.facebook.com/docs/messenger-platform/webhook-reference#setup" * >Facebook's Messenger Platform Webhook Setup Documentation</a> * */ public class Optin implements Serializable { /** * The serial version UID. */ private static final long serialVersionUID = 1L; /** * Data-ref parameter that was defined with the entry point. */ private String ref; /** * Gets the {@link #ref}. * * @return the {@link #ref}. */ public String getRef() { return ref; } /** * Sets the {@link #ref}. * * @param ref * the {@link #ref} to set. */ public void setRef(String ref) { this.ref = ref; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((ref == null) ? 0 : ref.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Optin other = (Optin) obj; if (ref == null) { if (other.ref != null) return false; } else if (!ref.equals(other.ref)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Optin [ref=" + ref + "]"; } }
Aurasphere/facebot
src/main/java/co/aurasphere/botmill/fb/model/incoming/callback/Optin.java
Java
mit
3,777
package net.authorize.sample.CustomerProfiles; import net.authorize.Environment; import net.authorize.api.contract.v1.*; import java.math.BigDecimal; import net.authorize.api.controller.CreateCustomerShippingAddressController; import net.authorize.api.controller.base.ApiOperationBase; public class CreateCustomerShippingAddress { public static ANetApiResponse run(String apiLoginId, String transactionKey, String customerProfileId) { ApiOperationBase.setEnvironment(Environment.SANDBOX); MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType() ; merchantAuthenticationType.setName(apiLoginId); merchantAuthenticationType.setTransactionKey(transactionKey); ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType); CustomerAddressType customerAddressType = new CustomerAddressType(); customerAddressType.setFirstName("John"); customerAddressType.setLastName("Doe"); customerAddressType.setAddress("123 Main St."); customerAddressType.setCity("Bellevue"); customerAddressType.setState("WA"); customerAddressType.setZip("98004"); customerAddressType.setCountry("USA"); customerAddressType.setPhoneNumber("000-000-0000"); CreateCustomerShippingAddressRequest apiRequest = new CreateCustomerShippingAddressRequest(); apiRequest.setCustomerProfileId(customerProfileId); apiRequest.setAddress(customerAddressType); CreateCustomerShippingAddressController controller = new CreateCustomerShippingAddressController(apiRequest); controller.execute(); CreateCustomerShippingAddressResponse response = controller.getApiResponse(); if (response!=null) { if (response.getMessages().getResultCode() == MessageTypeEnum.OK) { System.out.println(response.getCustomerAddressId()); System.out.println(response.getMessages().getMessage().get(0).getCode()); System.out.println(response.getMessages().getMessage().get(0).getText()); } else { System.out.println("Failed to create customer shipping address: " + response.getMessages().getResultCode()); } } return response; } }
AuthorizeNet/sample-code-java
src/main/java/net/authorize/sample/CustomerProfiles/CreateCustomerShippingAddress.java
Java
mit
2,316
package me.calebjones.spacelaunchnow.data.models.main.spacestation; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.Date; import io.realm.RealmObject; import me.calebjones.spacelaunchnow.data.models.main.spacecraft.SpacecraftStage; public class DockingEvent extends RealmObject { @SerializedName("id") @Expose public Integer id; @SerializedName("url") @Expose public String url; @SerializedName("docking") @Expose public Date docking; @SerializedName("departure") @Expose public Date departure; @SerializedName("flight_vehicle") @Expose public SpacecraftStage flightVehicle; @SerializedName("docking_location") @Expose public DockingLocation dockingLocation; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Date getDocking() { return docking; } public void setDocking(Date docking) { this.docking = docking; } public Date getDeparture() { return departure; } public void setDeparture(Date departure) { this.departure = departure; } public SpacecraftStage getFlightVehicle() { return flightVehicle; } public void setFlightVehicle(SpacecraftStage flightVehicle) { this.flightVehicle = flightVehicle; } public DockingLocation getDockingLocation() { return dockingLocation; } public void setDockingLocation(DockingLocation dockingLocation) { this.dockingLocation = dockingLocation; } }
caman9119/SpaceLaunchNow
data/src/main/java/me/calebjones/spacelaunchnow/data/models/main/spacestation/DockingEvent.java
Java
mit
1,761
package org.jdbcdslog; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Map; import java.util.TreeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CallableStatementLoggingProxy extends PreparedStatementLoggingProxy implements InvocationHandler { static Logger logger = LoggerFactory.getLogger(CallableStatementLoggingProxy.class); Map namedParameters = new TreeMap(); public CallableStatementLoggingProxy(CallableStatement ps, String sql) { super(ps, sql); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = "invoke() "; if(logger.isDebugEnabled()) logger.debug(methodName + "method = " + method); Object r = null; try { boolean toLog = (StatementLogger.logger.isInfoEnabled() || SlowQueryLogger.logger.isInfoEnabled()) && executeMethods.contains(method.getName()); long t1 = 0; if(toLog) t1 = System.currentTimeMillis(); if(logger.isDebugEnabled()) logger.debug(methodName + "before method call."); r = method.invoke(target, args); if(logger.isDebugEnabled()) logger.debug(methodName + "after method call. result = " + r); if(setMethods.contains(method.getName()) && args[0] instanceof Integer) parameters.put(args[0], args[1]); if(setMethods.contains(method.getName()) && args[0] instanceof String) namedParameters.put(args[0], args[1]); if("clearParameters".equals(method.getName())) parameters = new TreeMap(); if(toLog) { long t2 = System.currentTimeMillis(); long time = t2 - t1; StringBuffer s = LogUtils.createLogEntry(method, sql, parametersToString(), namedParameters.toString()); String logEntry = s.append(" ").append(t2 - t1).append(" ms.").toString(); StatementLogger.logger.info(logEntry); if(time >= ConfigurationParameters.slowQueryThreshold) SlowQueryLogger.logger.info(logEntry); } if(r instanceof ResultSet) r = ResultSetLoggingProxy.wrapByResultSetProxy((ResultSet)r); } catch(Throwable t) { LogUtils.handleException(t, StatementLogger.logger, LogUtils.createLogEntry(method, args[0], parametersToString(), namedParameters.toString())); } return r; } }
virtix/mut4j
lib/jdbcdslog/src/main/java/org/jdbcdslog/CallableStatementLoggingProxy.java
Java
mit
2,395
package be.ehb.model.responses; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; /** * @author Guillaume Vandecasteele * @since 2017 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class WorklogResponse implements Serializable { private Long id; private String userId; private ActivityResponse activity; private String day; private Long loggedMinutes; private Boolean confirmed; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public ActivityResponse getActivity() { return activity; } public void setActivity(ActivityResponse activity) { this.activity = activity; } public String getDay() { return day; } public void setDay(String day) { this.day = day; } public Long getLoggedMinutes() { return loggedMinutes; } public void setLoggedMinutes(Long loggedMinutes) { this.loggedMinutes = loggedMinutes; } public Boolean getConfirmed() { return confirmed; } public void setConfirmed(Boolean confirmed) { this.confirmed = confirmed; } @Override public String toString() { return "WorklogResponse{" + "id=" + id + ", userId='" + userId + '\'' + ", activity=" + activity + ", day=" + day + ", loggedMinutes=" + loggedMinutes + ", confirmed=" + confirmed + '}'; } }
Switch2IT/timeskip-api
timeskip-ejb/src/main/java/be/ehb/model/responses/WorklogResponse.java
Java
mit
1,704
import java.io.*; import java.util.*; import java.awt.geom.*; /** * Solution to Star Simulations * * The constraint that the stars are sparse, and that there will not be more * than 100,000 matching pairs, gives us a neat solution. We'll put all * of the stars into kxkxk bins. Then, we only need to check within a bin * and in adjacent bins. The sparseness guarantee makes sure that there won't * be too many in any bin, and so we won't run into Time Limit Exceeded. * * @author vanb */ public class stars_vanb { public Scanner sc; public PrintStream ps; /** * A Star. * * @author vanb */ public class Star { // Position public long x, y, z; /** * Create a Star * * @param x X coordinate * @param y Y coordinate * @param z Z coordinate */ public Star( long x, long y, long z ) { this.x=x; this.y=y; this.z=z; } /** * Distance Squared to another star. * We'll use squared distance to keep things in integers. * * @param s Another star * @return Distance squared form this star to s */ public long d2( Star s ) { long dx = x-s.x; long dy = y-s.y; long dz = z-s.z; return dx*dx + dy*dy + dz*dz; } } // Structure for the bins public HashMap<String,List<Star>> bins = new HashMap<String,List<Star>>(); // These define the 13 'adjacent' bins to a current bin. // Note that if we check the bin at (x+1,y,z), then checking the bin at (x-1,y,z) // is redundant. We would have checked those pairings when we handled bin (x-1,y,z) public int dx[] = { 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 }; public int dy[] = { 0, 1, 0, 1, 0, 1, 1, -1, 0, 1, 1, -1, -1 }; public int dz[] = { 0, 0, 1, 0, 1, 1, 1, 0, -1, -1, -1, 1, -1 }; /** * Figure out what bin to put an integer in. * * @param i Integer * @param k Bin size * @return Ordinal index of a bin */ public static String bin( long i, long k ) { long b = i<0 ? ((i+1)/k-1) : i/k; return ""+b; } /** * Driver. * @throws Exception */ public void doit() throws Exception { sc = new Scanner( System.in ); //new File( "stars.judge" ) ); ps = System.out; //new PrintStream( new FileOutputStream( "stars.solution" ) ); for(;;) { int n = sc.nextInt(); long k = sc.nextLong(); if( n==0 ) break; bins.clear(); for( int i=0; i<n; i++ ) { long x = sc.nextLong(); long y = sc.nextLong(); long z = sc.nextLong(); // Here's the bin to put this star into String key = bin(x,k) + ":" + bin(y,k) + ":" + bin(z,k); List<Star> stars = bins.get( key ); if( stars==null ) { // If it doesn't exist yet, create it. stars = new LinkedList<Star>(); bins.put( key, stars ); } stars.add( new Star( x, y, z ) ); } // Remember, we're comparing distance squared. long kk = k*k; int count = 0; // Go through all of the bins String keys[] = (String[])bins.keySet().toArray( new String[bins.keySet().size()] ); for( String key : keys ) { // Get this bin List<Star> bin = bins.get( key ); // Get all of the stars local to this bin Star local[] = (Star[])bin.toArray( new Star[bin.size()] ); // Compare the local stars to each other for( int i=0; i<local.length; i++ ) for( int j=i+1; j<local.length; j++ ) { if( local[i].d2( local[j] ) < kk ) ++count; } // Get the indices of this bin String tokens[] = key.split( ":" ); int kx = Integer.parseInt( tokens[0] ); int ky = Integer.parseInt( tokens[1] ); int kz = Integer.parseInt( tokens[2] ); // Go through all adjacent bins for( int i=0; i<dx.length; i++ ) { // Get the adjacent bin, if it exists String newkey = "" + (kx+dx[i]) + ":" + (ky+dy[i]) + ":" + (kz+dz[i]); List<Star> newbin = bins.get( newkey ); if( newbin!=null ) { // Compare all of the stars in this bin // to those in the adjacent bin for( Star star1 : bin ) for( Star star2 : newbin ) { if( star1.d2( star2 ) < kk ) ++count; } } } } ps.println( count ); } } /** * @param args */ public static void main( String[] args ) throws Exception { new stars_vanb().doit(); } }
tylerburnham42/ProgrammingTeam
2016/slides/ComputationalGeometry/stars_vanb.java
Java
mit
5,710
package pl.tomaszdziurko.jvm_bloggers.mailing.domain; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "mailing_address") @Data @NoArgsConstructor public class MailingAddress { @Id @GeneratedValue(generator = "MAILING_ADDRESS_SEQ", strategy = GenerationType.SEQUENCE) @SequenceGenerator(name = "MAILING_ADDRESS_SEQ", sequenceName = "MAILING_ADDRESS_SEQ", allocationSize = 1) private Long id; @Column(name = "address", unique = true, nullable = false, length = 250) private String address; public MailingAddress(String address) { this.address = address; } }
alien11689/jvm-bloggers
src/main/java/pl/tomaszdziurko/jvm_bloggers/mailing/domain/MailingAddress.java
Java
mit
883
/** */ package gluemodel.substationStandard.util; import gluemodel.substationStandard.*; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see gluemodel.substationStandard.SubstationStandardPackage * @generated */ public class SubstationStandardAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static SubstationStandardPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SubstationStandardAdapterFactory() { if (modelPackage == null) { modelPackage = SubstationStandardPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SubstationStandardSwitch<Adapter> modelSwitch = new SubstationStandardSwitch<Adapter>() { @Override public Adapter caseSubstandard(Substandard object) { return createSubstandardAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link gluemodel.substationStandard.Substandard <em>Substandard</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see gluemodel.substationStandard.Substandard * @generated */ public Adapter createSubstandardAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //SubstationStandardAdapterFactory
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/substationStandard/util/SubstationStandardAdapterFactory.java
Java
mit
3,279
/** * @author Mike Ma */ package gui.dialogue; public class FireDialog extends Dialog { public FireDialog() { super("Fire Spreading"); } @Override protected void addTexts() { super.addTexts(); addTextField("numBurning", "Num of Burning Cells:", "0", "Num of Burning Cells", "Cannot exceed width*height"); addTextField("numEmpty", "Num of Empty Cells:", "0", "Num of Empty Cells", "Cannot exceed width*height"); addTextField("probCatchFire", "Probability of Catching Fire:", "0.5", "Probability of Catching Fire", "Double between 0 and 1"); }; @Override protected boolean validate() { try { int width = Integer.parseInt(myTexts.get("width").getText().trim()); int height = Integer.parseInt(myTexts.get("height").getText().trim()); int numBurning = Integer.parseInt(myTexts.get("numBurning").getText().trim()); int numEmpty = Integer.parseInt(myTexts.get("numEmpty").getText().trim()); double probCatchFire = Double.parseDouble(myTexts.get("probCatchFire").getText().trim()); return width <= 100 && width > 0 && height <= 100 && height > 0 && numBurning>=0 && numEmpty>=0 && numBurning + numEmpty<= width*height && probCatchFire <= 1 && probCatchFire >= 0; } catch (Exception e) { return false; } } @Override protected String getName() { return "FireModel"; } }
mym987/cps308_cellsociety
src/gui/dialogue/FireDialog.java
Java
mit
1,376
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, 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 ch.qos.logback.access.filter; public interface StatisticalView { long getTotal(); long getLastMinuteCount(); double getMinuteAverage(); long getLastHoursCount(); double getHourlyAverage(); long getLastDaysCount(); double getDailyAverage(); long getLastWeeksCount(); double getWeeklyAverage(); long getLastMonthsCount(); double getMonthlyAverage(); }
JPAT-ROSEMARY/SCUBA
org.jpat.scuba.external.slf4j/logback-1.2.3/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalView.java
Java
mit
928
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.TByteByteHashMap; import gnu.trove.TByteByteIterator; import java.io.*; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map.Entry; import java.util.Map; import java.util.Set; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Wrapper class to make a TByteByteHashMap conform to the <tt>java.util.Map</tt> API. * This class simply decorates an underlying TByteByteHashMap and translates the Object-based * APIs into their Trove primitive analogs. * <p/> * <p/> * Note that wrapping and unwrapping primitive values is extremely inefficient. If * possible, users of this class should override the appropriate methods in this class * and use a table of canonical values. * </p> * <p/> * Created: Mon Sep 23 22:07:40 PDT 2002 * * @author Eric D. Friedman * @author Rob Eden */ public class TByteByteHashMapDecorator extends AbstractMap<Byte, Byte> implements Map<Byte, Byte>, Externalizable, Cloneable { /** the wrapped primitive map */ protected TByteByteHashMap _map; /** * FOR EXTERNALIZATION ONLY!! */ public TByteByteHashMapDecorator() {} /** * Creates a wrapper that decorates the specified primitive map. */ public TByteByteHashMapDecorator(TByteByteHashMap map) { super(); this._map = map; } /** * Returns a reference to the map wrapped by this decorator. */ public TByteByteHashMap getMap() { return _map; } /** * Clones the underlying trove collection and returns the clone wrapped in a new * decorator instance. This is a shallow clone except where primitives are * concerned. * * @return a copy of the receiver */ public TByteByteHashMapDecorator clone() { try { TByteByteHashMapDecorator copy = (TByteByteHashMapDecorator) super.clone(); copy._map = (TByteByteHashMap)_map.clone(); return copy; } catch (CloneNotSupportedException e) { // assert(false); throw new InternalError(); // we are cloneable, so this does not happen } } /** * Inserts a key/value pair into the map. * * @param key an <code>Object</code> value * @param value an <code>Object</code> value * @return the previous value associated with <tt>key</tt>, * or Byte(0) if none was found. */ public Byte put(Byte key, Byte value) { return wrapValue(_map.put(unwrapKey(key), unwrapValue(value))); } /** * Retrieves the value for <tt>key</tt> * * @param key an <code>Object</code> value * @return the value of <tt>key</tt> or null if no such mapping exists. */ public Byte get(Byte key) { byte k = unwrapKey(key); byte v = _map.get(k); // 0 may be a false positive since primitive maps // cannot return null, so we have to do an extra // check here. if (v == 0) { return _map.containsKey(k) ? wrapValue(v) : null; } else { return wrapValue(v); } } /** * Empties the map. */ public void clear() { this._map.clear(); } /** * Deletes a key/value pair from the map. * * @param key an <code>Object</code> value * @return the removed value, or Byte(0) if it was not found in the map */ public Byte remove(Byte key) { return wrapValue(_map.remove(unwrapKey(key))); } /** * Returns a Set view on the entries of the map. * * @return a <code>Set</code> value */ public Set<Map.Entry<Byte,Byte>> entrySet() { return new AbstractSet<Map.Entry<Byte,Byte>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TByteByteHashMapDecorator.this.isEmpty(); } public boolean contains(Object o) { if (o instanceof Map.Entry) { Object k = ((Map.Entry) o).getKey(); Object v = ((Map.Entry) o).getValue(); return TByteByteHashMapDecorator.this.containsKey(k) && TByteByteHashMapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator<Map.Entry<Byte,Byte>> iterator() { return new Iterator<Map.Entry<Byte,Byte>>() { private final TByteByteIterator it = _map.iterator(); public Map.Entry<Byte,Byte> next() { it.advance(); final Byte key = wrapKey(it.key()); final Byte v = wrapValue(it.value()); return new Map.Entry<Byte,Byte>() { private Byte val = v; public boolean equals(Object o) { return o instanceof Map.Entry && ((Map.Entry) o).getKey().equals(key) && ((Map.Entry) o).getValue().equals(val); } public Byte getKey() { return key; } public Byte getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Byte setValue(Byte value) { val = value; return put(key, value); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add(Byte o) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends Map.Entry<Byte, Byte>> c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } public void clear() { TByteByteHashMapDecorator.this.clear(); } }; } /** * Checks for the presence of <tt>val</tt> in the values of the map. * * @param val an <code>Object</code> value * @return a <code>boolean</code> value */ public boolean containsValue(Object val) { return _map.containsValue(unwrapValue(val)); } /** * Checks for the present of <tt>key</tt> in the keys of the map. * * @param key an <code>Object</code> value * @return a <code>boolean</code> value */ public boolean containsKey(Object key) { return _map.containsKey(unwrapKey(key)); } /** * Returns the number of entries in the map. * * @return the map's size. */ public int size() { return this._map.size(); } /** * Indicates whether map has any entries. * * @return true if the map is empty */ public boolean isEmpty() { return size() == 0; } /** * Copies the key/value mappings in <tt>map</tt> into this map. * Note that this will be a <b>deep</b> copy, as storage is by * primitive value. * * @param map a <code>Map</code> value */ public void putAll(Map<? extends Byte, ? extends Byte> map) { Iterator<? extends Entry<? extends Byte,? extends Byte>> it = map.entrySet().iterator(); for (int i = map.size(); i-- > 0;) { Entry<? extends Byte,? extends Byte> e = it.next(); this.put(e.getKey(), e.getValue()); } } /** * Wraps a key * * @param k key in the underlying map * @return an Object representation of the key */ protected Byte wrapKey(byte k) { return Byte.valueOf(k); } /** * Unwraps a key * * @param key wrapped key * @return an unwrapped representation of the key */ protected byte unwrapKey(Object key) { return ((Byte)key).byteValue(); } /** * Wraps a value * * @param k value in the underlying map * @return an Object representation of the value */ protected Byte wrapValue(byte k) { return Byte.valueOf(k); } /** * Unwraps a value * * @param value wrapped value * @return an unwrapped representation of the value */ protected byte unwrapValue(Object value) { return ((Byte)value).byteValue(); } // Implements Externalizable public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // MAP _map = (TByteByteHashMap) in.readObject(); } // Implements Externalizable public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte(0); // MAP out.writeObject(_map); } } // TByteByteHashMapDecorator
jgaltidor/VarJ
analyzed_libs/trove-2.1.0/src/gnu/trove/decorator/TByteByteHashMapDecorator.java
Java
mit
10,877
package me.reddev.osucelebrity.twitch.api; import me.reddev.osucelebrity.twitchapi.TwitchApiUser; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Produces(MediaType.APPLICATION_JSON) public interface Kraken { @Path("/users/{user}") @GET TwitchApiUser getUser(@PathParam("user") String user); @Path("/channels/{channel}") KrakenChannel getChannel(@PathParam("channel") String channel); }
RedbackThomson/OsuCelebrity
osuCelebrity-twitch/src/main/java/me/reddev/osucelebrity/twitch/api/Kraken.java
Java
mit
497
/** * 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.datamigration.v2018_07_15_preview; import com.fasterxml.jackson.annotation.JsonProperty; /** * Specifies resource limits for the migration. */ public class MongoDbThrottlingSettings { /** * The percentage of CPU time that the migrator will try to avoid using, * from 0 to 100. */ @JsonProperty(value = "minFreeCpu") private Integer minFreeCpu; /** * The number of megabytes of RAM that the migrator will try to avoid * using. */ @JsonProperty(value = "minFreeMemoryMb") private Integer minFreeMemoryMb; /** * The maximum number of work items (e.g. collection copies) that will be * processed in parallel. */ @JsonProperty(value = "maxParallelism") private Integer maxParallelism; /** * Get the percentage of CPU time that the migrator will try to avoid using, from 0 to 100. * * @return the minFreeCpu value */ public Integer minFreeCpu() { return this.minFreeCpu; } /** * Set the percentage of CPU time that the migrator will try to avoid using, from 0 to 100. * * @param minFreeCpu the minFreeCpu value to set * @return the MongoDbThrottlingSettings object itself. */ public MongoDbThrottlingSettings withMinFreeCpu(Integer minFreeCpu) { this.minFreeCpu = minFreeCpu; return this; } /** * Get the number of megabytes of RAM that the migrator will try to avoid using. * * @return the minFreeMemoryMb value */ public Integer minFreeMemoryMb() { return this.minFreeMemoryMb; } /** * Set the number of megabytes of RAM that the migrator will try to avoid using. * * @param minFreeMemoryMb the minFreeMemoryMb value to set * @return the MongoDbThrottlingSettings object itself. */ public MongoDbThrottlingSettings withMinFreeMemoryMb(Integer minFreeMemoryMb) { this.minFreeMemoryMb = minFreeMemoryMb; return this; } /** * Get the maximum number of work items (e.g. collection copies) that will be processed in parallel. * * @return the maxParallelism value */ public Integer maxParallelism() { return this.maxParallelism; } /** * Set the maximum number of work items (e.g. collection copies) that will be processed in parallel. * * @param maxParallelism the maxParallelism value to set * @return the MongoDbThrottlingSettings object itself. */ public MongoDbThrottlingSettings withMaxParallelism(Integer maxParallelism) { this.maxParallelism = maxParallelism; return this; } }
selvasingh/azure-sdk-for-java
sdk/datamigration/mgmt-v2018_07_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_07_15_preview/MongoDbThrottlingSettings.java
Java
mit
2,918
/* * The MIT License (MIT) * * Copyright (c) 2014-2017 abel533@gmail.com * * 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 tk.mybatis.mapper.test.user; import org.apache.ibatis.session.SqlSession; import org.junit.Assert; import org.junit.Test; import tk.mybatis.mapper.mapper.MybatisHelper; import tk.mybatis.mapper.mapper.UserLogin2Mapper; import tk.mybatis.mapper.model.UserLogin2; import tk.mybatis.mapper.model.UserLogin2Key; import java.util.Date; import java.util.List; /** * 通过主键删除 * * @author liuzh */ public class TestUserLogin2 { /** * 新增 */ @Test public void testInsert() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserLogin2Mapper mapper = sqlSession.getMapper(UserLogin2Mapper.class); UserLogin2 userLogin = new UserLogin2(); userLogin.setUsername("abel533"); userLogin.setLogindate(new Date()); userLogin.setLoginip("192.168.123.1"); Assert.assertEquals(1, mapper.insert(userLogin)); Assert.assertNotNull(userLogin.getLogid()); Assert.assertTrue(userLogin.getLogid() > 10); //这里测了实体类入参的删除 Assert.assertEquals(1, mapper.deleteByPrimaryKey(userLogin)); } finally { sqlSession.close(); } } /** * 主要测试删除 */ @Test public void testDelete() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserLogin2Mapper mapper = sqlSession.getMapper(UserLogin2Mapper.class); //查询总数 Assert.assertEquals(10, mapper.selectCount(new UserLogin2())); //根据主键查询 UserLogin2Key key = new UserLogin2(); key.setLogid(1); key.setUsername("test1"); UserLogin2 userLogin = mapper.selectByPrimaryKey(key); //根据主键删除 Assert.assertEquals(1, mapper.deleteByPrimaryKey(key)); //查询总数 Assert.assertEquals(9, mapper.selectCount(new UserLogin2())); //插入 Assert.assertEquals(1, mapper.insert(userLogin)); } finally { sqlSession.close(); } } /** * 查询 */ @Test public void testSelect() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserLogin2Mapper mapper = sqlSession.getMapper(UserLogin2Mapper.class); UserLogin2 userLogin = new UserLogin2(); userLogin.setUsername("test1"); List<UserLogin2> userLogins = mapper.select(userLogin); Assert.assertEquals(5, userLogins.size()); } finally { sqlSession.close(); } } /** * 根据主键全更新 */ @Test public void testUpdateByPrimaryKey() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserLogin2Mapper mapper = sqlSession.getMapper(UserLogin2Mapper.class); UserLogin2Key key = new UserLogin2(); key.setLogid(2); key.setUsername("test1"); UserLogin2 userLogin = mapper.selectByPrimaryKey(key); Assert.assertNotNull(userLogin); userLogin.setLoginip("1.1.1.1"); userLogin.setLogindate(null); //不会更新username Assert.assertEquals(1, mapper.updateByPrimaryKey(userLogin)); userLogin = mapper.selectByPrimaryKey(userLogin); Assert.assertNull(userLogin.getLogindate()); Assert.assertEquals("1.1.1.1", userLogin.getLoginip()); } finally { sqlSession.close(); } } /** * 根据主键更新非null */ @Test public void testUpdateByPrimaryKeySelective() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserLogin2Mapper mapper = sqlSession.getMapper(UserLogin2Mapper.class); UserLogin2Key key = new UserLogin2(); key.setLogid(1); key.setUsername("test1"); UserLogin2 userLogin = mapper.selectByPrimaryKey(key); Assert.assertNotNull(userLogin); userLogin.setLogindate(null); userLogin.setLoginip("1.1.1.1"); //不会更新username Assert.assertEquals(1, mapper.updateByPrimaryKeySelective(userLogin)); userLogin = mapper.selectByPrimaryKey(key); Assert.assertNotNull(userLogin.getLogindate()); Assert.assertEquals("1.1.1.1", userLogin.getLoginip()); } finally { sqlSession.close(); } } }
NorthFacing/Mapper
base/src/test/java/tk/mybatis/mapper/test/user/TestUserLogin2.java
Java
mit
5,752
package io.dwadden.gps.avroprocessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.messaging.Processor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.config.EnableIntegration; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; @SuppressWarnings("unused") @EnableIntegration @EnableBinding(Processor.class) @Configuration public class AvroProcessorFlowConfiguration { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); return mapper; } @Bean public IntegrationFlow flow(JsonToAvroTransformer serializeAvroTransformer) { return IntegrationFlows .from(Processor.INPUT) .transform(serializeAvroTransformer) .channel(Processor.OUTPUT) .get(); } }
davidwadden/streams-example
avro-processor/src/main/java/io/dwadden/gps/avroprocessor/AvroProcessorFlowConfiguration.java
Java
mit
1,108
package info.bitrich.xchangestream.ftx; import info.bitrich.xchangestream.core.ProductSubscription; import info.bitrich.xchangestream.core.StreamingExchange; import info.bitrich.xchangestream.core.StreamingMarketDataService; import info.bitrich.xchangestream.service.netty.ConnectionStateModel; import io.reactivex.Completable; import io.reactivex.Observable; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.ftx.FtxExchange; public class FtxStreamingExchange extends FtxExchange implements StreamingExchange { private final String API_URI = "wss://ftx.com/ws/"; private FtxStreamingService ftxStreamingService; private FtxStreamingMarketDataService ftxStreamingMarketDataService; @Override protected void initServices() { super.initServices(); this.ftxStreamingService = new FtxStreamingService(API_URI); this.ftxStreamingMarketDataService = new FtxStreamingMarketDataService(ftxStreamingService); } @Override public Completable connect(ProductSubscription... args) { return ftxStreamingService.connect(); } @Override public Completable disconnect() { return ftxStreamingService.disconnect(); } @Override public boolean isAlive() { return ftxStreamingService.isSocketOpen(); } @Override public Observable<Object> connectionSuccess() { return ftxStreamingService.subscribeConnectionSuccess(); } @Override public Observable<Throwable> reconnectFailure() { return ftxStreamingService.subscribeReconnectFailure(); } @Override public Observable<ConnectionStateModel.State> connectionStateObservable() { return ftxStreamingService.subscribeConnectionState(); } @Override public ExchangeSpecification getDefaultExchangeSpecification() { ExchangeSpecification spec = super.getDefaultExchangeSpecification(); spec.setShouldLoadRemoteMetaData(false); return spec; } @Override public StreamingMarketDataService getStreamingMarketDataService() { return ftxStreamingMarketDataService; } @Override public void useCompressedMessages(boolean compressedMessages) { ftxStreamingService.useCompressedMessages(compressedMessages); } }
douggie/XChange
xchange-stream-ftx/src/main/java/info/bitrich/xchangestream/ftx/FtxStreamingExchange.java
Java
mit
2,176
/* * The MIT License * Copyright © 2014-2019 Ilkka Seppälä * * 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.iluwatar.layers.app; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * * Application test * */ class AppTest { @Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); } }
javaseeds/java-design-patterns
layers/src/test/java/com/iluwatar/layers/app/AppTest.java
Java
mit
1,456
/** * 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_09_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for IpsecEncryption. */ public final class IpsecEncryption extends ExpandableStringEnum<IpsecEncryption> { /** Static value None for IpsecEncryption. */ public static final IpsecEncryption NONE = fromString("None"); /** Static value DES for IpsecEncryption. */ public static final IpsecEncryption DES = fromString("DES"); /** Static value DES3 for IpsecEncryption. */ public static final IpsecEncryption DES3 = fromString("DES3"); /** Static value AES128 for IpsecEncryption. */ public static final IpsecEncryption AES128 = fromString("AES128"); /** Static value AES192 for IpsecEncryption. */ public static final IpsecEncryption AES192 = fromString("AES192"); /** Static value AES256 for IpsecEncryption. */ public static final IpsecEncryption AES256 = fromString("AES256"); /** Static value GCMAES128 for IpsecEncryption. */ public static final IpsecEncryption GCMAES128 = fromString("GCMAES128"); /** Static value GCMAES192 for IpsecEncryption. */ public static final IpsecEncryption GCMAES192 = fromString("GCMAES192"); /** Static value GCMAES256 for IpsecEncryption. */ public static final IpsecEncryption GCMAES256 = fromString("GCMAES256"); /** * Creates or finds a IpsecEncryption from its string representation. * @param name a name to look for * @return the corresponding IpsecEncryption */ @JsonCreator public static IpsecEncryption fromString(String name) { return fromString(name, IpsecEncryption.class); } /** * @return known IpsecEncryption values */ public static Collection<IpsecEncryption> values() { return values(IpsecEncryption.class); } }
navalev/azure-sdk-for-java
sdk/network/mgmt-v2019_09_01/src/main/java/com/microsoft/azure/management/network/v2019_09_01/IpsecEncryption.java
Java
mit
2,164
package com.benromberg.cordonbleu.util; import java.util.Optional; public class OptionalHelper { public static Optional<String> toOptional(String value) { if (value.isEmpty()) { return Optional.empty(); } return Optional.of(value); } public static Optional<Integer> toOptional(int value) { if (value < 0) { return Optional.empty(); } return Optional.of(value); } }
nicodeur/cordonbleu
cordonbleu-util/src/test/java/com/benromberg/cordonbleu/util/OptionalHelper.java
Java
mit
456
package Feb2021Leetcode; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.TreeMap; public class _0599MinimumIndexSumOfTwoLists { public static void main(String[] args) { System.out.println( Arrays.toString(findRestaurant(new String[] { "Shogun", "Tapioca Express", "Burger King", "KFC" }, new String[] { "Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun" }))); System.out.println( Arrays.toString(findRestaurant(new String[] { "Shogun", "Tapioca Express", "Burger King", "KFC" }, new String[] { "KFC", "Shogun", "Burger King" }))); System.out.println( Arrays.toString(findRestaurant(new String[] { "Shogun", "Tapioca Express", "Burger King", "KFC" }, new String[] { "KFC", "Burger King", "Tapioca Express", "Shogun" }))); System.out.println( Arrays.toString(findRestaurant(new String[] { "Shogun", "Tapioca Express", "Burger King", "KFC" }, new String[] { "KNN", "KFC", "Burger King", "Tapioca Express", "Shogun" }))); System.out.println(Arrays.toString(findRestaurant(new String[] { "KFC" }, new String[] { "KFC" }))); } public static String[] findRestaurant(String[] list1, String[] list2) { } }
darshanhs90/Java-InterviewPrep
src/Feb2021Leetcode/_0599MinimumIndexSumOfTwoLists.java
Java
mit
1,259
package edu.pdx.team_b_capstone2015.s_pi_watch; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.DataApi; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataMap; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.PutDataMapRequest; import com.google.android.gms.wearable.Wearable; import com.google.android.gms.wearable.WearableListenerService; import org.json.JSONException; import org.json.JSONObject; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MobileListenerService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks { public static final String PATH_PATIENTS = "/patients"; public static final String PATH_PATIENT = "/patient"; public static final String PATH_QUERY_STATUS = "/query_status"; //REST API keys private static final String NAME = "name"; private static final String BED = "bed" ; private static final String ID = "id"; private static final String AGE = "age"; private static final String TEMP = "temperature"; private static final String HEIGHT = "height"; private static final String BP = "blood_pressure" ; private static final String STATUS = "status"; private static final String CASE_ID = "case_id" ; private static final String H_ID = "hospital_admission_id" ; private static final String CARDIAC = "cardiac"; private static final String ALLERGIES = "allergies"; private static final String WEIGHT = "weight"; private static final String HEART_RATE = "heart-rate"; private static final String P_ID= "patient_id"; private static final String NOTES = "notes"; private static final String DATE = "date"; private static final String[] keys = {NAME,BED,ID,AGE,TEMP,HEIGHT,BP,STATUS,CASE_ID,H_ID,CARDIAC,ALLERGIES,WEIGHT,HEART_RATE,P_ID}; private static final byte[] DATA_AVAILABLE = "Data_available".getBytes() ; private static final String GET_PATIENTS = "Get_Patients"; private GoogleApiClient mGoogleApiClient; private static final String TAG = "SPI-MobileService"; @Override public void onCreate() { super.onCreate(); //Log.d(TAG, "onCreate"); } @Override public void onDestroy() { super.onDestroy(); //Log.d(TAG, "onDestroy"); // if (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()) { // mGoogleApiClient.disconnect(); // } } @Override public void onMessageReceived(MessageEvent messageEvent) { super.onMessageReceived(messageEvent); Log.d(TAG, "message recieved: path = " + messageEvent.getPath() + " Message = " + new String(messageEvent.getData())); if(messageEvent.getPath().contentEquals(PATH_QUERY_STATUS)){ if(new String(messageEvent.getData()).contentEquals(GET_PATIENTS)){ String json = getPatients(); if(json != null){ mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .addConnectionCallbacks(this) .build(); mGoogleApiClient.blockingConnect(); updateData(json); //send a response so the wearable knows the data is available Wearable.MessageApi.sendMessage(mGoogleApiClient, messageEvent.getSourceNodeId(), PATH_QUERY_STATUS, DATA_AVAILABLE); mGoogleApiClient.disconnect(); } } } } //queries the http REST api for patient info //retuns a json string with all patient info private String getPatients() { String server = "http://" + PreferenceManager.getDefaultSharedPreferences(this).getString("pref_ipPref","api.s-pi-demo.com"); String path = "/patients"; String result; InputStream in; // HTTP Get try { Log.d(TAG, "getting patient names from "+ server + path); URL url = new URL(server+path); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); in = urlConnection.getInputStream(); } catch (Exception ex ) { try{ URL url = new URL(server+":8080"+path); Log.d(TAG, "getting patient names from "+ url.toString()); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); in = urlConnection.getInputStream(); }catch(Exception e){ Log.e(TAG, "Error during HTTP connection"); return null; } } result = convertStreamToString(in); //Log.d(TAG, "server returned from patients call " + result); return result; } //converts a stream to a string String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } //updates the shared dataitems //takes a json string private void updateData(String result){ PutDataMapRequest put = PutDataMapRequest.create(PATH_PATIENTS); DataApi.DataItemResult status = Wearable.DataApi.putDataItem(mGoogleApiClient, put.asPutDataRequest()).await(); Log.d(TAG, "Put results: " + status.getStatus().toString()); //send each patient for(PutDataMapRequest p : parseJS(result)){ //Log.d(TAG, "Puting " + p.getUri().getPath()); Wearable.DataApi.putDataItem(mGoogleApiClient, p.asPutDataRequest()).await(); } } @Override public void onConnected(Bundle bundle) { //Log.d(TAG, "onConnected"); } @Override public void onConnectionSuspended(int i) { //Log.d(TAG, "onConnectionSuspended"); } //parses the json and returns a list of PutDataMaps for each patient with the path set to patient# private List<PutDataMapRequest> parseJS(String result) { ArrayList<PutDataMapRequest> putDataMapRequestArray = new ArrayList<>(); //DataMap data; //Parse json //Create JSON object JSONObject allPatients, patient; try { allPatients = new JSONObject(result); for (int i = 0; i < 4; i++){ patient = new JSONObject(allPatients.getString( Integer.toString(i+1) )); //patient ids are 1-4 in json PutDataMapRequest patientPDMR = PutDataMapRequest.create(PATH_PATIENT + Integer.toString(i));//patient paths are /patient0 - /patient3 Log.d(TAG,patientPDMR.getUri().toString()); for(String k : keys){ patientPDMR.getDataMap().putString(k, patient.getString(k)); } putDataMapRequestArray.add(patientPDMR); } } catch (JSONException e) { Log.d(TAG, "JSON ERROR"); e.printStackTrace(); } return putDataMapRequestArray; } }
JoelCranston/S-Pi-Watch
mobile/src/main/java/edu/pdx/team_b_capstone2015/s_pi_watch/MobileListenerService.java
Java
mit
7,444
public class Template { public static void main(String[] args) { Relatorio terremoto = new RelatorioTerremoto(); Relatorio umidade = new RelatorioUmidade(); System.out.println(terremoto.montarRelatorio()); System.out.println(umidade.montarRelatorio()); } }
jucimarjr/uarini
examples/design_patterns/22_Template/Java/Template.java
Java
mit
287
package jenkins.model; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.XmlFile; import hudson.model.PersistentDescriptor; import hudson.util.FormValidation; import hudson.util.XStream2; import jenkins.util.SystemProperties; import jenkins.util.UrlHelper; import org.jenkinsci.Symbol; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.QueryParameter; import edu.umd.cs.findbugs.annotations.Nullable; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.servlet.ServletContext; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; import static hudson.Util.fixNull; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; /** * Stores the location of Jenkins (e-mail address and the HTTP URL.) * * @author Kohsuke Kawaguchi * @since 1.494 */ @Extension(ordinal = JenkinsLocationConfiguration.ORDINAL) @Symbol("location") public class JenkinsLocationConfiguration extends GlobalConfiguration implements PersistentDescriptor { /** * If disabled, the application will no longer check for URL validity in the configuration page. * This will lead to an instance vulnerable to SECURITY-1471. * * @since 2.176.4 / 2.197 */ @Restricted(NoExternalUse.class) @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts") public static /* not final */ boolean DISABLE_URL_VALIDATION = SystemProperties.getBoolean(JenkinsLocationConfiguration.class.getName() + ".disableUrlValidation"); @Restricted(NoExternalUse.class) public static final int ORDINAL = 200; /** * @deprecated replaced by {@link #jenkinsUrl} */ @Deprecated private transient String hudsonUrl; private String adminAddress; private String jenkinsUrl; // just to suppress warnings private transient String charset,useSsl; public static @NonNull JenkinsLocationConfiguration get() { return GlobalConfiguration.all().getInstance(JenkinsLocationConfiguration.class); } /** * Gets local configuration. For explanation when it could die, see {@link #get()} */ @Restricted(NoExternalUse.class) public static @NonNull JenkinsLocationConfiguration getOrDie(){ JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); if (config == null) { throw new IllegalStateException("JenkinsLocationConfiguration instance is missing. Probably the Jenkins instance is not fully loaded at this time."); } return config; } @Override public synchronized void load() { // for backward compatibility, if we don't have our own data yet, then // load from Mailer. XmlFile file = getConfigFile(); if(!file.exists()) { XStream2 xs = new XStream2(); xs.addCompatibilityAlias("hudson.tasks.Mailer$DescriptorImpl",JenkinsLocationConfiguration.class); file = new XmlFile(xs,new File(Jenkins.get().getRootDir(),"hudson.tasks.Mailer.xml")); if (file.exists()) { try { file.unmarshal(this); if (jenkinsUrl==null) jenkinsUrl = hudsonUrl; } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+file, e); } } } else { super.load(); } if (!DISABLE_URL_VALIDATION) { preventRootUrlBeingInvalid(); } updateSecureSessionFlag(); } /** * Gets the service administrator e-mail address. * @return Admin address or &quot;address not configured&quot; stub */ public @NonNull String getAdminAddress() { String v = adminAddress; if(v==null) v = Messages.Mailer_Address_Not_Configured(); return v; } /** * Sets the e-mail address of Jenkins administrator. * @param adminAddress Admin address. Use null to reset the value to default. */ public void setAdminAddress(@CheckForNull String adminAddress) { String address = Util.nullify(adminAddress); if(address != null && address.startsWith("\"") && address.endsWith("\"")) { // some users apparently quote the whole thing. Don't know why // anyone does this, but it's a machine's job to forgive human mistake address = address.substring(1,address.length()-1); } this.adminAddress = address; save(); } public @CheckForNull String getUrl() { return jenkinsUrl; } public void setUrl(@CheckForNull String jenkinsUrl) { String url = Util.nullify(jenkinsUrl); if(url!=null && !url.endsWith("/")) url += '/'; this.jenkinsUrl = url; if (!DISABLE_URL_VALIDATION) { preventRootUrlBeingInvalid(); } save(); updateSecureSessionFlag(); } private void preventRootUrlBeingInvalid() { if (this.jenkinsUrl != null && isInvalidRootUrl(this.jenkinsUrl)) { LOGGER.log(Level.INFO, "Invalid URL received: {0}, considered as null", this.jenkinsUrl); this.jenkinsUrl = null; } } private boolean isInvalidRootUrl(@Nullable String value) { return !UrlHelper.isValidRootUrl(value); } /** * If the Jenkins URL starts from "https", force the secure session flag * * @see <a href="https://www.owasp.org/index.php/SecureFlag">discussion of this topic in OWASP</a> */ private void updateSecureSessionFlag() { try { ServletContext context = Jenkins.get().servletContext; Method m; try { m = context.getClass().getMethod("getSessionCookieConfig"); } catch (NoSuchMethodException x) { // 3.0+ LOGGER.log(Level.FINE, "Failed to set secure cookie flag", x); return; } Object sessionCookieConfig = m.invoke(context); Class scc = Class.forName("javax.servlet.SessionCookieConfig"); Method setSecure = scc.getMethod("setSecure", boolean.class); boolean v = fixNull(jenkinsUrl).startsWith("https"); setSecure.invoke(sessionCookieConfig, v); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof IllegalStateException) { // servlet 3.0 spec seems to prohibit this from getting set at runtime, // though Winstone is happy to accept i. see JENKINS-25019 return; } LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e); } } /** * Checks the URL in {@code global.jelly} */ public FormValidation doCheckUrl(@QueryParameter String value) { if(value.startsWith("http://localhost")) return FormValidation.warning(Messages.Mailer_Localhost_Error()); if (!DISABLE_URL_VALIDATION && isInvalidRootUrl(value)) { return FormValidation.error(Messages.Mailer_NotHttp_Error()); } return FormValidation.ok(); } public FormValidation doCheckAdminAddress(@QueryParameter String value) { try { new InternetAddress(value); return FormValidation.ok(); } catch (AddressException e) { return FormValidation.error(e.getMessage()); } } private static final Logger LOGGER = Logger.getLogger(JenkinsLocationConfiguration.class.getName()); }
oleg-nenashev/jenkins
core/src/main/java/jenkins/model/JenkinsLocationConfiguration.java
Java
mit
8,024
/** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.abstractdocument; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * AbstractDocument test class */ public class AbstractDocumentTest { private static final String KEY = "key"; private static final String VALUE = "value"; private class DocumentImplementation extends AbstractDocument { DocumentImplementation(Map<String, Object> properties) { super(properties); } } private DocumentImplementation document = new DocumentImplementation(new HashMap<>()); @Test public void shouldPutAndGetValue() { document.put(KEY, VALUE); assertEquals(VALUE, document.get(KEY)); } @Test public void shouldRetrieveChildren() { Map<String, Object> child1 = new HashMap<>(); Map<String, Object> child2 = new HashMap<>(); List<Map<String, Object>> children = Arrays.asList(child1, child2); document.put(KEY, children); Stream<DocumentImplementation> childrenStream = document.children(KEY, DocumentImplementation::new); assertNotNull(children); assertEquals(2, childrenStream.count()); } @Test public void shouldRetrieveEmptyStreamForNonExistingChildren() { Stream<DocumentImplementation> children = document.children(KEY, DocumentImplementation::new); assertNotNull(children); assertEquals(0, children.count()); } @Test public void shouldIncludePropsInToString() { Map<String, Object> props = new HashMap<>(); props.put(KEY, VALUE); DocumentImplementation document = new DocumentImplementation(props); assertNotNull(document.toString().contains(KEY)); assertNotNull(document.toString().contains(VALUE)); } }
SerhatSurguvec/java-design-patterns
abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java
Java
mit
3,040
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.client; import java.io.IOException; import org.apache.http.HttpResponse; /** * Handler that encapsulates the process of generating a response object * from a {@link HttpResponse}. * * * @since 4.0 */ public interface ResponseHandler<T> { /** * Processes an {@link HttpResponse} and returns some value * corresponding to that response. * * @param response The response to process * @return A value determined by the response * * @throws ClientProtocolException in case of an http protocol error * @throws IOException in case of a problem or the connection was aborted */ T handleResponse(HttpResponse response) throws ClientProtocolException, IOException; }
byronka/xenos
lib/lib_src/httpcomponents_source/httpcomponents-client-4.4/httpclient/src/main/java/org/apache/http/client/ResponseHandler.java
Java
mit
1,929
// // 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: 2015.07.16 at 03:24:22 PM EEST // package org.ecloudmanager.tmrk.cloudapi.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; /** * <p>Java class for OperatingSystemReferencesType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="OperatingSystemReferencesType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="OperatingSystem" type="{}ReferenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OperatingSystemReferencesType", propOrder = { "operatingSystem" }) public class OperatingSystemReferencesType { @XmlElement(name = "OperatingSystem", nillable = true) protected List<ReferenceType> operatingSystem; /** * Gets the value of the operatingSystem 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 operatingSystem property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOperatingSystem().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getOperatingSystem() { if (operatingSystem == null) { operatingSystem = new ArrayList<ReferenceType>(); } return this.operatingSystem; } }
AltisourceLabs/ecloudmanager
tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/OperatingSystemReferencesType.java
Java
mit
2,371
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package telefonica; /** * * @author alumno */ public class Provincial extends Llamada{ public Provincial(float _duracion, String _nroDestino, String _nroOrigen) { super(_duracion, _nroDestino, _nroOrigen); } }
Fabriciocasal/test
src/clase26HerenciaPoliArray/Telefonica/src/telefonica/Provincial.java
Java
mit
443
package com.alphamedia.rutilahu; import android.os.Environment; public class Config { public static final String BASE_URL = "http://demo.alphamdia.web.id/fieldreport/"; public static final String FILE_UPLOAD_URL = "http://demo.alphamdia.web.id/fieldreport/fu.php"; public static final String IMAGE_DIRECTORY_NAME = "Android File Upload"; public static final String APP_DIR = Environment.getExternalStorageDirectory().getPath() + "/fieldreport"; public static final String FILE_DIR = APP_DIR + "/file/"; public static final String FOTO_DIR = APP_DIR + "/foto/"; public static final String DATA_DIR = APP_DIR + "/file/data.json"; }
AlphaMediaConsultant/rutilahu
app/src/main/java/com/alphamedia/rutilahu/Config.java
Java
mit
659
/* * Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.protocol.json; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.Date; import com.amazonaws.annotation.SdkInternalApi; import com.amazonaws.SdkClientException; import com.amazonaws.util.BinaryUtils; import software.amazon.ion.IonType; import software.amazon.ion.IonWriter; import software.amazon.ion.Timestamp; import software.amazon.ion.system.IonWriterBuilder; @SdkInternalApi abstract class SdkIonGenerator implements StructuredJsonGenerator { private final String contentType; protected final IonWriter writer; private SdkIonGenerator(IonWriter writer, String contentType) { this.writer = writer; this.contentType = contentType; } @Override public StructuredJsonGenerator writeStartArray() { try { writer.stepIn(IonType.LIST); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeNull() { try { writer.writeNull(); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeEndArray() { try { writer.stepOut(); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeStartObject() { try { writer.stepIn(IonType.STRUCT); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeEndObject() { try { writer.stepOut(); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeFieldName(String fieldName) { writer.setFieldName(fieldName); return this; } @Override public StructuredJsonGenerator writeValue(String val) { try { writer.writeString(val); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(boolean bool) { try { writer.writeBool(bool); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(long val) { try { writer.writeInt(val); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(double val) { try { writer.writeFloat(val); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(float val) { try { writer.writeFloat(val); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(short val) { try { writer.writeInt(val); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(int val) { try { writer.writeInt(val); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(ByteBuffer bytes) { try { writer.writeBlob(BinaryUtils.copyAllBytesFrom(bytes)); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(Date date) { try { writer.writeTimestamp(Timestamp.forDateZ(date)); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(BigDecimal value) { try { writer.writeDecimal(value); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public StructuredJsonGenerator writeValue(BigInteger value) { try { writer.writeInt(value); } catch (IOException e) { throw new SdkClientException(e); } return this; } @Override public abstract byte[] getBytes(); @Override public String getContentType() { return contentType; } public static SdkIonGenerator create(IonWriterBuilder builder, String contentType) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IonWriter writer = builder.build(bytes); return new ByteArraySdkIonGenerator(bytes, writer, contentType); } private static class ByteArraySdkIonGenerator extends SdkIonGenerator { private final ByteArrayOutputStream bytes; public ByteArraySdkIonGenerator(ByteArrayOutputStream bytes, IonWriter writer, String contentType) { super(writer, contentType); this.bytes = bytes; } @Override public byte[] getBytes() { try { writer.finish(); } catch (IOException e) { throw new SdkClientException(e); } return bytes.toByteArray(); } } }
loremipsumdolor/CastFast
src/com/amazonaws/protocol/json/SdkIonGenerator.java
Java
mit
6,444
package com.sinewang.kiimate.status.core.api; import one.kii.kiimate.model.core.dai.IntensionDai; import one.kii.kiimate.model.core.dai.ModelSubscriptionDai; import one.kii.kiimate.status.core.api.VisitInstanceApi; import one.kii.kiimate.status.core.dai.InstanceDai; import one.kii.kiimate.status.core.fui.InstanceTransformer; import one.kii.summer.beans.utils.ValueMapping; import one.kii.summer.io.context.ReadContext; import one.kii.summer.io.exception.BadRequest; import one.kii.summer.io.exception.NotFound; import one.kii.summer.io.exception.Panic; import one.kii.summer.io.validator.NotBadResponse; import one.kii.summer.zoom.InsideView; import one.kii.summer.zoom.ZoomInById; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; /** * Created by WangYanJiong on 03/06/2017. */ @Component public class DefaultVisitInstanceApi implements VisitInstanceApi { @Autowired private InstanceDai instanceDai; @Autowired private IntensionDai intensionDai; @Autowired private ModelSubscriptionDai modelSubscriptionDai; @Autowired private InstanceTransformer instanceTransformer; @Override public Instance visit(ReadContext context, ZoomInById form) throws BadRequest, NotFound, Panic { List<InstanceDai.Value> values = instanceDai.loadInstances(form); ZoomInById statusId = ValueMapping.from(ZoomInById.class, context, form); InsideView model = modelSubscriptionDai.loadModelSubById(statusId); Instance instance = ValueMapping.from(Instance.class, model); IntensionDai.ChannelPubSet set = ValueMapping.from(IntensionDai.ChannelPubSet.class, model); set.setSet(model.getSet()); List<IntensionDai.Record> records = intensionDai.loadLast(set); List<Intension> intensions = ValueMapping.from(Intension.class, records); Map<String, Object> map = instanceTransformer.toFatValue(values, model); instance.setIntensions(intensions); instance.setMap(map); return NotBadResponse.of(instance); } }
SINeWang/metamate
status-core-impl/src/main/java/com/sinewang/kiimate/status/core/api/DefaultVisitInstanceApi.java
Java
mit
2,141
package GeeksforGeeksPractice; import java.util.Arrays; /* * Link : http://www.geeksforgeeks.org/find-k-such-that-all-elements-in-kth-row-are-0-and-kth-column-are-1-in-a-boolean-matrix/ */ public class _0085BooleanMatrixFindK { public static void main(String[] args) { int mat[][] = {{0, 0, 1, 1, 0}, {0, 0, 0, 1, 0}, {1, 1, 1, 1, 0}, {0, 0, 0, 0, 0}, {1, 1, 1, 1, 1}}; //printMatrix(mat); System.out.println(findK(mat)); } private static int findK(int[][] mat) { int noOfRows=mat.length; int noOfCols=mat[0].length; int i=0,j=noOfCols-1; int res=-1; while(i<noOfRows && noOfCols>-1) { if(mat[i][j]==0) { while (j >= 0 && (mat[i][j] == 0 || i == j)) j--; if (j == -1) { res = i; break; } else i++; } else{ while (i<noOfRows && (mat[i][j] == 1 || i == j)) i++; if (i == noOfRows) { res = j; break; } else j--; } } if (res == -1) return res; for (int k = 0; k < noOfRows; k++) { if((mat[k][res]==0 && k!=res)) return -1; } for (int k = 0; k < noOfCols; k++) { if((mat[res][k]==1 && k!=res)) return -1; } return res; } private static void printMatrix(int[][] s) { for (int i = 0; i < s.length; i++) { System.out.println(Arrays.toString(s[i])); } } }
darshanhs90/Java-InterviewPrep
src/GeeksforGeeksPractice/_0085BooleanMatrixFindK.java
Java
mit
1,629
/** * Project Name:XPGSdkV4AppBase * File Name:SoftApConfigActivity.java * Package Name:com.gizwits.framework.activity.onboarding * Date:2015-1-27 14:46:20 * Copyright (c) 2014~2015 Xtreme Programming Group, Inc. * 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.gizwits.framework.activity.onboarding; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.InputType; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ToggleButton; import com.gizwits.framework.activity.BaseActivity; import com.gizwits.framework.activity.device.DeviceListActivity; import com.gizwits.powersocket.R; import com.xpg.common.system.IntentUtils; import com.xpg.common.useful.NetworkUtils; import com.xtremeprog.xpgconnect.XPGWifiDevice; import java.util.Timer; import java.util.TimerTask; // TODO: Auto-generated Javadoc /** * * ClassName: Class SoftApConfigActivity. <br/> * 手动配置设备 <br/> * * @author Lien */ public class SoftApConfigActivity extends BaseActivity implements OnClickListener { /** The ll connect ap. */ private LinearLayout llConnectAp; /** The ll insert psw. */ private LinearLayout llInsertPsw; /** The ll config. */ private LinearLayout llConfig; /** The ll config success. */ private LinearLayout llConfigSuccess; /** The ll config failed. */ private LinearLayout llConfigFailed; /** The et input psw. */ private EditText etInputPsw; /** The btn next. */ private Button btnNext; /** The btn ok. */ private Button btnOK; /** The btn retry. */ private Button btnRetry; /** The tvpsw. */ private TextView tvpsw; /** * The iv back. */ private ImageView ivBack; /** The tv ssid. */ private TextView tvSsid; /** The tv tick. */ private TextView tvTick; /** The tb psw flag. */ private ToggleButton tbPswFlag; /** The str ssid. */ private String strSsid; /** The str psw. */ private String strPsw; /** The secondleft. */ int secondleft = 30; /** The timer. */ private Timer timer; /** The UI_STATE now. */ private UI_STATE UiStateNow; /** * The iv step. */ private ImageView ivStep; /** * ClassName: Enum handler_key. <br/> * <br/> * date: 2014-11-26 17:51:10 <br/> * * @author Lien */ private enum handler_key { /** The tick time. */ TICK_TIME, /** The change wifi. */ CHANGE_WIFI, /** The config success. */ CONFIG_SUCCESS, /** The config failed. */ CONFIG_FAILED, } /** * The handler. */ Handler handler = new Handler() { /* * (non-Javadoc) * * @see android.os.Handler#handleMessage(android.os.Message) */ public void handleMessage(Message msg) { super.handleMessage(msg); handler_key key = handler_key.values()[msg.what]; switch (key) { case TICK_TIME: secondleft--; if (secondleft <= 0) { timer.cancel(); sendEmptyMessage(handler_key.CONFIG_FAILED.ordinal()); } else { tvTick.setText(secondleft + ""); } break; case CHANGE_WIFI: showLayout(UI_STATE.PswInput); break; case CONFIG_SUCCESS: showLayout(UI_STATE.ResultSuccess); break; case CONFIG_FAILED: showLayout(UI_STATE.ResultFailed); break; } } }; /** 网络状态广播接受器. */ ConnectChangeBroadcast mChangeBroadcast = new ConnectChangeBroadcast(); /* * (non-Javadoc) * * @see * com.gizwits.framework.activity.BaseActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_softap); initViews(); initEvents(); initDatas(); } /** * Inits the datas. */ private void initDatas() { if (getIntent() != null) { strSsid = getIntent().getStringExtra("ssid"); tvSsid.setText("Wi-Fi名称:" + strSsid); } } /** * Inits the views. */ private void initViews() { llConnectAp = (LinearLayout) findViewById(R.id.llConnectAp); llInsertPsw = (LinearLayout) findViewById(R.id.llInsertPsw); llConfig = (LinearLayout) findViewById(R.id.llConfiging); llConfigSuccess = (LinearLayout) findViewById(R.id.llConfigSuccess); llConfigFailed = (LinearLayout) findViewById(R.id.llConfigFailed); ivBack = (ImageView) findViewById(R.id.ivBack); etInputPsw = (EditText) findViewById(R.id.etInputPsw); btnNext = (Button) findViewById(R.id.btnNext); btnOK = (Button) findViewById(R.id.btnOK); btnRetry = (Button) findViewById(R.id.btnRetry); tvpsw = (TextView) findViewById(R.id.tvpsw); ivStep = (ImageView) findViewById(R.id.ivStep); tvSsid = (TextView) findViewById(R.id.tvSsid); tvTick = (TextView) findViewById(R.id.tvTick); tbPswFlag = (ToggleButton) findViewById(R.id.tbPswFlag); showLayout(UI_STATE.SoftApReady); } /** * Inits the events. */ private void initEvents() { btnRetry.setOnClickListener(this); btnNext.setOnClickListener(this); btnOK.setOnClickListener(this); btnNext.setOnClickListener(this); ivBack.setOnClickListener(this); tbPswFlag.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { etInputPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { etInputPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }); } /* * (non-Javadoc) * * @see com.gizwits.framework.activity.BaseActivity#onResume() */ @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mChangeBroadcast, filter); } /* * (non-Javadoc) * * @see com.gizwits.framework.activity.BaseActivity#onPause() */ public void onPause() { super.onPause(); unregisterReceiver(mChangeBroadcast); } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnNext: startConfig(); break; case R.id.btnOK: IntentUtils.getInstance().startActivity(SoftApConfigActivity.this, DeviceListActivity.class); finish(); break; case R.id.btnRetry: case R.id.ivBack: onBackPressed(); break; } } enum UI_STATE { SoftApReady, PswInput, Setting, ResultFailed, ResultSuccess; } private void showLayout(UI_STATE ui) { UiStateNow = ui; switch (ui) { case SoftApReady: llConnectAp.setVisibility(View.VISIBLE); llInsertPsw.setVisibility(View.GONE); llConfig.setVisibility(View.GONE); llConfigSuccess.setVisibility(View.GONE); llConfigFailed.setVisibility(View.GONE); ivBack.setVisibility(View.VISIBLE); ivStep.setImageResource(R.drawable.step_devicelist); break; case PswInput: llConnectAp.setVisibility(View.GONE); llInsertPsw.setVisibility(View.VISIBLE); llConfig.setVisibility(View.GONE); llConfigSuccess.setVisibility(View.GONE); llConfigFailed.setVisibility(View.GONE); ivBack.setVisibility(View.VISIBLE); ivStep.setImageResource(R.drawable.step_inputpsw_2); break; case Setting: llConnectAp.setVisibility(View.GONE); llInsertPsw.setVisibility(View.GONE); llConfig.setVisibility(View.VISIBLE); llConfigSuccess.setVisibility(View.GONE); llConfigFailed.setVisibility(View.GONE); ivBack.setVisibility(View.GONE); ivStep.setImageResource(R.drawable.step_inputpsw_2); break; case ResultFailed: llConnectAp.setVisibility(View.GONE); llInsertPsw.setVisibility(View.GONE); llConfig.setVisibility(View.GONE); llConfigSuccess.setVisibility(View.GONE); llConfigFailed.setVisibility(View.VISIBLE); ivBack.setVisibility(View.VISIBLE); ivStep.setImageResource(R.drawable.step_inputpsw_2); break; case ResultSuccess: llConnectAp.setVisibility(View.GONE); llInsertPsw.setVisibility(View.GONE); llConfig.setVisibility(View.GONE); llConfigSuccess.setVisibility(View.VISIBLE); llConfigFailed.setVisibility(View.GONE); ivBack.setVisibility(View.VISIBLE); ivStep.setImageResource(R.drawable.step_inputpsw_2); break; } } /** * Start config. */ private void startConfig() { secondleft = 60; tvTick.setText(secondleft + ""); showLayout(UI_STATE.Setting); strPsw = etInputPsw.getText().toString(); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { handler.sendEmptyMessage(handler_key.TICK_TIME.ordinal()); } }, 1000, 1000); String ssidAP = NetworkUtils.getCurentWifiSSID(SoftApConfigActivity.this); mCenter.cSetSoftAp(strSsid, strPsw, ssidAP); } @Override public void onBackPressed() { switch (UiStateNow) { case SoftApReady: startActivity(new Intent(SoftApConfigActivity.this, SearchDeviceActivity.class)); finish(); break; case PswInput: showLayout(UiStateNow.SoftApReady); break; case Setting: break; case ResultFailed: startActivity(new Intent(SoftApConfigActivity.this, SearchDeviceActivity.class)); finish(); case ResultSuccess: finish(); break; } } /** * 广播监听器,监听wifi连上的广播. * * @author Lien */ public class ConnectChangeBroadcast extends BroadcastReceiver { /* * (non-Javadoc) * * @see * android.content.BroadcastReceiver#onReceive(android.content.Context, * android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) { if (NetworkUtils.isWifiConnected(context) && NetworkUtils.getCurentWifiSSID(SoftApConfigActivity.this).contains("XPG-GAgent")) { handler.sendEmptyMessage(handler_key.CHANGE_WIFI.ordinal()); } } } /* * (non-Javadoc) * * @see com.gizwits.framework.activity.BaseActivity#didSetDeviceWifi(int, * com.xtremeprog.xpgconnect.XPGWifiDevice) */ @Override protected void didSetDeviceWifi(int error, XPGWifiDevice device) { if (error == 0) { handler.sendEmptyMessage(handler_key.CONFIG_SUCCESS.ordinal()); } else { handler.sendEmptyMessage(handler_key.CONFIG_FAILED.ordinal()); } } }
gizwits/Gizwits-SmartSocket_Android
src/com/gizwits/framework/activity/onboarding/SoftApConfigActivity.java
Java
mit
11,619
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.contracts.productruntime; import java.util.List; import org.joda.time.DateTime; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.joda.time.DateTime; import com.mozu.api.contracts.productruntime.AttributeDetail; import com.mozu.api.contracts.productruntime.ProductPropertyValue; /** * Details of a property defined for a product. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ProductProperty implements Serializable { // Default Serial Version UID private static final long serialVersionUID = 1L; /** * The fully qualified name of the attribute, which is a user defined attribute identifier. */ protected String attributeFQN; public String getAttributeFQN() { return this.attributeFQN; } public void setAttributeFQN(String attributeFQN) { this.attributeFQN = attributeFQN; } /** * Indicates if the object is hidden or breaks inheritance, primarily used by facets, products, and attribute vocabulary values. For example, if true, the attribute vocabulary value does not appear in the list when defining a value for an attribute. */ protected Boolean isHidden; public Boolean getIsHidden() { return this.isHidden; } public void setIsHidden(Boolean isHidden) { this.isHidden = isHidden; } /** * Indicates if the object has or can have multiple properties or values. If true, the object can have more than one value, selectable by shoppers through the storefront or configurable through the catalogs. */ protected Boolean isMultiValue; public Boolean getIsMultiValue() { return this.isMultiValue; } public void setIsMultiValue(Boolean isMultiValue) { this.isMultiValue = isMultiValue; } /** * Detail data for a product or product options attribute. This acts as a wrapper for the properties to configure or generate from the system in the product Admin. Properties may include namespace, attribute code, attribute sequence, site group ID, input type, and value. */ protected AttributeDetail attributeDetail; public AttributeDetail getAttributeDetail() { return this.attributeDetail; } public void setAttributeDetail(AttributeDetail attributeDetail) { this.attributeDetail = attributeDetail; } /** * List of value data for objects. */ protected List<ProductPropertyValue> values; public List<ProductPropertyValue> getValues() { return this.values; } public void setValues(List<ProductPropertyValue> values) { this.values = values; } }
bhewett/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/contracts/productruntime/ProductProperty.java
Java
mit
2,682
package ch.heigvd.schoolpulse; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.io.BufferedWriter; import java.io.FileWriter; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import org.glassfish.jersey.jackson.JacksonFeature; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.RunListener; /** * * @author Olivier Liechti */ public class TestResultListener extends RunListener { private static final Logger LOG = Logger.getLogger(TestResultListener.class.getName()); private WebTarget target; private Map<String, Integer> numberOfTestsByAuthor = new HashMap<>(); public TestResultListener() { Client client = ClientBuilder.newClient().register(JacksonFeature.class); target = client.target("http://iflux.herokuapp.com/").path("events"); } @Override public void testStarted(Description description) throws Exception { String testClassName = description.getClassName(); TestAuthor testAuthor = description.getAnnotation(TestAuthor.class); if (testAuthor != null) { for (String githubId : testAuthor.githubId()) { LOG.log(Level.INFO, "The test method named {0} has been written by {1}", new Object[]{description.getMethodName(), githubId}); final String testKey = testClassName + "#" + githubId; Integer n = numberOfTestsByAuthor.get(testKey); if (n == null) { numberOfTestsByAuthor.put(testKey, 1); } else { numberOfTestsByAuthor.put(testKey, n+1); } } } } @Override public void testRunStarted(Description description) throws Exception { Event[] payload = new Event[1]; Event e1 = new Event(); e1.setSource("RES"); e1.setTimestamp(new Date()); e1.setType("io.iflux.schoolpulse.test"); e1.set("who", "olivier"); e1.set("pulseId", System.getProperty("schoolPulseUserId")); payload[0] = e1; try { Response response = target.request().post(Entity.json(payload)); } catch (Exception e) { LOG.info("Are you connected to the network? It is better to run the tests when you have an Internet connection."); } } @Override public void testRunFinished(Result result) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); TestStats stats = new TestStats(); stats.setNumberOfTestsByAuthor(numberOfTestsByAuthor); stats.setTestResults(result); BufferedWriter writer = new BufferedWriter(new FileWriter("test-stats.json")); mapper.writeValue(writer, stats); writer.close(); } }
IamFonky/Teaching-HEIGVD-RES-2017-Labo-02
QuizRouletteServer-build/QuizRouletteServer-test/src/test/java/ch/heigvd/schoolpulse/TestResultListener.java
Java
mit
2,982
package org.zalando.riptide.compatibility; import lombok.AllArgsConstructor; import lombok.experimental.Delegate; import org.springframework.http.HttpMethod; import org.springframework.http.HttpOutputMessage; import org.springframework.http.client.AsyncClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.concurrent.ListenableFuture; import javax.annotation.Nonnull; import java.net.URI; @AllArgsConstructor final class HttpOutputMessageAsyncClientHttpRequestAdapter implements AsyncClientHttpRequest { @Delegate private final HttpOutputMessage message; @Nonnull @Override public ListenableFuture<ClientHttpResponse> executeAsync() { throw new UnsupportedOperationException(); } @Nonnull // TODO(Spring 5): @Override public String getMethodValue() { throw new UnsupportedOperationException(); } // TODO(Spring 4): @Override public HttpMethod getMethod() { throw new UnsupportedOperationException(); } @Nonnull @Override public URI getURI() { throw new UnsupportedOperationException(); } }
zalando/riptide
riptide-compatibility/src/main/java/org/zalando/riptide/compatibility/HttpOutputMessageAsyncClientHttpRequestAdapter.java
Java
mit
1,156
package com.conlect.oatos.dto.client; import java.util.ArrayList; import java.util.List; /** * 角色list * * @author yang * */ public class RolesDTO implements BaseDTO { /** * */ private static final long serialVersionUID = 1L; private List<RoleDTO> roleList = new ArrayList<RoleDTO>(); public List<RoleDTO> getRoleList() { return roleList; } public void setRoleList(List<RoleDTO> roleList) { this.roleList = roleList; } }
allanfish/facetime-demo
oatos_project/oatos_dto/src/main/java/com/conlect/oatos/dto/client/RolesDTO.java
Java
mit
454
// Copyright (c) 2001, 2002, 2003 Per M.A. Bothner and Brainfood Inc. // This is free software; for terms and warranty disclaimer see ./COPYING. package gnu.lists; import java.util.NoSuchElementException; /** * A position in a sequence (list). * * Conceptually similar to Java2's ListIterator, but we use the name "Position" * to indicate that it can be used to both indicate a position in a sequence * and to iterate through a sequence. If you use a SeqPosition as a * "position", you would not modify if (though it is possible the offset * of the position in the sequence may change due to other update operations * on the sequence). If you use a SeqPosition as an "iterator", you would * initialize it to some beginnning position, and then modify the current * position of the SeqPosition so it refers to successive elements. * * See the <a href="package-summary.html#iteration">package overview</a> * for more information. */ public class SeqPosition implements /* #ifdef JAVA2 */ java.util.ListIterator, /* #endif */ java.util.Enumeration { /** * The Sequence relative to which ipos and xpos have meaning. * This is normally the same as the Sequence we iterate through. * However, if this is a TreePosition, it may an ancestor instead. */ public AbstractSequence sequence; /** * An integer that (together with xpos) indicates the current position. * The actual value has no meaning, except as interpreted by sequence. */ public int ipos; public SeqPosition() { } public SeqPosition(AbstractSequence seq) { this.sequence = seq; } public SeqPosition(AbstractSequence seq, int offset, boolean isAfter) { this.sequence = seq; ipos = seq.createPos(offset, isAfter); } public SeqPosition(AbstractSequence seq, int ipos) { this.sequence = seq; this.ipos = ipos; } /** Creates a new SeqPosition, from a position pair. * The position pair is copied (using copyPos). */ public static SeqPosition make(AbstractSequence seq, int ipos) { return new SeqPosition(seq, seq.copyPos(ipos)); } public SeqPosition copy () { return new SeqPosition(sequence, sequence.copyPos(getPos())); } public final void gotoStart(AbstractSequence seq) { setPos(seq, seq.startPos()); } public final void gotoEnd(AbstractSequence seq) { setPos(seq, seq.endPos()); } /** Set position before first child (of the element following position). * @return true if there is a child sequence (which might be empty); * false if current position is end of sequence or following element * is atomic (cannot have children). */ public boolean gotoChildrenStart() { int child = sequence.firstChildPos(getPos()); if (child == 0) return false; ipos = child; return true; } /** True if there is an element following the current position. * False if we are at the end. See java.util.Enumeration. */ public final boolean hasMoreElements() { return hasNext(); } /** See java.util.Iterator. */ public boolean hasNext() { return sequence.hasNext(getPos()); } /** Return a code (defined in Sequence) for the type of the next element. */ public int getNextKind() { return sequence.getNextKind(getPos()); } /** Get the "tag name" for the next element, if any. */ public String getNextTypeName() { return sequence.getNextTypeName(getPos()); } /** Get the "tag object" for the next element, if any. */ public Object getNextTypeObject() { return sequence.getNextTypeObject(getPos()); } /** See java.util.Iterator. */ public boolean hasPrevious() { return sequence.hasPrevious(getPos()); } /** See java.util.ListIterator. */ public Object next() { Object result = getNext(); if (result == Sequence.eofValue || ! gotoNext()) throw new NoSuchElementException(); return result; } /** Move one element forwards, if possible. * @return if we succeeded in moving forwards (i.e. not at end of sequence). */ public boolean gotoNext() { int next = sequence.nextPos(ipos); if (next != 0) { ipos = next; return true; } else { ipos = -1; return false; } } /** Move backwards one element. * @return false iff already at beginning. */ public boolean gotoPrevious() { int prev = sequence.previousPos(ipos); if (prev != -1) { ipos = prev; return true; } else { ipos = 0; return false; } } /** See java.util.ListIterator. */ public Object previous() { Object result = getPrevious(); if (result == Sequence.eofValue || ! gotoPrevious()) throw new NoSuchElementException(); return result; } /** See java.util.Enumeration. */ public final Object nextElement() { return next(); } /** * Get element following current position. * Does not move the position, in contrast to next() method. * @return EOF if at end of sequence, otherwise the value following. */ public Object getNext() { return sequence.getPosNext(getPos()); } /** * Get element before the current position. * Does not move the position, in contrast to previous() method. * @return EOF if at beginning of sequence, otherwise the value prior. */ public Object getPrevious() { return sequence.getPosPrevious(getPos()); } /** See java.util.Iterator. */ public int nextIndex() { return sequence.nextIndex(getPos()); } public final int fromEndIndex() { return sequence.fromEndIndex(getPos()); } public int getContainingSequenceSize() { return sequence.getContainingSequenceSize(getPos()); } /** See java.util.Iterator. */ public final int previousIndex() { return sequence.nextIndex(getPos()) - 1; } /** Tests whether the position pair has the "isAfter" property. * I.e. if something is inserted at the position, will * the iterator end up being after the new data? * A toNext() or next() command should set isAfter() to true; * a toPrevious or previous command should set isAfter() to false. */ public boolean isAfter() { return sequence.isAfterPos(getPos()); } public final void set(Object value) { if (isAfter()) setPrevious(value); else setNext(value); } public void setNext (Object value) { sequence.setPosNext(getPos(), value); } public void setPrevious (Object value) { sequence.setPosPrevious(getPos(), value); } public void remove() { sequence.removePos(getPos(), isAfter() ? -1 : 1); } public void add(Object o) { setPos(sequence.addPos(getPos(), o)); } /** Get a position int "cookie" for this SeqPosition. * The result can be passed to AbstractSequence's getPosNext(int), * createRelativePos, and other methods. * By default this is the value of ipos, but for sequences that need emore * state than an ipos for efficient position, we use a PositionManager index. * So this gets over-ridden in ExtPosition. */ public int getPos () { return ipos; } public void setPos (AbstractSequence seq, int ipos) { if (sequence != null) sequence.releasePos(getPos()); this.ipos = ipos; this.sequence = seq; } public void setPos (int ipos) { if (sequence != null) sequence.releasePos(getPos()); this.ipos = ipos; } public void set (AbstractSequence seq, int index, boolean isAfter) { if (sequence != null) sequence.releasePos(ipos); sequence = seq; ipos = seq.createPos(index, isAfter); } public void set (SeqPosition pos) { if (sequence != null) sequence.releasePos(ipos); sequence = pos.sequence; pos.ipos = sequence.copyPos(pos.ipos); } public void release() { if (sequence != null) { sequence.releasePos(getPos()); sequence = null; } } public void finalize() { release(); } public String toString() { if (sequence == null) return toInfo(); Object item = sequence.getPosNext(ipos); return "@"+nextIndex()+": "+(item==null ? "(null)" : item.toString()); } public String toInfo() { StringBuffer sbuf = new StringBuffer(60); sbuf.append('{'); if (sequence == null) sbuf.append("null sequence"); else { sbuf.append(sequence.getClass().getName()); sbuf.append('@'); sbuf.append(System.identityHashCode(sequence)); } sbuf.append(" ipos: "); sbuf.append(ipos); /* if (sequence instanceof TreeList) { sbuf.append(" index: "); sbuf.append(((TreeList) sequence).posToDataIndex(ipos)); } */ sbuf.append('}'); return sbuf.toString(); } } // This is for people using the Emacs editor: // Local Variables: // c-file-style: "gnu" // tab-width: 8 // indent-tabs-mode: t // End:
thequixotic/ai2-kawa
gnu/lists/SeqPosition.java
Java
mit
8,883
package online.zhaopei.myproject.service.ecssent; import java.io.Serializable; import java.util.List; import online.zhaopei.myproject.domain.ecssent.CheckMailGoodHead; public interface CheckMailGoodHeadService extends Serializable { List<CheckMailGoodHead> getCheckMailGoodHeadList(CheckMailGoodHead checkMailGoodHead); }
zhaopei0418/maintain
src/main/java/online/zhaopei/myproject/service/ecssent/CheckMailGoodHeadService.java
Java
mit
327
package openmods.datastore; import java.util.List; import java.util.Map; import openmods.utils.io.*; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class DataStoreBuilder<K, V> { private final DataStoreManager owner; private final DataStoreKey<K, V> key; private final Class<? extends K> keyClass; private final Class<? extends V> valueClass; private IStreamWriter<K> keyWriter; private IStreamWriter<V> valueWriter; private IStreamReader<K> keyReader; private IStreamReader<V> valueReader; private List<IDataVisitor<K, V>> visitors = Lists.newArrayList(); private final Map<K, V> values = Maps.newHashMap(); DataStoreBuilder(DataStoreManager owner, DataStoreKey<K, V> key, Class<? extends K> keyClass, Class<? extends V> valueClass) { this.owner = owner; this.key = key; this.keyClass = keyClass; this.valueClass = valueClass; } public DataStoreKey<K, V> register() { Preconditions.checkNotNull(keyWriter, "Key writer not set"); Preconditions.checkNotNull(valueWriter, "Value writer not set"); Preconditions.checkNotNull(keyReader, "Key reader not set"); Preconditions.checkNotNull(valueReader, "Value reader not set"); final DataStoreWrapper<K, V> wrapper = new DataStoreWrapper<K, V>(values, keyWriter, valueWriter, keyReader, valueReader); for (IDataVisitor<K, V> visitor : visitors) wrapper.addVisitor(visitor); wrapper.activateLocalData(); owner.register(key, wrapper); return key; } public boolean isRegistered(K key) { return values.containsKey(key); } public void addEntry(K key, V value) { Preconditions.checkNotNull(key, "Null key not allowed"); Preconditions.checkNotNull(value, "Null values not allowed"); V prev = values.put(key, value); Preconditions.checkState(prev == null, "Replacing value for key %s: %s -> %s, id: %s", key, prev, value, this.key.id); } private <T> TypeRW<T> getDefaultReaderWriter(Class<? extends T> cls) { @SuppressWarnings("unchecked") TypeRW<T> rw = (TypeRW<T>)TypeRW.UNIVERSAL_SERIALIZERS.get(cls); Preconditions.checkNotNull(rw, "Can't find default reader/writer for class %s, id: %s", cls, key.id); return rw; } public void setDefaultKeyWriter() { this.keyWriter = getDefaultReaderWriter(keyClass); } public void setDefaultValueWriter() { this.valueWriter = getDefaultReaderWriter(valueClass); } public void setDefaultKeyReader() { this.keyReader = getDefaultReaderWriter(keyClass); } public void setDefaultValueReader() { this.valueReader = getDefaultReaderWriter(valueClass); } public void setDefaultKeyReaderWriter() { setDefaultKeyWriter(); setDefaultKeyReader(); } public void setDefaultValueReaderWriter() { setDefaultValueWriter(); setDefaultValueReader(); } public void setDefaultReadersWriters() { setDefaultKeyReaderWriter(); setDefaultValueReaderWriter(); } public void setKeyWriter(IStreamWriter<K> keyWriter) { this.keyWriter = keyWriter; } public void setValueWriter(IStreamWriter<V> valueWriter) { this.valueWriter = valueWriter; } public void setKeyReaderWriter(IStreamSerializer<K> rw) { this.keyReader = rw; this.keyWriter = rw; } public void setKeyReader(IStreamReader<K> keyReader) { this.keyReader = keyReader; } public void setValueReader(IStreamReader<V> valueReader) { this.valueReader = valueReader; } public void setValueReaderWriter(IStreamSerializer<V> rw) { this.valueReader = rw; this.valueWriter = rw; } public void addVisitor(IDataVisitor<K, V> visitor) { visitors.add(visitor); } }
nevercast/OpenModsLib
src/main/java/openmods/datastore/DataStoreBuilder.java
Java
mit
3,609
/* * The MIT License * Copyright © 2014-2019 Ilkka Seppälä * * 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.iluwatar.semaphore; /** * Fruit is a resource stored in a FruitBowl. */ public class Fruit { /** * Enumeration of Fruit Types. */ public enum FruitType { ORANGE, APPLE, LEMON } private FruitType type; public Fruit(FruitType type) { this.type = type; } public FruitType getType() { return type; } /** * toString method. */ public String toString() { switch (type) { case ORANGE: return "Orange"; case APPLE: return "Apple"; case LEMON: return "Lemon"; default: return ""; } } }
zik43/java-design-patterns
semaphore/src/main/java/com/iluwatar/semaphore/Fruit.java
Java
mit
1,752
package cn.wwah.common.event.inner; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import rx.Subscription; import rx.functions.Action1; import rx.schedulers.Schedulers; /** * @Description: 事件订阅者 * @author: jeasinlee * @date: 2016-12-29 19:05 */ public class EventSubscriber extends EventHelper { private final Object target; private final Method method; private final EventThread thread; private Subscription subscription; public EventSubscriber(Object target, Method method, EventThread thread) { if (target == null) { throw new NullPointerException("SubscriberEvent target cannot be null."); } if (method == null) { throw new NullPointerException("SubscriberEvent method cannot be null."); } if (thread == null) { throw new NullPointerException("SubscriberEvent thread cannot be null."); } this.target = target; this.method = method; this.thread = thread; this.method.setAccessible(true); initObservable(this.method.getParameterTypes()[0]); } public final Class getParameter() { return this.method.getParameterTypes()[0]; } private final void initObservable(Class aClass) { subscription = toObservable(aClass).onBackpressureBuffer().subscribeOn(Schedulers.io()).observeOn(EventThread.getScheduler (thread)).subscribe(new Action1<Object>() { @Override public void call(Object event) { try { handleEvent(event); dellSticky(event); } catch (InvocationTargetException e) { throwRuntimeException("Could not dispatch event: " + event.getClass() + " to subscriber " + EventSubscriber.this, e); } } }); } public final Subscription getSubscription() { return subscription; } public final void handleEvent(Object event) throws InvocationTargetException { try { method.invoke(target, event); } catch (IllegalAccessException e) { throw new AssertionError(e); } catch (InvocationTargetException e) { if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw e; } } @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final EventSubscriber other = (EventSubscriber) obj; return method.equals(other.method) && target == other.target; } public final void throwRuntimeException(String msg, InvocationTargetException e) { throwRuntimeException(msg, e.getCause()); } public final void throwRuntimeException(String msg, Throwable e) { Throwable cause = e.getCause(); if (cause != null) { throw new RuntimeException(msg + ": " + cause.getMessage(), cause); } else { throw new RuntimeException(msg + ": " + e.getMessage(), e); } } }
jeasinlee/AndroidBasicLibs
common/src/main/java/cn/wwah/common/event/inner/EventSubscriber.java
Java
mit
3,284
package org.knowm.xchange.gateio.service; import java.io.IOException; import java.math.BigDecimal; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.gateio.dto.GateioBaseResponse; import org.knowm.xchange.gateio.dto.account.GateioDepositAddress; import org.knowm.xchange.gateio.dto.account.GateioFunds; public class GateioAccountServiceRaw extends GateioBaseService { /** * Constructor * * @param exchange */ public GateioAccountServiceRaw(Exchange exchange) { super(exchange); } public GateioFunds getGateioAccountInfo() throws IOException { GateioFunds gateioFunds = bter.getFunds( exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory()); return handleResponse(gateioFunds); } public GateioDepositAddress getGateioDepositAddress(Currency currency) throws IOException { GateioDepositAddress depositAddress = bter.getDepositAddress( exchange.getExchangeSpecification().getApiKey(), signatureCreator, currency.getCurrencyCode()); return depositAddress; } public GateioBaseResponse withdraw( Currency currency, BigDecimal amount, String baseAddress, String addressTag) throws IOException { String withdrawAddress = baseAddress; if (addressTag != null && addressTag.length() > 0) { withdrawAddress = withdrawAddress + "/" + addressTag; } return bter.withdraw( exchange.getExchangeSpecification().getApiKey(), signatureCreator, currency.getCurrencyCode(), amount.toPlainString(), withdrawAddress); } }
npomfret/XChange
xchange-gateio/src/main/java/org/knowm/xchange/gateio/service/GateioAccountServiceRaw.java
Java
mit
1,712
/* Copyright (c) 2014 lib4j * * 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. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.lib4j.util; import java.io.ByteArrayInputStream; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class StreamSearcherTest { @Test public void testStreamSearcher() throws IOException { final StreamSearcher.Byte searcher = new StreamSearcher.Byte(new byte[] {0, 0, 0}, new byte[] {1, 1, 1}); final ByteArrayInputStream test1 = new ByteArrayInputStream(new byte[] {0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0}); final ByteArrayInputStream test2 = new ByteArrayInputStream(new byte[] {1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1}); final byte[] bytes = new byte[15]; Assert.assertEquals(9, searcher.search(test1, bytes, 0)); Assert.assertEquals(9, searcher.search(test2, bytes, 0)); Assert.assertEquals(3, searcher.search(test1, bytes, 0)); Assert.assertEquals(3, searcher.search(test2, bytes, 0)); Assert.assertEquals(3, searcher.search(test1, bytes, 0)); Assert.assertEquals(3, searcher.search(test2, bytes, 0)); } }
safris-src/org
lib4j/util/src/test/java/org/lib4j/util/StreamSearcherTest.java
Java
mit
1,777
package com.microsoft.bingads.api.test.entities.targets.campaign.bids.daytime.read; import com.microsoft.bingads.api.test.entities.targets.campaign.bids.daytime.BulkCampaignDayTimeTargetBidTest; import com.microsoft.bingads.bulk.entities.BulkCampaignDayTimeTargetBid; import com.microsoft.bingads.internal.functionalinterfaces.Function; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class BulkCampaignDayTimeTargetReadFromRowValuesToHourTest extends BulkCampaignDayTimeTargetBidTest { @Parameter(value = 1) public int expectedResult; @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"5", 5} }); } @Test public void testRead() { this.<Integer>testReadProperty("To Hour", this.datum, this.expectedResult, new Function<BulkCampaignDayTimeTargetBid, Integer>() { @Override public Integer apply(BulkCampaignDayTimeTargetBid c) { return c.getDayTimeTargetBid().getToHour(); } }); } }
JeffRisberg/BING01
src/test/java/com/microsoft/bingads/api/test/entities/targets/campaign/bids/daytime/read/BulkCampaignDayTimeTargetReadFromRowValuesToHourTest.java
Java
mit
1,314
package com.conveyal.analysis.components.broker; import com.google.common.io.ByteStreams; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.text.MessageFormat; /** * Test hook (main class) that reads the worker startup script and substitutes in values. */ public class WorkerStartupScriptTestHook { public static void main (String... args) throws Exception { InputStream scriptIs = Broker.class.getClassLoader().getResourceAsStream("worker.sh"); ByteArrayOutputStream scriptBaos = new ByteArrayOutputStream(); ByteStreams.copy(scriptIs, scriptBaos); scriptIs.close(); scriptBaos.close(); String scriptTemplate = scriptBaos.toString(); String workerDownloadUrl = "https://r5-builds.s3.amazonaws.com/v2.3.1.jar"; String logGroup = "test-log-group"; String workerConfigString = "key=val\nkey2=val\n"; String script = MessageFormat.format(scriptTemplate, workerDownloadUrl, logGroup, workerConfigString); System.out.println(script); } }
conveyal/r5
src/main/java/com/conveyal/analysis/components/broker/WorkerStartupScriptTestHook.java
Java
mit
1,064
package net.glowstone.block.blocktype; import lombok.Getter; import net.glowstone.EventFactory; import net.glowstone.GlowWorld; import net.glowstone.block.GlowBlock; import net.glowstone.block.ItemTable; import net.glowstone.block.MaterialValueManager; import net.glowstone.block.PistonMoveBehavior; import net.glowstone.chunk.GlowChunk; import net.glowstone.constants.GameRules; import net.glowstone.entity.GlowPlayer; import net.glowstone.net.message.play.game.BlockActionMessage; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.SoundCategory; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.material.PistonBaseMaterial; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class BlockPiston extends BlockDirectional { private static final int PUSH_LIMIT = 12; private static final BlockFace[] ADJACENT_FACES = new BlockFace[] { BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN }; /** * The piston is either non-sticky (default), or has a sticky behavior. * * @return true if the piston has a sticky base */ @Getter private final boolean sticky; /** * Creates the basic (non-sticky) piston block type. */ public BlockPiston() { this(false); } /** * Creates a piston block type. * * @param sticky true for the sticky-piston type; false for the basic piston type */ public BlockPiston(boolean sticky) { super(false); this.sticky = sticky; if (sticky) { setDrops(new ItemStack(Material.STICKY_PISTON)); } else { setDrops(new ItemStack(Material.PISTON)); } } @Override public void blockDestroy(GlowPlayer player, GlowBlock block, BlockFace face) { if (block.getType() == Material.PISTON) { // break piston extension if extended if (isPistonExtended(block)) { block.getRelative(((PistonBaseMaterial) block.getState().getData()).getFacing()) .setType(Material.AIR); } } // TODO: handle breaking of piston extension } private void performMovement(BlockFace direction, List<Block> blocksToMove, List<Block> blocksToBreak) { blocksToMove.sort((a, b) -> { switch (direction) { case NORTH: return a.getZ() - b.getZ(); case SOUTH: return b.getZ() - a.getZ(); case EAST: return b.getX() - a.getX(); case WEST: return a.getX() - b.getX(); case UP: return b.getY() - a.getY(); case DOWN: return a.getY() - b.getY(); default: return 0; } }); for (Block block : blocksToBreak) { breakBlock((GlowBlock) block); } for (Block block : blocksToMove) { setType(block.getRelative(direction), block.getType(), block.getData()); // Need to do this to remove pulled blocks setType(block, Material.AIR, 0); } } @Override public void onRedstoneUpdate(GlowBlock me) { PistonBaseMaterial piston = (PistonBaseMaterial) me.getState().getData(); BlockFace pistonBlockFace = piston.getFacing(); int rawFace = BlockDirectional.getRawFace(pistonBlockFace); BlockActionMessage message = new BlockActionMessage(me.getX(), me.getY(), me.getZ(), me.isBlockIndirectlyPowered() ? 0 : 1, rawFace, me.getType().getId()); GlowChunk chunk = me.getChunk(); GlowChunk.Key chunkKey = GlowChunk.Key.of(chunk.getX(), chunk.getZ()); GlowWorld world = me.getWorld(); if (me.isBlockIndirectlyPowered() && !isPistonExtended(me)) { List<Block> blocksToMove = new ArrayList<>(); List<Block> blocksToBreak = new ArrayList<>(); boolean allowMovement = addBlock(me, pistonBlockFace, me.getRelative(pistonBlockFace), pistonBlockFace.getOppositeFace(), blocksToMove, blocksToBreak); if (!allowMovement) { return; } BlockPistonExtendEvent event = EventFactory.getInstance().callEvent( new BlockPistonExtendEvent(me, blocksToMove, pistonBlockFace) ); if (event.isCancelled()) { return; } world.getRawPlayers().stream().filter(player -> player.canSeeChunk(chunkKey)) .forEach(player -> player.getSession().send(message)); world.playSound(me.getLocation(), Sound.BLOCK_PISTON_EXTEND, SoundCategory.BLOCKS, 0.5f, 0.75f); // extended state for piston base me.setData((byte) (me.getData() | 0x08)); performMovement(pistonBlockFace, blocksToMove, blocksToBreak); // set piston head block when extended setType(me.getRelative(pistonBlockFace), Material.MOVING_PISTON, sticky ? me.getData() | 0x08 : rawFace); return; } if (!isPistonExtended(me)) { return; } List<Block> blocksToMove = new ArrayList<>(); List<Block> blocksToBreak = new ArrayList<>(); if (sticky) { addBlock(me, pistonBlockFace.getOppositeFace(), me.getRelative(pistonBlockFace, 2), pistonBlockFace.getOppositeFace(), blocksToMove, blocksToBreak); } BlockPistonRetractEvent event = EventFactory.getInstance().callEvent( new BlockPistonRetractEvent(me, blocksToMove, pistonBlockFace) ); if (event.isCancelled()) { return; } world.getRawPlayers().stream().filter(player -> player.canSeeChunk(chunkKey)) .forEach(player -> player.getSession().send(message)); world.playSound(me.getLocation(), Sound.BLOCK_PISTON_CONTRACT, SoundCategory.BLOCKS, 0.5f, 0.75f); // normal state for piston setType(me, me.getType(), me.getData() & ~0x08); if (sticky && blocksToMove.size() > 0) { performMovement(pistonBlockFace.getOppositeFace(), blocksToMove, blocksToBreak); } else { // remove piston head me.getRelative(pistonBlockFace).setTypeIdAndData(0, (byte) 0, true); } } private boolean addBlock(GlowBlock piston, BlockFace movementDirection, GlowBlock block, BlockFace ignoredFace, List<Block> blocksToMove, List<Block> blocksToBreak) { boolean isPushing = (movementDirection == ignoredFace.getOppositeFace()); MaterialValueManager.ValueCollection materialValues = block.getMaterialValues(); PistonMoveBehavior moveBehavior = isPushing ? materialValues.getPistonPushBehavior() : materialValues.getPistonPullBehavior(); if (block.isEmpty()) { return true; } if (blocksToMove.size() >= PUSH_LIMIT) { return false; } if (isPushing) { switch (moveBehavior) { case MOVE_STICKY: case MOVE: blocksToMove.add(block); break; case BREAK: blocksToBreak.add(block); return true; case DONT_MOVE: return false; default: return true; } } else { switch (moveBehavior) { case MOVE_STICKY: case MOVE: blocksToMove.add(block); break; case BREAK: case DONT_MOVE: default: return true; } } if (moveBehavior == PistonMoveBehavior.MOVE_STICKY) { boolean allowMovement = true; for (BlockFace face : ADJACENT_FACES) { GlowBlock nextBlock = block.getRelative(face); if (nextBlock.getLocation().equals(piston.getLocation())) { continue; } if (face == ignoredFace || blocksToMove.contains(nextBlock)) { continue; } allowMovement = addBlock(piston, movementDirection, block.getRelative(face), face.getOppositeFace(), blocksToMove, blocksToBreak); if (!allowMovement) { break; } } return allowMovement; } else if (movementDirection != ignoredFace) { GlowBlock nextBlock = block.getRelative(movementDirection); if (nextBlock.getLocation().equals(piston.getLocation())) { return false; } return addBlock(piston, movementDirection, nextBlock, movementDirection.getOppositeFace(), blocksToMove, blocksToBreak); } else { return true; } } private void breakBlock(GlowBlock block) { if (block.isEmpty()) { return; } GlowWorld world = block.getWorld(); Collection<ItemStack> drops = new ArrayList<>(); BlockType blockType = ItemTable.instance().getBlock(block.getType()); if (world.getGameRuleMap().getBoolean(GameRules.DO_TILE_DROPS)) { drops.addAll(blockType.getMinedDrops(block)); } else { // Container contents is dropped anyways if (blockType instanceof BlockContainer) { drops.addAll(((BlockContainer) blockType).getContentDrops(block)); } } Location location = block.getLocation(); setType(block, Material.AIR, 0); if (drops.size() > 0 && !(blockType instanceof BlockLiquid)) { drops.stream().forEach((stack) -> block.getWorld().dropItemNaturally(location, stack)); } } private boolean isPistonExtended(Block block) { // TODO: check direction of piston_extension to make sure that the extension is attached to // piston Block pistonHead = block .getRelative(((PistonBaseMaterial) block.getState().getData()).getFacing()); return pistonHead.getType() == Material.MOVING_PISTON; } // update block server side without sending block change packets private void setType(Block block, Material type, int data) { World world = block.getWorld(); int x = block.getX(); int y = block.getY(); int z = block.getZ(); GlowChunk chunk = (GlowChunk) world.getChunkAt(block); chunk.setType(x & 0xf, z & 0xf, y, type); chunk.setMetaData(x & 0xf, z & 0xf, y, data); } }
GlowstonePlusPlus/GlowstonePlusPlus
src/main/java/net/glowstone/block/blocktype/BlockPiston.java
Java
mit
11,275
// TYPE_LINKING /* TypeLinking: * Check that no prefixes (consisting of whole identifiers) of fully qualified * types themselves resolve to types. */ public class Main { public Main() {} public static int test() { foo.String.bar.foo s = new foo.String.bar.foo(); return 123; } }
gregwym/joos-compiler-java
testcases/a2/J1_3_InfixResolvesToType/Main.java
Java
mit
300
package ultimatets.minecraft; import ultimatets.UltimateTs; import ultimatets.teamspeak.BotManager; import java.util.Collections; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerQuitEvent; import com.github.theholywaffle.teamspeak3.api.ClientProperty; public class TypeYesOrNo implements Listener { @EventHandler public void onChat(AsyncPlayerChatEvent e){ Player p = e.getPlayer(); if(PlayerManager.confirmationReady.contains(p)){ String message = e.getMessage(); if(message == null) return; String rep = UltimateTs.main().getConfig().getString("config.yesReponse"); if(rep == null) rep = "YES"; if(message.equalsIgnoreCase(rep.toString())){ BotManager.getBot().editClient(PlayerManager.convertDatabaseIdToClientId(PlayerManager.getLinkedWithDbId(p)), Collections.singletonMap(ClientProperty.CLIENT_DESCRIPTION, "")); p.sendMessage(UltimateTs.messages.getString("messages.unlinked.confirmation.yes").replace('&', '§')); PlayerManager.unlink(p); }else{ p.sendMessage(UltimateTs.messages.getString("messages.unlinked.confirmation.no").replace('&', '§')); } PlayerManager.confirmationReady.remove(p); e.setCancelled(true); } } @EventHandler public void onQuit(PlayerQuitEvent e){ Player p = e.getPlayer(); if(PlayerManager.confirmationReady.contains(p)){ PlayerManager.confirmationReady.remove(p); } } }
DiscowZombie/UltimateTs
ultimatets/minecraft/TypeYesOrNo.java
Java
mit
1,576
package module3; //Java utilities libraries import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.data.PointFeature; import de.fhpotsdam.unfolding.marker.Marker; import de.fhpotsdam.unfolding.marker.SimplePointMarker; import de.fhpotsdam.unfolding.providers.Google; import de.fhpotsdam.unfolding.providers.MBTilesMapProvider; import de.fhpotsdam.unfolding.utils.MapUtils; import parsing.ParseFeed; import processing.core.PApplet; import java.util.ArrayList; import java.util.List; /** * EarthquakeCityMap An application with an interactive map displaying earthquake data. Author: UC San Diego Intermediate Software * Development MOOC team * * @author Dan Karlsson: October 17, 2015 */ public class EarthquakeCityMap extends PApplet { /** * The Threshold moderate. The constant THRESHOLD_MODERATE. Less than this threshold is a light earthquake */ public static final float THRESHOLD_MODERATE = 5; /** * The Threshold light. The constant THRESHOLD_LIGHT. Less than this threshold is a minor earthquake */ public static final float THRESHOLD_LIGHT = 4; // You can ignore this. It's to keep eclipse from generating a warning. private static final long serialVersionUID = 1L; // IF YOU ARE WORKING OFFLINE, change the value of this variable to true private static final boolean offline = false; /** * This is where to find the local tiles, for working without an Internet connection */ public static String mbTilesString = "blankLight-1-3.mbtiles"; private final boolean DEBUG = true; // The map private UnfoldingMap map; //feed with magnitude 2.5+ Earthquakes private String earthquakesURL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.atom"; private PointFeature feature; private float magnitude; private int yellow = color(255, 255, 0); private int red = color(200, 0, 0); private int blue = color(0, 102, 255); private int white = color(255, 255, 255); private int grey = color(50, 50, 50); private int black = color(0, 0, 0); public void setup() { size(950, 600, OPENGL); if (offline) { map = new UnfoldingMap(this, 200, 50, 700, 500, new MBTilesMapProvider(mbTilesString)); earthquakesURL = "2.5_week.atom"; // Same feed, saved Aug 7, 2015, for working offline } else { map = new UnfoldingMap(this, 200, 50, 700, 500, new Google.GoogleMapProvider()); // IF YOU WANT TO TEST WITH A LOCAL FILE, uncomment the next line //earthquakesURL = "2.5_week.atom"; } map.zoomToLevel(2); MapUtils.createDefaultEventDispatcher(this, map); // The List you will populate with new SimplePointMarkers List<Marker> markers = new ArrayList<Marker>(); //Use provided parser to collect properties for each earthquake //PointFeatures have a getLocation method List<PointFeature> earthquakes = ParseFeed.parseEarthquake(this, earthquakesURL); // These print statements show you (1) all of the relevant properties // in the features, and (2) how to get one property and use it if (DEBUG) { if (earthquakes.size() > 0) { PointFeature f = earthquakes.get(0); System.out.println(f.getProperties()); Object magObj = f.getProperty("magnitude"); float mag = Float.parseFloat(magObj.toString()); println("Magnitude : " + mag); // PointFeatures also have a getLocation method // System.out.println(createMarker(f)); } } // Here is an example of how to use Processing's color method to generate // an int that represents the color yellow. //TODO: Add code here as appropriate for (PointFeature quake : earthquakes) { markers.add(createMarker(quake)); } map.addMarkers(markers); } /** * createMarker * * @param feature * A suggested helper method that takes in an earthquake feature * * @return returns a SimplePointMarker for that earthquake */ private SimplePointMarker createMarker(PointFeature feature) { SimplePointMarker marker = new SimplePointMarker(feature.getLocation()); marker.setRadius(10); Object magObject = feature.getProperty("magnitude"); this.magnitude = Float.parseFloat(magObject.toString()); if (DEBUG) { println("-----------------------------------------------"); } if (this.magnitude > THRESHOLD_MODERATE) { if (DEBUG) { println("Color : red"); } marker.setColor(this.red); marker.setRadius(20); } else if (this.magnitude > THRESHOLD_LIGHT) { marker.setColor(this.yellow); marker.setRadius(15); if (DEBUG) { println("Color : yellow"); } } else { marker.setColor(this.blue); if (DEBUG) { println("Color : blue"); } } if (DEBUG) { println("Marker Magnitude : " + this.magnitude); println("Marker Lat: " + marker.getLocation().getLat()); println("Marker Lon: " + marker.getLocation().getLon()); println("-----------------------------------------------"); } // PointFeatures also have a getLocation method return marker; } public void draw() { background(10); map.draw(); addKey(); } // helper method to draw key in GUI // TODO: Implement this method to draw the key private void addKey() { int rectHeight = 300; int rectWidth = 175; int rectX = 20; int rectY = 50; // Remember you can use Processing's graphics methods here fill(grey); rect(rectX, rectY, rectWidth, rectHeight); fill(white); rect(rectX, rectY, rectWidth, rectHeight); fill(red); ellipse(50, 80, 30, 30); fill(black); text("Moderate Magnitude > 4.9", 80, 105); fill(yellow); ellipse(50, 170, 20, 20); fill(black); text("Light Magnitude 4.0 - 4.9", 80, 175); fill(blue); ellipse(50, 230, 10, 10); fill(black); text("Magnitude < 4.0", 80, 235); fill(white); } }
dank-developer/coursera-java
src/module3/EarthquakeCityMap.java
Java
mit
6,634
package com.microsoft.xrm.sdk.Messages; import com.microsoft.xrm.sdk.OrganizationResponse; import com.microsoft.xrm.sdk.Utils; import org.xmlpull.v1.XmlPullParser; import java.util.UUID; public final class AddMemberListResponse extends OrganizationResponse { private UUID id; public UUID getId() { return id; } @Override public void storeResult(XmlPullParser parser) { try { String name = parser.getName(); parser.nextTag(); do { if (parser.getEventType() != XmlPullParser.START_TAG) { parser.next(); continue; } if (parser.getName().equals("KeyValuePairOfstringanyType")) { parser.nextTag(); do { if (parser.getEventType() != XmlPullParser.START_TAG) { parser.next(); continue; } if (parser.getName().equals("key")) { parser.next(); if (parser.getText().equals("id")) { parser.nextTag(); parser.nextTag(); this.id = (UUID) Utils.objectFromXml(parser); } } parser.next(); } while (!parser.getName().equals("KeyValuePairOfstringanyType")); } else { Utils.skip(parser); } parser.next(); } while (parser.getEventType() != XmlPullParser.END_TAG || !parser.getName().equals(name)); } catch(Exception ex) { ex.printStackTrace(); } } }
DynamicsCRM/crm-mobilesdk-library-for-android
crmsdk2015/src/main/java/com/microsoft/xrm/sdk/Messages/AddMemberListResponse.java
Java
mit
1,855
/** * 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.sql.v2014_04_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.sql.v2014_04_01.ServerTableAuditingPolicies; import rx.Observable; import rx.functions.Func1; import com.microsoft.azure.management.sql.v2014_04_01.ServerTableAuditingPolicyListResult; import com.microsoft.azure.management.sql.v2014_04_01.ServerTableAuditingPolicy; class ServerTableAuditingPoliciesImpl extends WrapperImpl<ServerTableAuditingPoliciesInner> implements ServerTableAuditingPolicies { private final SqlManager manager; ServerTableAuditingPoliciesImpl(SqlManager manager) { super(manager.inner().serverTableAuditingPolicies()); this.manager = manager; } public SqlManager manager() { return this.manager; } @Override public ServerTableAuditingPolicyImpl define(String name) { return wrapModel(name); } private ServerTableAuditingPolicyImpl wrapModel(ServerTableAuditingPolicyInner inner) { return new ServerTableAuditingPolicyImpl(inner, manager()); } private ServerTableAuditingPolicyImpl wrapModel(String name) { return new ServerTableAuditingPolicyImpl(name, this.manager()); } @Override public Observable<ServerTableAuditingPolicyListResult> listByServerAsync(String resourceGroupName, String serverName) { ServerTableAuditingPoliciesInner client = this.inner(); return client.listByServerAsync(resourceGroupName, serverName) .map(new Func1<ServerTableAuditingPolicyListResultInner, ServerTableAuditingPolicyListResult>() { @Override public ServerTableAuditingPolicyListResult call(ServerTableAuditingPolicyListResultInner inner) { return new ServerTableAuditingPolicyListResultImpl(inner, manager()); } }); } @Override public Observable<ServerTableAuditingPolicy> getAsync(String resourceGroupName, String serverName) { ServerTableAuditingPoliciesInner client = this.inner(); return client.getAsync(resourceGroupName, serverName) .map(new Func1<ServerTableAuditingPolicyInner, ServerTableAuditingPolicy>() { @Override public ServerTableAuditingPolicy call(ServerTableAuditingPolicyInner inner) { return wrapModel(inner); } }); } }
navalev/azure-sdk-for-java
sdk/sql/mgmt-v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ServerTableAuditingPoliciesImpl.java
Java
mit
2,656
package ru.atott.combiq.web.bean; public class CountQuestionSearchBean { private long count; public CountQuestionSearchBean() { } public CountQuestionSearchBean(long count) { this.count = count; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } }
atott/combiq
web/src/main/java/ru/atott/combiq/web/bean/CountQuestionSearchBean.java
Java
mit
359
package net.glowstone; import net.glowstone.GlowChunk.ChunkSection; import net.glowstone.GlowChunk.Key; import net.glowstone.constants.GlowBiome; import net.glowstone.generator.GlowChunkData; import net.glowstone.generator.GlowChunkGenerator; import net.glowstone.generator.biomegrid.MapLayer; import net.glowstone.io.ChunkIoService; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkPopulateEvent; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; import org.bukkit.material.MaterialData; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import java.util.stream.Collectors; /** * A class which manages the {@link GlowChunk}s currently loaded in memory. * * @author Graham Edgecombe */ public final class ChunkManager { /** * The world this ChunkManager is managing. */ private final GlowWorld world; /** * The chunk I/O service used to read chunks from the disk and write them to * the disk. */ private final ChunkIoService service; /** * The chunk generator used to generate new chunks. */ private final ChunkGenerator generator; /** * The biome maps used to fill chunks biome grid and terrain generation. */ private final MapLayer[] biomeGrid; /** * A map of chunks currently loaded in memory. */ private final ConcurrentMap<Key, GlowChunk> chunks = new ConcurrentHashMap<>(); /** * A map of chunks which are being kept loaded by players or other factors. */ private final ConcurrentMap<Key, Set<ChunkLock>> locks = new ConcurrentHashMap<>(); /** * Creates a new chunk manager with the specified I/O service and world * generator. * * @param world The chunk manager's world. * @param service The I/O service. * @param generator The world generator. */ public ChunkManager(GlowWorld world, ChunkIoService service, ChunkGenerator generator) { this.world = world; this.service = service; this.generator = generator; biomeGrid = MapLayer.initialize(world.getSeed(), world.getEnvironment(), world.getWorldType()); } /** * Get the chunk generator. * * @return The chunk generator. */ public ChunkGenerator getGenerator() { return generator; } /** * Gets a chunk object representing the specified coordinates, which might * not yet be loaded. * * @param x The X coordinate. * @param z The Z coordinate. * @return The chunk. */ public GlowChunk getChunk(int x, int z) { Key key = new Key(x, z); if (chunks.containsKey(key)) { return chunks.get(key); } else { // only create chunk if it's not in the map already GlowChunk chunk = new GlowChunk(world, x, z); GlowChunk prev = chunks.putIfAbsent(key, chunk); // if it was created in the intervening time, the earlier one wins return prev == null ? chunk : prev; } } /** * Checks if the Chunk at the specified coordinates is loaded. * * @param x The X coordinate. * @param z The Z coordinate. * @return true if the chunk is loaded, otherwise false. */ public boolean isChunkLoaded(int x, int z) { Key key = new Key(x, z); return chunks.containsKey(key) && chunks.get(key).isLoaded(); } /** * Check whether a chunk has locks on it preventing it from being unloaded. * * @param x The X coordinate. * @param z The Z coordinate. * @return Whether the chunk is in use. */ public boolean isChunkInUse(int x, int z) { Key key = new Key(x, z); Set<ChunkLock> lockSet = locks.get(key); return lockSet != null && !lockSet.isEmpty(); } /** * Call the ChunkIoService to load a chunk, optionally generating the chunk. * * @param x The X coordinate of the chunk to load. * @param z The Y coordinate of the chunk to load. * @param generate Whether to generate the chunk if needed. * @return True on success, false on failure. */ public boolean loadChunk(int x, int z, boolean generate) { GlowChunk chunk = getChunk(x, z); // try to load chunk try { if (service.read(chunk)) { EventFactory.callEvent(new ChunkLoadEvent(chunk, false)); return true; } } catch (Exception e) { GlowServer.logger.log(Level.SEVERE, "Error while loading chunk (" + x + "," + z + ")", e); // an error in chunk reading may have left the chunk in an invalid state // (i.e. double initialization errors), so it's forcibly unloaded here chunk.unload(false, false); } // stop here if we can't generate if (!generate) { return false; } // get generating try { generateChunk(chunk, x, z); } catch (Throwable ex) { GlowServer.logger.log(Level.SEVERE, "Error while generating chunk (" + x + "," + z + ")", ex); return false; } EventFactory.callEvent(new ChunkLoadEvent(chunk, true)); // right now, forcePopulate takes care of populating chunks that players actually see. /*for (int x2 = x - 1; x2 <= x + 1; ++x2) { for (int z2 = z - 1; z2 <= z + 1; ++z2) { populateChunk(x2, z2, false); } }*/ return true; } /** * Unload chunks with no locks on them. */ public void unloadOldChunks() { for (Entry<Key, GlowChunk> entry : chunks.entrySet()) { Set<ChunkLock> lockSet = locks.get(entry.getKey()); if (lockSet == null || lockSet.isEmpty()) { if (!entry.getValue().unload(true, true)) { GlowServer.logger.warning("Failed to unload chunk " + world.getName() + ":" + entry.getKey()); } } if (!entry.getValue().isLoaded()) { //GlowServer.logger.info("Removing from cache " + entry.getKey()); chunks.entrySet().remove(entry); locks.remove(entry.getKey()); } } } /** * Populate a single chunk if needed. */ private void populateChunk(int x, int z, boolean force) { GlowChunk chunk = getChunk(x, z); // cancel out if it's already populated if (chunk.isPopulated()) { return; } // cancel out if the 3x3 around it isn't available for (int x2 = x - 1; x2 <= x + 1; ++x2) { for (int z2 = z - 1; z2 <= z + 1; ++z2) { if (!getChunk(x2, z2).isLoaded() && (!force || !loadChunk(x2, z2, true))) { return; } } } // it might have loaded since before, so check again that it's not already populated if (chunk.isPopulated()) { return; } chunk.setPopulated(true); Random random = new Random(world.getSeed()); long xRand = random.nextLong() / 2 * 2 + 1; long zRand = random.nextLong() / 2 * 2 + 1; random.setSeed(x * xRand + z * zRand ^ world.getSeed()); for (BlockPopulator p : world.getPopulators()) { p.populate(world, random, chunk); } EventFactory.callEvent(new ChunkPopulateEvent(chunk)); } /** * Force a chunk to be populated by loading the chunks in an area around it. Used when streaming chunks to players * so that they do not have to watch chunks being populated. * * @param x The X coordinate. * @param z The Z coordinate. */ public void forcePopulation(int x, int z) { try { populateChunk(x, z, true); } catch (Throwable ex) { GlowServer.logger.log(Level.SEVERE, "Error while populating chunk (" + x + "," + z + ")", ex); } } /** * Initialize a single chunk from the chunk generator. */ private void generateChunk(GlowChunk chunk, int x, int z) { Random random = new Random(x * 341873128712L + z * 132897987541L); BiomeGrid biomes = new BiomeGrid(); int[] biomeValues = biomeGrid[0].generateValues(x * GlowChunk.WIDTH, z * GlowChunk.HEIGHT, GlowChunk.WIDTH, GlowChunk.HEIGHT); for (int i = 0; i < biomeValues.length; i++) { biomes.biomes[i] = (byte) biomeValues[i]; } // extended sections with data GlowChunkData glowChunkData = null; if (generator instanceof GlowChunkGenerator) { glowChunkData = (GlowChunkData) generator.generateChunkData(world, random, x, z, biomes); } else { ChunkGenerator.ChunkData chunkData = generator.generateChunkData(world, random, x, z, biomes); if (chunkData != null) { glowChunkData = new GlowChunkData(world); for (int i = 0; i < 16; ++i) { for (int j = 0; j < 16; ++j) { int maxHeight = chunkData.getMaxHeight(); for (int k = 0; k < maxHeight; ++k) { MaterialData materialData = chunkData.getTypeAndData(i, k, j); if (materialData != null) { glowChunkData.setBlock(i, k, j, materialData); } else { glowChunkData.setBlock(i, k, j, new MaterialData(Material.AIR)); } } } } } } if (glowChunkData != null) { short[][] extSections = glowChunkData.getSections(); if (extSections != null) { ChunkSection[] sections = new ChunkSection[extSections.length]; for (int i = 0; i < extSections.length; ++i) { // this is sort of messy. if (extSections[i] != null) { sections[i] = new ChunkSection(); for (int j = 0; j < extSections[i].length; ++j) { sections[i].types[j] = (char) extSections[i][j]; } sections[i].recount(); } } chunk.initializeSections(sections); chunk.setBiomes(biomes.biomes); chunk.automaticHeightMap(); return; } } // extended sections short[][] extSections = generator.generateExtBlockSections(world, random, x, z, biomes); if (extSections != null) { ChunkSection[] sections = new ChunkSection[extSections.length]; for (int i = 0; i < extSections.length; ++i) { // this is sort of messy. if (extSections[i] != null) { sections[i] = new ChunkSection(); for (int j = 0; j < extSections[i].length; ++j) { sections[i].types[j] = (char) (extSections[i][j] << 4); } sections[i].recount(); } } chunk.initializeSections(sections); chunk.setBiomes(biomes.biomes); chunk.automaticHeightMap(); return; } // normal sections byte[][] blockSections = generator.generateBlockSections(world, random, x, z, biomes); if (blockSections != null) { ChunkSection[] sections = new ChunkSection[blockSections.length]; for (int i = 0; i < blockSections.length; ++i) { // this is sort of messy. if (blockSections[i] != null) { sections[i] = new ChunkSection(); for (int j = 0; j < blockSections[i].length; ++j) { sections[i].types[j] = (char) (blockSections[i][j] << 4); } sections[i].recount(); } } chunk.initializeSections(sections); chunk.setBiomes(biomes.biomes); chunk.automaticHeightMap(); return; } // deprecated flat generation byte[] types = generator.generate(world, random, x, z); ChunkSection[] sections = new ChunkSection[8]; for (int sy = 0; sy < sections.length; ++sy) { ChunkSection sec = new ChunkSection(); int by = 16 * sy; for (int cx = 0; cx < 16; ++cx) { for (int cz = 0; cz < 16; ++cz) { for (int cy = by; cy < by + 16; ++cy) { char type = (char) types[(cx * 16 + cz) * 128 + cy]; sec.types[sec.index(cx, cy, cz)] = (char) (type << 4); } } } sec.recount(); sections[sy] = sec; } chunk.initializeSections(sections); chunk.setBiomes(biomes.biomes); chunk.automaticHeightMap(); } /** * Forces generation of the given chunk. * * @param x The X coordinate. * @param z The Z coordinate. * @return Whether the chunk was successfully regenerated. */ public boolean forceRegeneration(int x, int z) { GlowChunk chunk = getChunk(x, z); if (chunk == null || !chunk.unload(false, false)) { return false; } chunk.setPopulated(false); try { generateChunk(chunk, x, z); populateChunk(x, z, false); // should this be forced? } catch (Throwable ex) { GlowServer.logger.log(Level.SEVERE, "Error while regenerating chunk (" + x + "," + z + ")", ex); return false; } return true; } /** * Gets a list of loaded chunks. * * @return The currently loaded chunks. */ public GlowChunk[] getLoadedChunks() { ArrayList<GlowChunk> result = chunks.values().stream().filter(GlowChunk::isLoaded).collect(Collectors.toCollection(ArrayList::new)); return result.toArray(new GlowChunk[result.size()]); } /** * Performs the save for the given chunk using the storage provider. * * @param chunk The chunk to save. * @return True if the save was successful. */ public boolean performSave(GlowChunk chunk) { if (chunk.isLoaded()) { try { service.write(chunk); return true; } catch (IOException ex) { GlowServer.logger.log(Level.SEVERE, "Error while saving " + chunk, ex); return false; } } return false; } public int[] getBiomeGridAtLowerRes(int x, int z, int sizeX, int sizeZ) { return biomeGrid[1].generateValues(x, z, sizeX, sizeZ); } /** * Look up the set of locks on a given chunk. * * @param key The chunk key. * @return The set of locks for that chunk. */ private Set<ChunkLock> getLockSet(Key key) { if (locks.containsKey(key)) { return locks.get(key); } else { // only create chunk if it's not in the map already Set<ChunkLock> set = new HashSet<>(); Set<ChunkLock> prev = locks.putIfAbsent(key, set); // if it was created in the intervening time, the earlier one wins return prev == null ? set : prev; } } /** * A group of locks on chunks to prevent them from being unloaded while in use. */ public static class ChunkLock implements Iterable<Key> { private final ChunkManager cm; private final String desc; private final Set<Key> keys = new HashSet<>(); public ChunkLock(ChunkManager cm, String desc) { this.cm = cm; this.desc = desc; } public void acquire(Key key) { if (keys.contains(key)) return; keys.add(key); cm.getLockSet(key).add(this); //GlowServer.logger.info(this + " acquires " + key); } public void release(Key key) { if (!keys.contains(key)) return; keys.remove(key); cm.getLockSet(key).remove(this); //GlowServer.logger.info(this + " releases " + key); } public void clear() { for (Key key : keys) { cm.getLockSet(key).remove(this); //GlowServer.logger.info(this + " clearing " + key); } keys.clear(); } @Override public String toString() { return "ChunkLock{" + desc + "}"; } @Override public Iterator<Key> iterator() { return keys.iterator(); } } /** * A BiomeGrid implementation for chunk generation. */ private class BiomeGrid implements ChunkGenerator.BiomeGrid { private final byte[] biomes = new byte[256]; @Override public Biome getBiome(int x, int z) { return GlowBiome.getBiome(biomes[x | z << 4] & 0xFF); // upcasting is very important to get extended biomes } @Override public void setBiome(int x, int z, Biome bio) { biomes[x | z << 4] = (byte) GlowBiome.getId(bio); } } }
jimmikaelkael/GlowstonePlusPlus
src/main/java/net/glowstone/ChunkManager.java
Java
mit
17,829
/******************************************************************************* * Copyright (c) 2016, 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package web; /* * Programmatic filter installed by the application's servlet container initializer. */ public class SCIProgrammaticRequestFilter extends BaseRequestFilter { { super.filterName = "SCIProgrammaticRequestFilter"; } }
OpenLiberty/open-liberty
dev/com.ibm.ws.security.jaspic_fat/test-applications/JASPIWrappingServlet.war/src/web/SCIProgrammaticRequestFilter.java
Java
epl-1.0
790
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ /* * Created on May 29, 2006 */ package org.python.pydev.editor.preferences; import org.eclipse.jface.bindings.keys.KeySequence; import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.IntegerFieldEditor; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.python.pydev.core.preferences.PyDevTypingPreferences; import org.python.pydev.plugin.PydevPlugin; import org.python.pydev.shared_core.SharedCorePlugin; import org.python.pydev.shared_core.string.StringUtils; import org.python.pydev.shared_core.string.WrapAndCaseUtils; import org.python.pydev.shared_ui.bindings.KeyBindingHelper; import org.python.pydev.shared_ui.field_editors.BooleanFieldEditorCustom; import org.python.pydev.shared_ui.field_editors.LabelFieldEditor; import org.python.pydev.shared_ui.field_editors.ScopedFieldEditorPreferencePage; import org.python.pydev.shared_ui.field_editors.ScopedPreferencesFieldEditor; /** * This class is the class that resulted of the separation of the PydevPrefs because * it was too big. * * @author Fabio */ public class PydevTypingPreferencesPage extends ScopedFieldEditorPreferencePage implements IWorkbenchPreferencePage { public PydevTypingPreferencesPage() { super(GRID); setDescription("Editor"); setPreferenceStore(PydevPlugin.getDefault().getPreferenceStore()); } @Override protected void createFieldEditors() { final Composite initialParent = getFieldEditorParent(); final Composite p = initialParent; String preference = PyDevTypingPreferences.AUTO_LINK; String text = "Enable link on automatic parenthesis or literals closing?"; String tooltip = "Enabling this option will enable the linking mode after a parenthesis or literal is auto-closed."; addBooleanField(p, preference, text, tooltip); //auto par addBooleanField( p, PyDevTypingPreferences.AUTO_PAR, "Automatic parentheses insertion", "Enabling this option will enable automatic insertion of parentheses. " + "Specifically, whenever you hit a brace such as '(', '{', or '[', its related peer will be inserted " + "and your cursor will be placed between the two braces."); //smart indent? final BooleanFieldEditorCustom useSmartIndent = addBooleanField(p, PyDevTypingPreferences.SMART_INDENT_PAR, "Use smart-indent?", ""); //pep-8 indent? final BooleanFieldEditorCustom usePep8Indent = addBooleanField(p, PyDevTypingPreferences.INDENT_AFTER_PAR_AS_PEP8, " After {, [, ( indent as pep-8.\n", ""); final LabelFieldEditor labelPep8_1 = new LabelFieldEditor("__UNUSED__00", " I.e.: add indentation plus additional level right after", p); addField(labelPep8_1); final LabelFieldEditor labelPep8_2 = new LabelFieldEditor("__UNUSED__01", "", p); addField(labelPep8_2); // fill second column final LabelFieldEditor labelPep8_3 = new LabelFieldEditor("__UNUSED__02", " braces or indent to braces after another token.", p); addField(labelPep8_3); // indent final BooleanFieldEditorCustom autoIndentToParLevel = addBooleanField(p, PyDevTypingPreferences.AUTO_INDENT_TO_PAR_LEVEL, " After {, [, ( indent to its level (indents by tabs if unchecked)", ""); final IntegerFieldEditor indentationLevelsToAddField = new IntegerFieldEditor(PyDevTypingPreferences.AUTO_INDENT_AFTER_PAR_WIDTH, " Number of indentation levels to add:", p, 1); addField(indentationLevelsToAddField); final Runnable fixEnablement = new Runnable() { @Override public void run() { boolean useSmartIndentBool = useSmartIndent.getBooleanValue(); boolean usePep8IndentBool = usePep8Indent.getBooleanValue(); boolean useAutoIndentToParLevelBool = autoIndentToParLevel.getBooleanValue(); fixParensIndentEnablement(p, usePep8Indent, autoIndentToParLevel, indentationLevelsToAddField, labelPep8_1, labelPep8_2, labelPep8_3, useSmartIndentBool, usePep8IndentBool, useAutoIndentToParLevelBool); } }; autoIndentToParLevel.getCheckBox(p).addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fixEnablement.run(); } }); usePep8Indent.getCheckBox(p).addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fixEnablement.run(); } }); useSmartIndent.getCheckBox(p).addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fixEnablement.run(); } }); fixParensIndentEnablement(p, usePep8Indent, autoIndentToParLevel, indentationLevelsToAddField, labelPep8_1, labelPep8_2, labelPep8_3, getPreferenceStore().getBoolean(PyDevTypingPreferences.SMART_INDENT_PAR), getPreferenceStore().getBoolean(PyDevTypingPreferences.INDENT_AFTER_PAR_AS_PEP8), getPreferenceStore().getBoolean(PyDevTypingPreferences.AUTO_INDENT_TO_PAR_LEVEL)); //auto dedent 'else:' addBooleanField(p, PyDevTypingPreferences.AUTO_DEDENT_ELSE, "Automatic dedent of 'else:' and 'elif:'", ""); //auto braces addBooleanField( p, PyDevTypingPreferences.AUTO_BRACES, "Automatically skip matching braces when typing", "Enabling this option will enable automatically skipping matching braces " + "if you try to insert them. For example, if you have the following code:\n\n" + "def function(self):\n\n" + "...with your cursor before the end parenthesis (after the 'f' in \"self\"), typing a ')' will " + "simply move the cursor to the position after the ')' without inserting a new one."); //auto colon addBooleanField( p, PyDevTypingPreferences.AUTO_COLON, "Automatic colon detection", "Enabling this feature will enable the editor to detect if you are trying " + "to enter a colon which is already there. Instead of inserting another colon, the editor will " + "simply move your cursor to the next position after the colon."); //auto literals addBooleanField(p, PyDevTypingPreferences.AUTO_LITERALS, "Automatic literal closing", "Automatically close literals " + "(when ' or \" is added, another one is added to close it)."); //auto import str addBooleanField(p, PyDevTypingPreferences.AUTO_WRITE_IMPORT_STR, "Automatic insertion of the 'import' string on 'from xxx' ", "Enabling this will allow the editor to automatically write the" + "'import' string when you write a space after you've written 'from xxx '."); addBooleanField(p, PyDevTypingPreferences.AUTO_ADD_SELF, "Add 'self' automatically when declaring methods?", ""); KeySequence down = KeyBindingHelper.getCommandKeyBinding(ITextEditorActionDefinitionIds.MOVE_LINES_DOWN); KeySequence up = KeyBindingHelper.getCommandKeyBinding(ITextEditorActionDefinitionIds.MOVE_LINES_UP); String downKey = down != null ? down.format() : "Alt+Down"; //set the default if not there String upKey = up != null ? up.format() : "Alt+Up"; //set the default if not there addBooleanField(p, PyDevTypingPreferences.SMART_LINE_MOVE, StringUtils.format("Smart move for line up (%s) and line down (%s)?.", upKey, downKey), ""); addField(new LabelFieldEditor("__UNUSED__", "Note: smart move line up/down change applied on editor restart.", p)); addField(new ScopedPreferencesFieldEditor(p, SharedCorePlugin.DEFAULT_PYDEV_PREFERENCES_SCOPE, this)); } private BooleanFieldEditorCustom addBooleanField(Composite p, String preference, String text, String tooltip) { BooleanFieldEditorCustom field = new BooleanFieldEditorCustom(preference, text, BooleanFieldEditor.DEFAULT, p); addField(field); field.setTooltip(p, WrapAndCaseUtils.wrap(tooltip, PyDevTypingPreferences.TOOLTIP_WIDTH)); return field; } @Override public void init(IWorkbench workbench) { } private void fixParensIndentEnablement(final Composite p, final BooleanFieldEditorCustom usePep8Indent, final BooleanFieldEditorCustom autoIndentToParLevel, final IntegerFieldEditor indentationLevelsToAddField, LabelFieldEditor labelPep8_1, LabelFieldEditor labelPep8_2, LabelFieldEditor labelPep8_3, boolean useSmartIndentBool, boolean usePep8IndentBool, boolean useAutoIndentToParLevelBool) { if (!useSmartIndentBool) { // Disable all usePep8Indent.setEnabled(false, p); labelPep8_1.setEnabled(false, p); labelPep8_2.setEnabled(false, p); labelPep8_3.setEnabled(false, p); autoIndentToParLevel.setEnabled(false, p); indentationLevelsToAddField.setEnabled(false, p); } else { usePep8Indent.setEnabled(true, p); labelPep8_1.setEnabled(true, p); labelPep8_2.setEnabled(true, p); labelPep8_3.setEnabled(true, p); // Smart indent enabled, let's see if pep-8 is enabled if (usePep8IndentBool) { autoIndentToParLevel.setEnabled(false, p); indentationLevelsToAddField.setEnabled(false, p); } else { autoIndentToParLevel.setEnabled(true, p); indentationLevelsToAddField.setEnabled(!useAutoIndentToParLevelBool, p); } } } }
akurtakov/Pydev
plugins/org.python.pydev/src/org/python/pydev/editor/preferences/PydevTypingPreferencesPage.java
Java
epl-1.0
10,793
/******************************************************************************* * Copyright (c) 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package io.openliberty.wsoc.endpoints.client.trace; import java.io.IOException; import java.util.logging.Logger; import javax.websocket.CloseReason; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.Session; import io.openliberty.wsoc.util.wsoc.TestHelper; import io.openliberty.wsoc.util.wsoc.WsocTestContext; /** * */ public abstract class ProgrammaticClientEP extends Endpoint implements TestHelper { private static final Logger LOG = Logger.getLogger(ProgrammaticClientEP.class.getName()); /** * */ public ProgrammaticClientEP() { // TODO Auto-generated constructor stub } public WsocTestContext _wtr = null; @Override public void addTestResponse(WsocTestContext wtr) { _wtr = wtr; } @Override public WsocTestContext getTestResponse() { return _wtr; } public static class CloseTest extends ProgrammaticClientEP { private String[] _data = {}; public CloseTest(String[] data) { _data = data; } @Override public void onClose(Session session, CloseReason closeReason) { _wtr.addMessage(closeReason.getCloseCode().getCode() + ":" + closeReason.getReasonPhrase()); _wtr.setClosedAlready(true); if (_wtr.limitReached()) { _wtr.terminateClient(); } } /* * (non-Javadoc) * * @see javax.websocket.Endpoint#onOpen(javax.websocket.Session, javax.websocket.EndpointConfig) */ @Override public void onOpen(Session sess, EndpointConfig arg1) { try { sess.getBasicRemote().sendText(_data[0]); } catch (Exception e) { _wtr.addExceptionAndTerminate("Error publishing initial message", e); } } } public static class CloseTestOnOpen extends ProgrammaticClientEP { private String[] _data = {}; public CloseTestOnOpen(String[] data) { _data = data; } @Override public void onClose(Session session, CloseReason closeReason) { if ((closeReason.getCloseCode().getCode() == 1006) && (closeReason.getReasonPhrase().equals("WebSocket Read EOF"))) { System.out.println("Jetty detected premature closure..."); } _wtr.addMessage(closeReason.getCloseCode().getCode() + ":" + closeReason.getReasonPhrase()); _wtr.setClosedAlready(true); if (_wtr.limitReached()) { _wtr.terminateClient(); } } /* * (non-Javadoc) * * @see javax.websocket.Endpoint#onOpen(javax.websocket.Session, javax.websocket.EndpointConfig) */ @Override public void onOpen(Session sess, EndpointConfig arg1) {} } @Override public void onClose(Session session, CloseReason closeReason) { try { session.close(); } catch (IOException e) { _wtr.addExceptionAndTerminate("Error closing session", e); } } @Override public void onError(Session session, java.lang.Throwable throwable) { _wtr.addExceptionAndTerminate("Error during wsoc session", throwable); } }
OpenLiberty/open-liberty
dev/io.openliberty.wsoc.internal_fat/fat/src/io/openliberty/wsoc/endpoints/client/trace/ProgrammaticClientEP.java
Java
epl-1.0
3,861
package com.ola1.ola_maven; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
alextaaar/repozytorium
ola-maven/src/test/java/com/ola1/ola_maven/AppTest.java
Java
epl-1.0
684
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.heos.internal.resources; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; /** * The {@link HeosCommands} provides the available commands for the HEOS network. * * @author Johannes Einig - Initial contribution */ @NonNullByDefault public class HeosCommands { // System Commands private static final String REGISTER_CHANGE_EVENT_ON = "heos://system/register_for_change_events?enable=on"; private static final String REGISTER_CHANGE_EVENT_OFF = "heos://system/register_for_change_events?enable=off"; private static final String HEOS_ACCOUNT_CHECK = "heos://system/check_account"; private static final String prettifyJSONon = "heos://system/prettify_json_response?enable=on"; private static final String prettifyJSONoff = "heos://system/prettify_json_response?enable=off"; private static final String rebootSystem = "heos://system/reboot"; private static final String signOut = "heos://system/sign_out"; private static final String heartbeat = "heos://system/heart_beat"; // Player Commands Control private static final String setPlayStatePlay = "heos://player/set_play_state?pid="; private static final String setPlayStatePause = "heos://player/set_play_state?pid="; private static final String setPlayStateStop = "heos://player/set_play_state?pid="; private static final String setVolume = "heos://player/set_volume?pid="; private static final String volumeUp = "heos://player/volume_up?pid="; private static final String volumeDown = "heos://player/volume_down?pid="; private static final String setMute = "heos://player/set_mute?pid="; private static final String setMuteToggle = "heos://player/toggle_mute?pid="; private static final String playNext = "heos://player/play_next?pid="; private static final String playPrevious = "heos://player/play_previous?pid="; private static final String playQueueItem = "heos://player/play_queue?pid="; private static final String clearQueue = "heos://player/clear_queue?pid="; private static final String deleteQueueItem = "heos://player/remove_from_queue?pid="; private static final String setPlayMode = "heos://player/set_play_mode?pid="; // Group Commands Control private static final String getGroups = "heos://group/get_groups"; private static final String getGroupsInfo = "heos://group/get_group_info?gid="; private static final String setGroup = "heos://group/set_group?pid="; private static final String getGroupVolume = "heos://group/get_volume?gid="; private static final String setGroupVolume = "heos://group/set_volume?gid="; private static final String getGroupMute = "heos://group/get_mute?gid="; private static final String setGroupMute = "heos://group/set_mute?gid="; private static final String toggleGroupMute = "heos://group/toggle_mute?gid="; private static final String groupVolumeUp = "heos://group/volume_up?gid="; private static final String groupVolumeDown = "heos://group/volume_down?gid="; // Player Commands get Information private static final String getPlayers = "heos://player/get_players"; private static final String getPlayerInfo = "heos://player/get_player_info?pid="; private static final String getPlayState = "heos://player/get_play_state?pid="; private static final String getNowPlayingMedia = "heos://player/get_now_playing_media?pid="; private static final String playerGetVolume = "heos://player/get_volume?pid="; private static final String playerGetMute = "heos://player/get_mute?pid="; private static final String getQueue = "heos://player/get_queue?pid="; private static final String getPlayMode = "heos://player/get_play_mode?pid="; // Browse Commands private static final String getMusicSources = "heos://browse/get_music_sources"; private static final String browseSource = "heos://browse/browse?sid="; private static final String playStream = "heos://browse/play_stream?pid="; private static final String addToQueue = "heos://browse/add_to_queue?pid="; private static final String playInputSource = "heos://browse/play_input?pid="; private static final String playURL = "heos://browse/play_stream?pid="; public static String registerChangeEventOn() { return REGISTER_CHANGE_EVENT_ON; } public static String registerChangeEventOff() { return REGISTER_CHANGE_EVENT_OFF; } public static String heosAccountCheck() { return HEOS_ACCOUNT_CHECK; } public static String setPlayStatePlay(String pid) { return setPlayStatePlay + pid + "&state=play"; } public static String setPlayStatePause(String pid) { return setPlayStatePause + pid + "&state=pause"; } public static String setPlayStateStop(String pid) { return setPlayStateStop + pid + "&state=stop"; } public static String volumeUp(String pid) { return volumeUp + pid + "&step=1"; } public static String volumeDown(String pid) { return volumeDown + pid + "&step=1"; } public static String setMuteOn(String pid) { return setMute + pid + "&state=on"; } public static String setMuteOff(String pid) { return setMute + pid + "&state=off"; } public static String setMuteToggle(String pid) { return setMuteToggle + pid + "&state=off"; } public static String setShuffleMode(String pid, String shuffle) { return setPlayMode + pid + "&shuffle=" + shuffle; } public static String setRepeatMode(String pid, String repeat) { return setPlayMode + pid + "&repeat=" + repeat; } public static String getPlayMode(String pid) { return getPlayMode + pid; } public static String playNext(String pid) { return playNext + pid; } public static String playPrevious(String pid) { return playPrevious + pid; } public static String setVolume(String vol, String pid) { return setVolume + pid + "&level=" + vol; } public static String getPlayers() { return getPlayers; } public static String getPlayerInfo(String pid) { return getPlayerInfo + pid; } public static String getPlayState(String pid) { return getPlayState + pid; } public static String getNowPlayingMedia(String pid) { return getNowPlayingMedia + pid; } public static String getVolume(String pid) { return playerGetVolume + pid; } public static String getMusicSources() { return getMusicSources; } public static String prettifyJSONon() { return prettifyJSONon; } public static String prettifyJSONoff() { return prettifyJSONoff; } public static String getMute(String pid) { return playerGetMute + pid; } public static String getQueue(String pid) { return getQueue + pid; } public static String getQueue(String pid, int start, int end) { return getQueue(pid) + "&range=" + start + "," + end; } public static String playQueueItem(String pid, String qid) { return playQueueItem + pid + "&qid=" + qid; } public static String deleteQueueItem(String pid, String qid) { return deleteQueueItem + pid + "&qid=" + qid; } public static String browseSource(String sid) { return browseSource + sid; } public static String playStream(String pid) { return playStream + pid; } public static String addToQueue(String pid) { return addToQueue + pid; } public static String addContainerToQueuePlayNow(String pid, String sid, String cid) { return addToQueue + pid + "&sid=" + sid + "&cid=" + cid + "&aid=1"; } public static String clearQueue(String pid) { return clearQueue + pid; } public static String rebootSystem() { return rebootSystem; } public static String playStream(@Nullable String pid, @Nullable String sid, @Nullable String cid, @Nullable String mid, @Nullable String name) { String newCommand = playStream; if (pid != null) { newCommand = newCommand + pid; } if (sid != null) { newCommand = newCommand + "&sid=" + sid; } if (cid != null) { newCommand = newCommand + "&cid=" + cid; } if (mid != null) { newCommand = newCommand + "&mid=" + mid; } if (name != null) { newCommand = newCommand + "&name=" + name; } return newCommand; } public static String playStream(String pid, String sid, String mid) { return playStream + pid + "&sid=" + sid + "&mid=" + mid; } public static String playInputSource(String des_pid, String source_pid, String input) { return playInputSource + des_pid + "&spid=" + source_pid + "&input=inputs/" + input; } public static String playURL(String pid, String url) { return playURL + pid + "&url=" + url; } public static String signIn(String username, String password) { String encodedUsername = urlEncode(username); String encodedPassword = urlEncode(password); return "heos://system/sign_in?un=" + encodedUsername + "&pw=" + encodedPassword; } public static String signOut() { return signOut; } public static String heartbeat() { return heartbeat; } public static String getGroups() { return getGroups; } public static String getGroupInfo(String gid) { return getGroupsInfo + gid; } public static String setGroup(String[] gid) { String players = String.join(",", gid); return setGroup + players; } public static String getGroupVolume(String gid) { return getGroupVolume + gid; } public static String setGroupVolume(String volume, String gid) { return setGroupVolume + gid + "&level=" + volume; } public static String setGroupVolumeUp(String gid) { return groupVolumeUp + gid + "&step=1"; } public static String setGroupVolumeDown(String gid) { return groupVolumeDown + gid + "&step=1"; } public static String getGroupMute(String gid) { return getGroupMute + gid; } public static String setGroupMuteOn(String gid) { return setGroupMute + gid + "&state=on"; } public static String setGroupMuteOff(String gid) { return setGroupMute + gid + "&state=off"; } public static String getToggleGroupMute(String gid) { return toggleGroupMute + gid; } private static String urlEncode(String username) { try { String encoded = URLEncoder.encode(username, StandardCharsets.UTF_8.toString()); // however it cannot handle escaped @ signs return encoded.replace("%40", "@"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is not supported, bailing out"); } } }
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.heos/src/main/java/org/openhab/binding/heos/internal/resources/HeosCommands.java
Java
epl-1.0
11,634
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jaxrs.fat.beanvalidation; import java.util.Collection; import javax.validation.Valid; import javax.validation.constraints.Min; public interface BookStoreValidatable { @Valid Collection<BookWithValidation> list(@Min(1) int page); }
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/beanvalidation/src/com/ibm/ws/jaxrs/fat/beanvalidation/BookStoreValidatable.java
Java
epl-1.0
796
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.monopriceaudio.internal.handler; import static org.openhab.binding.monopriceaudio.internal.MonopriceAudioBindingConstants.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.monopriceaudio.internal.MonopriceAudioException; import org.openhab.binding.monopriceaudio.internal.MonopriceAudioStateDescriptionOptionProvider; import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioCommand; import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioConnector; import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioDefaultConnector; import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioIpConnector; import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioMessageEvent; import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioMessageEventListener; import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioSerialConnector; import org.openhab.binding.monopriceaudio.internal.communication.MonopriceAudioZone; import org.openhab.binding.monopriceaudio.internal.configuration.MonopriceAudioThingConfiguration; import org.openhab.binding.monopriceaudio.internal.dto.MonopriceAudioZoneDTO; import org.openhab.core.io.transport.serial.SerialPortManager; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OpenClosedType; import org.openhab.core.library.types.PercentType; import org.openhab.core.thing.Channel; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.binding.BaseThingHandler; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; import org.openhab.core.types.State; import org.openhab.core.types.StateOption; import org.openhab.core.types.UnDefType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link MonopriceAudioHandler} is responsible for handling commands, which are sent to one of the channels. * * Based on the Rotel binding by Laurent Garnier * * @author Michael Lobstein - Initial contribution */ @NonNullByDefault public class MonopriceAudioHandler extends BaseThingHandler implements MonopriceAudioMessageEventListener { private static final long RECON_POLLING_INTERVAL_SEC = 60; private static final long INITIAL_POLLING_DELAY_SEC = 5; private static final Pattern PATTERN = Pattern .compile("^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})"); private static final String ZONE = "ZONE"; private static final String ALL = "all"; private static final String CHANNEL_DELIMIT = "#"; private static final String ON_STR = "01"; private static final String OFF_STR = "00"; private static final int ONE = 1; private static final int MAX_ZONES = 18; private static final int MAX_SRC = 6; private static final int MIN_VOLUME = 0; private static final int MAX_VOLUME = 38; private static final int MIN_TONE = -7; private static final int MAX_TONE = 7; private static final int MIN_BALANCE = -10; private static final int MAX_BALANCE = 10; private static final int BALANCE_OFFSET = 10; private static final int TONE_OFFSET = 7; // build a Map with a MonopriceAudioZoneDTO for each zoneId private final Map<String, MonopriceAudioZoneDTO> zoneDataMap = MonopriceAudioZone.VALID_ZONE_IDS.stream() .collect(Collectors.toMap(s -> s, s -> new MonopriceAudioZoneDTO())); private final Logger logger = LoggerFactory.getLogger(MonopriceAudioHandler.class); private final MonopriceAudioStateDescriptionOptionProvider stateDescriptionProvider; private final SerialPortManager serialPortManager; private @Nullable ScheduledFuture<?> reconnectJob; private @Nullable ScheduledFuture<?> pollingJob; private MonopriceAudioConnector connector = new MonopriceAudioDefaultConnector(); private Set<String> ignoreZones = new HashSet<>(); private long lastPollingUpdate = System.currentTimeMillis(); private long pollingInterval = 0; private int numZones = 0; private int allVolume = 1; private int initialAllVolume = 0; private Object sequenceLock = new Object(); public MonopriceAudioHandler(Thing thing, MonopriceAudioStateDescriptionOptionProvider stateDescriptionProvider, SerialPortManager serialPortManager) { super(thing); this.stateDescriptionProvider = stateDescriptionProvider; this.serialPortManager = serialPortManager; } @Override public void initialize() { final String uid = this.getThing().getUID().getAsString(); MonopriceAudioThingConfiguration config = getConfigAs(MonopriceAudioThingConfiguration.class); final String serialPort = config.serialPort; final String host = config.host; final Integer port = config.port; final String ignoreZonesConfig = config.ignoreZones; // Check configuration settings String configError = null; if ((serialPort == null || serialPort.isEmpty()) && (host == null || host.isEmpty())) { configError = "undefined serialPort and host configuration settings; please set one of them"; } else if (serialPort != null && (host == null || host.isEmpty())) { if (serialPort.toLowerCase().startsWith("rfc2217")) { configError = "use host and port configuration settings for a serial over IP connection"; } } else { if (port == null) { configError = "undefined port configuration setting"; } else if (port <= 0) { configError = "invalid port configuration setting"; } } if (configError != null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, configError); return; } if (serialPort != null) { connector = new MonopriceAudioSerialConnector(serialPortManager, serialPort, uid); } else if (port != null) { connector = new MonopriceAudioIpConnector(host, port, uid); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Either Serial port or Host & Port must be specifed"); return; } pollingInterval = config.pollingInterval; numZones = config.numZones; initialAllVolume = config.initialAllVolume; // If zones were specified to be ignored by the 'all*' commands, use the specified binding // zone ids to get the controller's internal zone ids and save those to a list if (ignoreZonesConfig != null) { for (String zone : ignoreZonesConfig.split(",")) { try { int zoneInt = Integer.parseInt(zone); if (zoneInt >= ONE && zoneInt <= MAX_ZONES) { ignoreZones.add(ZONE + zoneInt); } else { logger.warn("Invalid ignore zone value: {}, value must be between {} and {}", zone, ONE, MAX_ZONES); } } catch (NumberFormatException nfe) { logger.warn("Invalid ignore zone value: {}", zone); } } } // Build a state option list for the source labels List<StateOption> sourcesLabels = new ArrayList<>(); sourcesLabels.add(new StateOption("1", config.inputLabel1)); sourcesLabels.add(new StateOption("2", config.inputLabel2)); sourcesLabels.add(new StateOption("3", config.inputLabel3)); sourcesLabels.add(new StateOption("4", config.inputLabel4)); sourcesLabels.add(new StateOption("5", config.inputLabel5)); sourcesLabels.add(new StateOption("6", config.inputLabel6)); // Put the source labels on all active zones List<Integer> activeZones = IntStream.range(1, numZones + 1).boxed().collect(Collectors.toList()); stateDescriptionProvider.setStateOptions( new ChannelUID(getThing().getUID(), ALL + CHANNEL_DELIMIT + CHANNEL_TYPE_ALLSOURCE), sourcesLabels); activeZones.forEach(zoneNum -> { stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), ZONE.toLowerCase() + zoneNum + CHANNEL_DELIMIT + CHANNEL_TYPE_SOURCE), sourcesLabels); }); // remove the channels for the zones we are not using if (numZones < MAX_ZONES) { List<Channel> channels = new ArrayList<>(this.getThing().getChannels()); List<Integer> zonesToRemove = IntStream.range(numZones + 1, MAX_ZONES + 1).boxed() .collect(Collectors.toList()); zonesToRemove.forEach(zone -> { channels.removeIf(c -> (c.getUID().getId().contains(ZONE.toLowerCase() + zone))); }); updateThing(editThing().withChannels(channels).build()); } // initialize the all volume state allVolume = initialAllVolume; long allVolumePct = Math .round((double) (initialAllVolume - MIN_VOLUME) / (double) (MAX_VOLUME - MIN_VOLUME) * 100.0); updateState(ALL + CHANNEL_DELIMIT + CHANNEL_TYPE_ALLVOLUME, new PercentType(BigDecimal.valueOf(allVolumePct))); scheduleReconnectJob(); schedulePollingJob(); updateStatus(ThingStatus.UNKNOWN); } @Override public void dispose() { cancelReconnectJob(); cancelPollingJob(); closeConnection(); ignoreZones.clear(); } @Override public void handleCommand(ChannelUID channelUID, Command command) { String channel = channelUID.getId(); String[] channelSplit = channel.split(CHANNEL_DELIMIT); MonopriceAudioZone zone = MonopriceAudioZone.valueOf(channelSplit[0].toUpperCase()); String channelType = channelSplit[1]; if (getThing().getStatus() != ThingStatus.ONLINE) { logger.debug("Thing is not ONLINE; command {} from channel {} is ignored", command, channel); return; } boolean success = true; synchronized (sequenceLock) { if (!connector.isConnected()) { logger.debug("Command {} from channel {} is ignored: connection not established", command, channel); return; } if (command instanceof RefreshType) { MonopriceAudioZoneDTO zoneDTO = zoneDataMap.get(zone.getZoneId()); if (zoneDTO != null) { updateChannelState(zone, channelType, zoneDTO); } else { logger.info("Could not execute REFRESH command for zone {}: null", zone.getZoneId()); } return; } Stream<String> zoneStream = MonopriceAudioZone.VALID_ZONES.stream().limit(numZones); try { switch (channelType) { case CHANNEL_TYPE_POWER: if (command instanceof OnOffType) { connector.sendCommand(zone, MonopriceAudioCommand.POWER, command == OnOffType.ON ? 1 : 0); zoneDataMap.get(zone.getZoneId()).setPower(command == OnOffType.ON ? ON_STR : OFF_STR); } break; case CHANNEL_TYPE_SOURCE: if (command instanceof DecimalType) { int value = ((DecimalType) command).intValue(); if (value >= ONE && value <= MAX_SRC) { logger.debug("Got source command {} zone {}", value, zone); connector.sendCommand(zone, MonopriceAudioCommand.SOURCE, value); zoneDataMap.get(zone.getZoneId()).setSource(String.format("%02d", value)); } } break; case CHANNEL_TYPE_VOLUME: if (command instanceof PercentType) { int value = (int) Math .round(((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME)) + MIN_VOLUME; logger.debug("Got volume command {} zone {}", value, zone); connector.sendCommand(zone, MonopriceAudioCommand.VOLUME, value); zoneDataMap.get(zone.getZoneId()).setVolume(value); } break; case CHANNEL_TYPE_MUTE: if (command instanceof OnOffType) { connector.sendCommand(zone, MonopriceAudioCommand.MUTE, command == OnOffType.ON ? 1 : 0); zoneDataMap.get(zone.getZoneId()).setMute(command == OnOffType.ON ? ON_STR : OFF_STR); } break; case CHANNEL_TYPE_TREBLE: if (command instanceof DecimalType) { int value = ((DecimalType) command).intValue(); if (value >= MIN_TONE && value <= MAX_TONE) { logger.debug("Got treble command {} zone {}", value, zone); connector.sendCommand(zone, MonopriceAudioCommand.TREBLE, value + TONE_OFFSET); zoneDataMap.get(zone.getZoneId()).setTreble(value + TONE_OFFSET); } } break; case CHANNEL_TYPE_BASS: if (command instanceof DecimalType) { int value = ((DecimalType) command).intValue(); if (value >= MIN_TONE && value <= MAX_TONE) { logger.debug("Got bass command {} zone {}", value, zone); connector.sendCommand(zone, MonopriceAudioCommand.BASS, value + TONE_OFFSET); zoneDataMap.get(zone.getZoneId()).setBass(value + TONE_OFFSET); } } break; case CHANNEL_TYPE_BALANCE: if (command instanceof DecimalType) { int value = ((DecimalType) command).intValue(); if (value >= MIN_BALANCE && value <= MAX_BALANCE) { logger.debug("Got balance command {} zone {}", value, zone); connector.sendCommand(zone, MonopriceAudioCommand.BALANCE, value + BALANCE_OFFSET); zoneDataMap.get(zone.getZoneId()).setBalance(value + BALANCE_OFFSET); } } break; case CHANNEL_TYPE_DND: if (command instanceof OnOffType) { connector.sendCommand(zone, MonopriceAudioCommand.DND, command == OnOffType.ON ? 1 : 0); zoneDataMap.get(zone.getZoneId()).setDnd(command == OnOffType.ON ? ON_STR : OFF_STR); } break; case CHANNEL_TYPE_ALLPOWER: if (command instanceof OnOffType) { zoneStream.forEach((zoneName) -> { if (command == OnOffType.OFF || !ignoreZones.contains(zoneName)) { try { connector.sendCommand(MonopriceAudioZone.valueOf(zoneName), MonopriceAudioCommand.POWER, command == OnOffType.ON ? 1 : 0); if (command == OnOffType.ON) { // reset the volume of each zone to allVolume connector.sendCommand(MonopriceAudioZone.valueOf(zoneName), MonopriceAudioCommand.VOLUME, allVolume); } } catch (MonopriceAudioException e) { logger.warn("Error Turning All Zones On: {}", e.getMessage()); } } }); } break; case CHANNEL_TYPE_ALLSOURCE: if (command instanceof DecimalType) { int value = ((DecimalType) command).intValue(); if (value >= ONE && value <= MAX_SRC) { zoneStream.forEach((zoneName) -> { if (!ignoreZones.contains(zoneName)) { try { connector.sendCommand(MonopriceAudioZone.valueOf(zoneName), MonopriceAudioCommand.SOURCE, value); } catch (MonopriceAudioException e) { logger.warn("Error Setting Source for All Zones: {}", e.getMessage()); } } }); } } break; case CHANNEL_TYPE_ALLVOLUME: if (command instanceof PercentType) { int value = (int) Math .round(((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME)) + MIN_VOLUME; allVolume = value; zoneStream.forEach((zoneName) -> { if (!ignoreZones.contains(zoneName)) { try { connector.sendCommand(MonopriceAudioZone.valueOf(zoneName), MonopriceAudioCommand.VOLUME, value); } catch (MonopriceAudioException e) { logger.warn("Error Setting Volume for All Zones: {}", e.getMessage()); } } }); } break; case CHANNEL_TYPE_ALLMUTE: if (command instanceof OnOffType) { int cmd = command == OnOffType.ON ? 1 : 0; zoneStream.forEach((zoneName) -> { if (!ignoreZones.contains(zoneName)) { try { connector.sendCommand(MonopriceAudioZone.valueOf(zoneName), MonopriceAudioCommand.MUTE, cmd); } catch (MonopriceAudioException e) { logger.warn("Error Setting Mute for All Zones: {}", e.getMessage()); } } }); } break; default: success = false; logger.debug("Command {} from channel {} failed: unexpected command", command, channel); break; } if (success) { logger.trace("Command {} from channel {} succeeded", command, channel); } } catch (MonopriceAudioException e) { logger.warn("Command {} from channel {} failed: {}", command, channel, e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Sending command failed"); closeConnection(); scheduleReconnectJob(); } } } /** * Open the connection with the MonopriceAudio device * * @return true if the connection is opened successfully or false if not */ private synchronized boolean openConnection() { connector.addEventListener(this); try { connector.open(); } catch (MonopriceAudioException e) { logger.debug("openConnection() failed: {}", e.getMessage()); } logger.debug("openConnection(): {}", connector.isConnected() ? "connected" : "disconnected"); return connector.isConnected(); } /** * Close the connection with the MonopriceAudio device */ private synchronized void closeConnection() { if (connector.isConnected()) { connector.close(); connector.removeEventListener(this); logger.debug("closeConnection(): disconnected"); } } @Override public void onNewMessageEvent(MonopriceAudioMessageEvent evt) { String key = evt.getKey(); String updateData = evt.getValue().trim(); if (!MonopriceAudioConnector.KEY_ERROR.equals(key)) { updateStatus(ThingStatus.ONLINE); } try { switch (key) { case MonopriceAudioConnector.KEY_ERROR: logger.debug("Reading feedback message failed"); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Reading thread ended"); closeConnection(); break; case MonopriceAudioConnector.KEY_ZONE_UPDATE: String zoneId = updateData.substring(0, 2); MonopriceAudioZoneDTO zoneDTO = zoneDataMap.get(zoneId); if (MonopriceAudioZone.VALID_ZONE_IDS.contains(zoneId) && zoneDTO != null) { MonopriceAudioZone targetZone = MonopriceAudioZone.fromZoneId(zoneId); processZoneUpdate(targetZone, zoneDTO, updateData); } else { logger.warn("invalid event: {} for key: {} or zone data null", evt.getValue(), key); } break; default: logger.debug("onNewMessageEvent: unhandled key {}", key); break; } } catch (NumberFormatException e) { logger.warn("Invalid value {} for key {}", updateData, key); } catch (MonopriceAudioException e) { logger.warn("Error processing zone update: {}", e.getMessage()); } } /** * Schedule the reconnection job */ private void scheduleReconnectJob() { logger.debug("Schedule reconnect job"); cancelReconnectJob(); reconnectJob = scheduler.scheduleWithFixedDelay(() -> { synchronized (sequenceLock) { if (!connector.isConnected()) { logger.debug("Trying to reconnect..."); closeConnection(); String error = null; if (openConnection()) { try { long prevUpdateTime = lastPollingUpdate; connector.queryZone(MonopriceAudioZone.ZONE1); // prevUpdateTime should have changed if a zone update was received if (lastPollingUpdate == prevUpdateTime) { error = "Controller not responding to status requests"; } } catch (MonopriceAudioException e) { error = "First command after connection failed"; logger.warn("{}: {}", error, e.getMessage()); closeConnection(); } } else { error = "Reconnection failed"; } if (error != null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, error); } else { updateStatus(ThingStatus.ONLINE); lastPollingUpdate = System.currentTimeMillis(); } } } }, 1, RECON_POLLING_INTERVAL_SEC, TimeUnit.SECONDS); } /** * Cancel the reconnection job */ private void cancelReconnectJob() { ScheduledFuture<?> reconnectJob = this.reconnectJob; if (reconnectJob != null) { reconnectJob.cancel(true); this.reconnectJob = null; } } /** * Schedule the polling job */ private void schedulePollingJob() { logger.debug("Schedule polling job"); cancelPollingJob(); pollingJob = scheduler.scheduleWithFixedDelay(() -> { synchronized (sequenceLock) { if (connector.isConnected()) { logger.debug("Polling the controller for updated status..."); // poll each zone up to the number of zones specified in the configuration MonopriceAudioZone.VALID_ZONES.stream().limit(numZones).forEach((zoneName) -> { try { connector.queryZone(MonopriceAudioZone.valueOf(zoneName)); } catch (MonopriceAudioException e) { logger.warn("Polling error: {}", e.getMessage()); } }); // if the last successful polling update was more than 2.25 intervals ago, the controller // is either switched off or not responding even though the connection is still good if ((System.currentTimeMillis() - lastPollingUpdate) > (pollingInterval * 2.25 * 1000)) { logger.warn("Controller not responding to status requests"); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Controller not responding to status requests"); closeConnection(); scheduleReconnectJob(); } } } }, INITIAL_POLLING_DELAY_SEC, pollingInterval, TimeUnit.SECONDS); } /** * Cancel the polling job */ private void cancelPollingJob() { ScheduledFuture<?> pollingJob = this.pollingJob; if (pollingJob != null) { pollingJob.cancel(true); this.pollingJob = null; } } /** * Update the state of a channel * * @param channel the channel */ private void updateChannelState(MonopriceAudioZone zone, String channelType, MonopriceAudioZoneDTO zoneData) { String channel = zone.name().toLowerCase() + CHANNEL_DELIMIT + channelType; if (!isLinked(channel)) { return; } State state = UnDefType.UNDEF; switch (channelType) { case CHANNEL_TYPE_POWER: state = zoneData.isPowerOn() ? OnOffType.ON : OnOffType.OFF; break; case CHANNEL_TYPE_SOURCE: state = new DecimalType(zoneData.getSource()); break; case CHANNEL_TYPE_VOLUME: long volumePct = Math.round( (double) (zoneData.getVolume() - MIN_VOLUME) / (double) (MAX_VOLUME - MIN_VOLUME) * 100.0); state = new PercentType(BigDecimal.valueOf(volumePct)); break; case CHANNEL_TYPE_MUTE: state = zoneData.isMuted() ? OnOffType.ON : OnOffType.OFF; break; case CHANNEL_TYPE_TREBLE: state = new DecimalType(BigDecimal.valueOf(zoneData.getTreble() - TONE_OFFSET)); break; case CHANNEL_TYPE_BASS: state = new DecimalType(BigDecimal.valueOf(zoneData.getBass() - TONE_OFFSET)); break; case CHANNEL_TYPE_BALANCE: state = new DecimalType(BigDecimal.valueOf(zoneData.getBalance() - BALANCE_OFFSET)); break; case CHANNEL_TYPE_DND: state = zoneData.isDndOn() ? OnOffType.ON : OnOffType.OFF; break; case CHANNEL_TYPE_PAGE: state = zoneData.isPageActive() ? OpenClosedType.OPEN : OpenClosedType.CLOSED; break; case CHANNEL_TYPE_KEYPAD: state = zoneData.isKeypadActive() ? OpenClosedType.OPEN : OpenClosedType.CLOSED; break; default: break; } updateState(channel, state); } private void processZoneUpdate(MonopriceAudioZone zone, MonopriceAudioZoneDTO zoneData, String newZoneData) { // only process the update if something actually changed in this zone since the last time through if (!newZoneData.equals(zoneData.toString())) { // example status string: 1200010000130809100601, matcher pattern from above: // "^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})" Matcher matcher = PATTERN.matcher(newZoneData); if (matcher.find()) { zoneData.setZone(matcher.group(1)); if (!matcher.group(2).equals(zoneData.getPage())) { zoneData.setPage(matcher.group(2)); updateChannelState(zone, CHANNEL_TYPE_PAGE, zoneData); } if (!matcher.group(3).equals(zoneData.getPower())) { zoneData.setPower(matcher.group(3)); updateChannelState(zone, CHANNEL_TYPE_POWER, zoneData); } if (!matcher.group(4).equals(zoneData.getMute())) { zoneData.setMute(matcher.group(4)); updateChannelState(zone, CHANNEL_TYPE_MUTE, zoneData); } if (!matcher.group(5).equals(zoneData.getDnd())) { zoneData.setDnd(matcher.group(5)); updateChannelState(zone, CHANNEL_TYPE_DND, zoneData); } int volume = Integer.parseInt(matcher.group(6)); if (volume != zoneData.getVolume()) { zoneData.setVolume(volume); updateChannelState(zone, CHANNEL_TYPE_VOLUME, zoneData); } int treble = Integer.parseInt(matcher.group(7)); if (treble != zoneData.getTreble()) { zoneData.setTreble(treble); updateChannelState(zone, CHANNEL_TYPE_TREBLE, zoneData); } int bass = Integer.parseInt(matcher.group(8)); if (bass != zoneData.getBass()) { zoneData.setBass(bass); updateChannelState(zone, CHANNEL_TYPE_BASS, zoneData); } int balance = Integer.parseInt(matcher.group(9)); if (balance != zoneData.getBalance()) { zoneData.setBalance(balance); updateChannelState(zone, CHANNEL_TYPE_BALANCE, zoneData); } if (!matcher.group(10).equals(zoneData.getSource())) { zoneData.setSource(matcher.group(10)); updateChannelState(zone, CHANNEL_TYPE_SOURCE, zoneData); } if (!matcher.group(11).equals(zoneData.getKeypad())) { zoneData.setKeypad(matcher.group(11)); updateChannelState(zone, CHANNEL_TYPE_KEYPAD, zoneData); } } else { logger.debug("Invalid zone update message: {}", newZoneData); } } lastPollingUpdate = System.currentTimeMillis(); } }
paulianttila/openhab2
bundles/org.openhab.binding.monopriceaudio/src/main/java/org/openhab/binding/monopriceaudio/internal/handler/MonopriceAudioHandler.java
Java
epl-1.0
33,500
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.zwave.internal.converter; import java.util.Map; import org.openhab.binding.zwave.internal.converter.command.MultiLevelIncreaseDecreaseCommandConverter; import org.openhab.binding.zwave.internal.converter.command.MultiLevelOnOffCommandConverter; import org.openhab.binding.zwave.internal.converter.command.MultiLevelPercentCommandConverter; import org.openhab.binding.zwave.internal.converter.command.ZWaveCommandConverter; import org.openhab.binding.zwave.internal.converter.state.BigDecimalDecimalTypeConverter; import org.openhab.binding.zwave.internal.converter.state.IntegerDecimalTypeConverter; import org.openhab.binding.zwave.internal.converter.state.IntegerOnOffTypeConverter; import org.openhab.binding.zwave.internal.converter.state.IntegerOpenClosedTypeConverter; import org.openhab.binding.zwave.internal.converter.state.IntegerPercentTypeConverter; import org.openhab.binding.zwave.internal.converter.state.ZWaveStateConverter; import org.openhab.binding.zwave.internal.protocol.SerialMessage; import org.openhab.binding.zwave.internal.protocol.ZWaveController; import org.openhab.binding.zwave.internal.protocol.ZWaveNode; import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveBasicCommandClass; import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent; import org.openhab.core.events.EventPublisher; import org.openhab.core.items.Item; import org.openhab.core.types.Command; import org.openhab.core.types.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /*** * ZWaveBasicConverter class. Converter for communication with the * {@link ZWaveBasicCommandClass}. Supports control of most devices * through the BASIC command class. Note that some devices report their * status as BASIC Report messages as well. We try to handle these devices * as best as possible. * * @author Jan-Willem Spuij * @since 1.4.0 */ public class ZWaveBasicConverter extends ZWaveCommandClassConverter<ZWaveBasicCommandClass> { private static final Logger logger = LoggerFactory.getLogger(ZWaveBasicConverter.class); private static final int REFRESH_INTERVAL = 0; // refresh interval in seconds for the binary switch; /** * Constructor. Creates a new instance of the {@link ZWaveBasicConverter} class. * * @param controller the {@link ZWaveController} to use for sending messages. * @param eventPublisher the {@link EventPublisher} to use to publish events. */ public ZWaveBasicConverter(ZWaveController controller, EventPublisher eventPublisher) { super(controller, eventPublisher); // State and commmand converters used by this converter. this.addStateConverter(new IntegerDecimalTypeConverter()); this.addStateConverter(new IntegerPercentTypeConverter()); this.addStateConverter(new IntegerOnOffTypeConverter()); this.addStateConverter(new IntegerOpenClosedTypeConverter()); this.addStateConverter(new BigDecimalDecimalTypeConverter()); this.addCommandConverter(new MultiLevelOnOffCommandConverter()); this.addCommandConverter(new MultiLevelPercentCommandConverter()); this.addCommandConverter(new MultiLevelIncreaseDecreaseCommandConverter()); } /** * {@inheritDoc} */ @Override public SerialMessage executeRefresh(ZWaveNode node, ZWaveBasicCommandClass commandClass, int endpointId, Map<String, String> arguments) { logger.debug("NODE {}: Generating poll message for {}, endpoint {}", node.getNodeId(), commandClass.getCommandClass().getLabel(), endpointId); return node.encapsulate(commandClass.getValueMessage(), commandClass, endpointId); } /** * {@inheritDoc} */ @Override public void handleEvent(ZWaveCommandClassValueEvent event, Item item, Map<String, String> arguments) { ZWaveStateConverter<?, ?> converter = this.getStateConverter(item, event.getValue()); if (converter == null) { logger.warn("No converter found for item = {}, node = {} endpoint = {}, ignoring event.", item.getName(), event.getNodeId(), event.getEndpoint()); return; } State state = converter.convertFromValueToState(event.getValue()); this.getEventPublisher().postUpdate(item.getName(), state); } /** * {@inheritDoc} */ @Override public void receiveCommand(Item item, Command command, ZWaveNode node, ZWaveBasicCommandClass commandClass, int endpointId, Map<String, String> arguments) { ZWaveCommandConverter<?, ?> converter = this.getCommandConverter(command.getClass()); if (converter == null) { logger.warn("No converter found for item = {}, node = {} endpoint = {}, ignoring command.", item.getName(), node.getNodeId(), endpointId); return; } SerialMessage serialMessage = node.encapsulate( commandClass.setValueMessage((Integer) converter.convertFromCommandToValue(item, command)), commandClass, endpointId); if (serialMessage == null) { logger.warn("Generating message failed for command class = {}, node = {}, endpoint = {}", commandClass.getCommandClass().getLabel(), node.getNodeId(), endpointId); return; } this.getController().sendData(serialMessage); if (command instanceof State) { this.getEventPublisher().postUpdate(item.getName(), (State) command); } } /** * {@inheritDoc} */ @Override int getRefreshInterval() { return REFRESH_INTERVAL; } }
openhab/openhab
bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/converter/ZWaveBasicConverter.java
Java
epl-1.0
6,106
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.WeakHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.StringUtils; /** * <p>Abstract superclass for type-safe enums.</p> * * <p>One feature of the C programming language lacking in Java is enumerations. The * C implementation based on ints was poor and open to abuse. The original Java * recommendation and most of the JDK also uses int constants. It has been recognised * however that a more robust type-safe class-based solution can be designed. This * class follows the basic Java type-safe enumeration pattern.</p> * * <p><em>NOTE:</em>Due to the way in which Java ClassLoaders work, comparing * Enum objects should always be done using <code>equals()</code>, not <code>==</code>. * The equals() method will try == first so in most cases the effect is the same.</p> * * <p>Of course, if you actually want (or don't mind) Enums in different class * loaders being non-equal, then you can use <code>==</code>.</p> * * <h4>Simple Enums</h4> * * <p>To use this class, it must be subclassed. For example:</p> * * <pre> * public final class ColorEnum extends Enum { * public static final ColorEnum RED = new ColorEnum("Red"); * public static final ColorEnum GREEN = new ColorEnum("Green"); * public static final ColorEnum BLUE = new ColorEnum("Blue"); * * private ColorEnum(String color) { * super(color); * } * * public static ColorEnum getEnum(String color) { * return (ColorEnum) getEnum(ColorEnum.class, color); * } * * public static Map getEnumMap() { * return getEnumMap(ColorEnum.class); * } * * public static List getEnumList() { * return getEnumList(ColorEnum.class); * } * * public static Iterator iterator() { * return iterator(ColorEnum.class); * } * } * </pre> * * <p>As shown, each enum has a name. This can be accessed using <code>getName</code>.</p> * * <p>The <code>getEnum</code> and <code>iterator</code> methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class.</p> * * <h4>Subclassed Enums</h4> * <p>A hierarchy of Enum classes can be built. In this case, the superclass is * unaffected by the addition of subclasses (as per normal Java). The subclasses * may add additional Enum constants <em>of the type of the superclass</em>. The * query methods on the subclass will return all of the Enum constants from the * superclass and subclass.</p> * * <pre> * public final class ExtraColorEnum extends ColorEnum { * // NOTE: Color enum declared above is final, change that to get this * // example to compile. * public static final ColorEnum YELLOW = new ExtraColorEnum("Yellow"); * * private ExtraColorEnum(String color) { * super(color); * } * * public static ColorEnum getEnum(String color) { * return (ColorEnum) getEnum(ExtraColorEnum.class, color); * } * * public static Map getEnumMap() { * return getEnumMap(ExtraColorEnum.class); * } * * public static List getEnumList() { * return getEnumList(ExtraColorEnum.class); * } * * public static Iterator iterator() { * return iterator(ExtraColorEnum.class); * } * } * </pre> * * <p>This example will return RED, GREEN, BLUE, YELLOW from the List and iterator * methods in that order. The RED, GREEN and BLUE instances will be the same (==) * as those from the superclass ColorEnum. Note that YELLOW is declared as a * ColorEnum and not an ExtraColorEnum.</p> * * <h4>Functional Enums</h4> * * <p>The enums can have functionality by defining subclasses and * overriding the <code>getEnumClass()</code> method:</p> * * <pre> * public static final OperationEnum PLUS = new PlusOperation(); * private static final class PlusOperation extends OperationEnum { * private PlusOperation() { * super("Plus"); * } * public int eval(int a, int b) { * return a + b; * } * } * public static final OperationEnum MINUS = new MinusOperation(); * private static final class MinusOperation extends OperationEnum { * private MinusOperation() { * super("Minus"); * } * public int eval(int a, int b) { * return a - b; * } * } * * private OperationEnum(String color) { * super(color); * } * * public final Class getEnumClass() { // NOTE: new method! * return OperationEnum.class; * } * * public abstract double eval(double a, double b); * * public static OperationEnum getEnum(String name) { * return (OperationEnum) getEnum(OperationEnum.class, name); * } * * public static Map getEnumMap() { * return getEnumMap(OperationEnum.class); * } * * public static List getEnumList() { * return getEnumList(OperationEnum.class); * } * * public static Iterator iterator() { * return iterator(OperationEnum.class); * } * } * </pre> * <p>The code above will work on JDK 1.2. If JDK1.3 and later is used, * the subclasses may be defined as anonymous.</p> * * <h4>Nested class Enums</h4> * * <p>Care must be taken with class loading when defining a static nested class * for enums. The static nested class can be loaded without the surrounding outer * class being loaded. This can result in an empty list/map/iterator being returned. * One solution is to define a static block that references the outer class where * the constants are defined. For example:</p> * * <pre> * public final class Outer { * public static final BWEnum BLACK = new BWEnum("Black"); * public static final BWEnum WHITE = new BWEnum("White"); * * // static nested enum class * public static final class BWEnum extends Enum { * * static { * // explicitly reference BWEnum class to force constants to load * Object obj = Outer.BLACK; * } * * // ... other methods omitted * } * } * </pre> * * <p>Although the above solves the problem, it is not recommended. The best solution * is to define the constants in the enum class, and hold references in the outer class: * * <pre> * public final class Outer { * public static final BWEnum BLACK = BWEnum.BLACK; * public static final BWEnum WHITE = BWEnum.WHITE; * * // static nested enum class * public static final class BWEnum extends Enum { * // only define constants in enum classes - private if desired * private static final BWEnum BLACK = new BWEnum("Black"); * private static final BWEnum WHITE = new BWEnum("White"); * * // ... other methods omitted * } * } * </pre> * * <p>For more details, see the 'Nested' test cases. * * @deprecated Replaced by {@link org.apache.commons.lang.enums.Enum org.apache.commons.lang.enums.Enum} * and will be removed in version 3.0. All classes in this package are deprecated and repackaged to * {@link org.apache.commons.lang.enums} since <code>enum</code> is a Java 1.5 keyword. * @see org.apache.commons.lang.enums.Enum * @author Apache Avalon project * @author Stephen Colebourne * @author Chris Webb * @author Mike Bowler * @since 1.0 * @version $Id: Enum.java 447975 2006-09-19 21:20:56Z bayard $ */ public abstract class Enum implements Comparable, Serializable { /** * Required for serialization support. Lang version 1.0.1 serial compatibility. * * @see java.io.Serializable */ private static final long serialVersionUID = -487045951170455942L; // After discussion, the default size for HashMaps is used, as the // sizing algorithm changes across the JDK versions /** * An empty <code>Map</code>, as JDK1.2 didn't have an empty map. */ private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap(0)); /** * <code>Map</code>, key of class name, value of <code>Entry</code>. */ private static final Map cEnumClasses = new WeakHashMap(); /** * The string representation of the Enum. */ private final String iName; /** * The hashcode representation of the Enum. */ private transient final int iHashCode; /** * The toString representation of the Enum. * @since 2.0 */ protected transient String iToString = null; /** * <p>Enable the iterator to retain the source code order.</p> */ private static class Entry { /** * Map of Enum name to Enum. */ final Map map = new HashMap(); /** * Map of Enum name to Enum. */ final Map unmodifiableMap = Collections.unmodifiableMap(map); /** * List of Enums in source code order. */ final List list = new ArrayList(25); /** * Map of Enum name to Enum. */ final List unmodifiableList = Collections.unmodifiableList(list); /** * <p>Restrictive constructor.</p> */ protected Entry() { super(); } } /** * <p>Constructor to add a new named item to the enumeration.</p> * * @param name the name of the enum object, * must not be empty or <code>null</code> * @throws IllegalArgumentException if the name is <code>null</code> * or an empty string * @throws IllegalArgumentException if the getEnumClass() method returns * a null or invalid Class */ protected Enum(String name) { super(); init(name); iName = name; iHashCode = 7 + getEnumClass().hashCode() + 3 * name.hashCode(); // cannot create toString here as subclasses may want to include other data } /** * Initializes the enumeration. * * @param name the enum name * @throws IllegalArgumentException if the name is null or empty or duplicate * @throws IllegalArgumentException if the enumClass is null or invalid */ private void init(String name) { if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("The Enum name must not be empty or null"); } Class enumClass = getEnumClass(); if (enumClass == null) { throw new IllegalArgumentException("getEnumClass() must not be null"); } Class cls = getClass(); boolean ok = false; while (cls != null && cls != Enum.class && cls != ValuedEnum.class) { if (cls == enumClass) { ok = true; break; } cls = cls.getSuperclass(); } if (ok == false) { throw new IllegalArgumentException("getEnumClass() must return a superclass of this class"); } // create entry Entry entry = (Entry) cEnumClasses.get(enumClass); if (entry == null) { entry = createEntry(enumClass); cEnumClasses.put(enumClass, entry); } if (entry.map.containsKey(name)) { throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added"); } entry.map.put(name, this); entry.list.add(this); } /** * <p>Handle the deserialization of the class to ensure that multiple * copies are not wastefully created, or illegal enum types created.</p> * * @return the resolved object */ protected Object readResolve() { Entry entry = (Entry) cEnumClasses.get(getEnumClass()); if (entry == null) { return null; } return entry.map.get(getName()); } //-------------------------------------------------------------------------------- /** * <p>Gets an <code>Enum</code> object by class and name.</p> * * @param enumClass the class of the Enum to get, must not * be <code>null</code> * @param name the name of the <code>Enum</code> to get, * may be <code>null</code> * @return the enum object, or <code>null</code> if the enum does not exist * @throws IllegalArgumentException if the enum class * is <code>null</code> */ protected static Enum getEnum(Class enumClass, String name) { Entry entry = getEntry(enumClass); if (entry == null) { return null; } return (Enum) entry.map.get(name); } /** * <p>Gets the <code>Map</code> of <code>Enum</code> objects by * name using the <code>Enum</code> class.</p> * * <p>If the requested class has no enum objects an empty * <code>Map</code> is returned.</p> * * @param enumClass the class of the <code>Enum</code> to get, * must not be <code>null</code> * @return the enum object Map * @throws IllegalArgumentException if the enum class is <code>null</code> * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static Map getEnumMap(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return EMPTY_MAP; } return entry.unmodifiableMap; } /** * <p>Gets the <code>List</code> of <code>Enum</code> objects using the * <code>Enum</code> class.</p> * * <p>The list is in the order that the objects were created (source code order). * If the requested class has no enum objects an empty <code>List</code> is * returned.</p> * * @param enumClass the class of the <code>Enum</code> to get, * must not be <code>null</code> * @return the enum object Map * @throws IllegalArgumentException if the enum class is <code>null</code> * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static List getEnumList(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return Collections.EMPTY_LIST; } return entry.unmodifiableList; } /** * <p>Gets an <code>Iterator</code> over the <code>Enum</code> objects in * an <code>Enum</code> class.</p> * * <p>The <code>Iterator</code> is in the order that the objects were * created (source code order). If the requested class has no enum * objects an empty <code>Iterator</code> is returned.</p> * * @param enumClass the class of the <code>Enum</code> to get, * must not be <code>null</code> * @return an iterator of the Enum objects * @throws IllegalArgumentException if the enum class is <code>null</code> * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } //----------------------------------------------------------------------- /** * <p>Gets an <code>Entry</code> from the map of Enums.</p> * * @param enumClass the class of the <code>Enum</code> to get * @return the enum entry */ private static Entry getEntry(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass); return entry; } /** * <p>Creates an <code>Entry</code> for storing the Enums.</p> * * <p>This accounts for subclassed Enums.</p> * * @param enumClass the class of the <code>Enum</code> to get * @return the enum entry */ private static Entry createEntry(Class enumClass) { Entry entry = new Entry(); Class cls = enumClass.getSuperclass(); while (cls != null && cls != Enum.class && cls != ValuedEnum.class) { Entry loopEntry = (Entry) cEnumClasses.get(cls); if (loopEntry != null) { entry.list.addAll(loopEntry.list); entry.map.putAll(loopEntry.map); break; // stop here, as this will already have had superclasses added } cls = cls.getSuperclass(); } return entry; } //----------------------------------------------------------------------- /** * <p>Retrieve the name of this Enum item, set in the constructor.</p> * * @return the <code>String</code> name of this Enum item */ public final String getName() { return iName; } /** * <p>Retrieves the Class of this Enum item, set in the constructor.</p> * * <p>This is normally the same as <code>getClass()</code>, but for * advanced Enums may be different. If overridden, it must return a * constant value.</p> * * @return the <code>Class</code> of the enum * @since 2.0 */ public Class getEnumClass() { return getClass(); } /** * <p>Tests for equality.</p> * * <p>Two Enum objects are considered equal * if they have the same class names and the same names. * Identity is tested for first, so this method usually runs fast.</p> * * <p>If the parameter is in a different class loader than this instance, * reflection is used to compare the names.</p> * * @param other the other object to compare for equality * @return <code>true</code> if the Enums are equal */ public final boolean equals(Object other) { if (other == this) { return true; } else if (other == null) { return false; } else if (other.getClass() == this.getClass()) { // Ok to do a class cast to Enum here since the test above // guarantee both // classes are in the same class loader. return iName.equals(((Enum) other).iName); } else { // This and other are in different class loaders, we must use reflection. if (other.getClass().getName().equals(this.getClass().getName()) == false) { return false; } return iName.equals( getNameInOtherClassLoader(other) ); } } /** * <p>Returns a suitable hashCode for the enumeration.</p> * * @return a hashcode based on the name */ public final int hashCode() { return iHashCode; } /** * <p>Tests for order.</p> * * <p>The default ordering is alphabetic by name, but this * can be overridden by subclasses.</p> * * <p>If the parameter is in a different class loader than this instance, * reflection is used to compare the names.</p> * * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater * than, <code>0</code> of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is <code>null</code> */ public int compareTo(Object other) { if (other == this) { return 0; } if (other.getClass() != this.getClass()) { if (other.getClass().getName().equals(this.getClass().getName())) { return iName.compareTo( getNameInOtherClassLoader(other) ); } } return iName.compareTo(((Enum) other).iName); } /** * <p>Use reflection to return an objects class name.</p> * * @param other The object to determine the class name for * @return The class name */ private String getNameInOtherClassLoader(Object other) { try { Method mth = other.getClass().getMethod("getName", null); String name = (String) mth.invoke(other, null); return name; } catch (NoSuchMethodException e) { // ignore - should never happen } catch (IllegalAccessException e) { // ignore - should never happen } catch (InvocationTargetException e) { // ignore - should never happen } throw new IllegalStateException("This should not happen"); } /** * <p>Human readable description of this Enum item.</p> * * @return String in the form <code>type[name]</code>, for example: * <code>Color[Red]</code>. Note that the package name is stripped from * the type name. */ public String toString() { if (iToString == null) { String shortName = ClassUtils.getShortClassName(getEnumClass()); iToString = shortName + "[" + getName() + "]"; } return iToString; } }
TheTypoMaster/dukecon_appsgenerator
org.apache.commons.lang/source-bundle/org/apache/commons/lang/enum/Enum.java
Java
epl-1.0
22,003