repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
selvasingh/azure-sdk-for-java
sdk/appservice/mgmt-v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/FunctionSecretsInner.java
1649
/** * 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.appservice.v2018_02_01.implementation; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.management.appservice.v2018_02_01.ProxyOnlyResource; /** * Function secrets. */ @JsonFlatten public class FunctionSecretsInner extends ProxyOnlyResource { /** * Secret key. */ @JsonProperty(value = "properties.key") private String key; /** * Trigger URL. */ @JsonProperty(value = "properties.trigger_url") private String triggerUrl; /** * Get secret key. * * @return the key value */ public String key() { return this.key; } /** * Set secret key. * * @param key the key value to set * @return the FunctionSecretsInner object itself. */ public FunctionSecretsInner withKey(String key) { this.key = key; return this; } /** * Get trigger URL. * * @return the triggerUrl value */ public String triggerUrl() { return this.triggerUrl; } /** * Set trigger URL. * * @param triggerUrl the triggerUrl value to set * @return the FunctionSecretsInner object itself. */ public FunctionSecretsInner withTriggerUrl(String triggerUrl) { this.triggerUrl = triggerUrl; return this; } }
mit
jonathan-major/Rapture
Libs/RaptureAPI/src/main/java/rapture/dsl/idef/DocLocator.java
3581
/** * The MIT License (MIT) * * Copyright (c) 2011-2016 Incapture Technologies LLC * * 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 rapture.dsl.idef; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import rapture.common.model.DocumentMetadata; public class DocLocator extends FieldLocator { private List<String> fields = new ArrayList<String>(); public void addField(String field) { fields.add(field); } @Override public String toString() { StringBuffer ret = new StringBuffer(); for (String f : fields) { ret.append(f); ret.append("."); } return ret.toString(); } @SuppressWarnings("unchecked") @Override public Object value(String key, Map<String, Object> mappedContent, DocumentMetadata meta) { Map<String, Object> current = mappedContent; Object val = null; boolean allInList = false; for (String field : fields) { if (allInList) { // everything in list assumes the next field is the end and // doesn't go deeper List<Object> vals = new ArrayList<Object>(); for (int i = 0; i < current.size(); i++) { Map<String, Object> listObj = (Map<String, Object>) current.get(String.valueOf(i)); vals.add(listObj.get(field)); } return vals; } if (field.equals("*")) { // star field means they want everything in a list, so skip to // next field allInList = true; continue; } val = current.get(field); if (val instanceof Map<?, ?>) { current = (Map<String, Object>) val; } else if (val instanceof List<?>) { current = listToMap((List<?>) val); } } return val; } /** * Support for lists, so we create a map where they key is the index of the * object in the list, and the value is the object itself * * @param l * - the list to convert * @return - a map with key being list index and value being object */ private Map<String, Object> listToMap(List<?> l) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < l.size(); i++) { map.put(String.valueOf(i), l.get(i)); } return map; } }
mit
Iroxsmyth/Brisca-AI-2017
src/main/java/aima/core/logic/fol/SubsumptionElimination.java
2901
package aima.core.logic.fol; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import aima.core.logic.fol.kb.data.Clause; /** * Artificial Intelligence A Modern Approach (3rd Edition): page 356.<br> * <br> * The subsumption method eliminates all sentences that are subsumed by (that * is, more specific than) an existing sentence in the KB. For example, P(x) is * in the KB, then there is no sense in adding P(A) and even less sense in * adding P(A) V Q(B). Subsumption helps keep the KB small and thus helps keep * the search space small.<br> * <br> * <b>Note:</b> <a * href="http://logic.stanford.edu/classes/cs157/2008/lectures/lecture12.pdf" * >From slide 17.</a> <br> * <br> * Relational Subsumption<br> * <br> * A relational clause &Phi; subsumes &Psi; if and only if there is a * substitution &delta; that, when applied to &Phi;, produces a clause &Phi;' * that is a subset of &Psi;. * * @author Ciaran O'Reilly * @author Mike Stampone */ public class SubsumptionElimination { /** * Returns the clauses that are subsumed by (that is, more specific than) an * existing clause in the specified set of clauses. * * @param clauses * a set of clauses in first order logic * * @return the clauses that are subsumed by (that is, more specific than) an * existing clause in the specified set of clauses. */ public static Set<Clause> findSubsumedClauses(Set<Clause> clauses) { Set<Clause> subsumed = new HashSet<Clause>(); // Group the clauses by their # of literals. // Keep track of the min and max # of literals. int min = Integer.MAX_VALUE; int max = 0; Map<Integer, Set<Clause>> clausesGroupedBySize = new HashMap<Integer, Set<Clause>>(); for (Clause c : clauses) { int size = c.getNumberLiterals(); if (size < min) { min = size; } if (size > max) { max = size; } Set<Clause> cforsize = clausesGroupedBySize.get(size); if (null == cforsize) { cforsize = new HashSet<Clause>(); clausesGroupedBySize.put(size, cforsize); } cforsize.add(c); } // Check if each smaller clause // subsumes any of the larger clauses. for (int i = min; i < max; i++) { Set<Clause> scs = clausesGroupedBySize.get(i); // Ensure there are clauses with this # of literals if (null != scs) { for (int j = i + 1; j <= max; j++) { Set<Clause> lcs = clausesGroupedBySize.get(j); // Ensure there are clauses with this # of literals if (null != lcs) { for (Clause sc : scs) { // Don't bother checking clauses // that are already subsumed. if (!subsumed.contains(sc)) { for (Clause lc : lcs) { if (!subsumed.contains(lc)) { if (sc.subsumes(lc)) { subsumed.add(lc); } } } } } } } } } return subsumed; } }
mit
jeremiemarc/zucchini-ui
zucchini-ui-backend/src/main/java/io/zucchiniui/backend/reportconverter/domain/ReportConverterService.java
336
package io.zucchiniui.backend.reportconverter.domain; import java.io.InputStream; import java.util.Optional; public interface ReportConverterService { void convertAndSaveFeatures(String testRunId, InputStream featureStream, Optional<String> group, boolean dryRun, boolean onlyNewScenarii, boolean mergeOnlyNewPassedScenarii); }
mit
saysotheara/Vitamio-Cordova-Plugin
src/android/ImageLoadTaskListener.java
224
package com.hutchind.cordova.plugins.vitamio; import android.graphics.Bitmap; /** * Created by nchutchind on 10/10/2014. */ public interface ImageLoadTaskListener { public void imageLoaded(String key, Bitmap bmp); }
mit
ryokato/ENdoSnipe
Javelin/src/test/java/jp/co/acroquest/endosnipe/javelin/testutil/PrivateAccessor.java
11168
/******************************************************************************* * ENdoSnipe 5.0 - (https://github.com/endosnipe) * * The MIT License (MIT) * * Copyright (c) 2012 Acroquest Technology Co.,Ltd. * * 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 jp.co.acroquest.endosnipe.javelin.testutil; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class PrivateAccessor { private PrivateAccessor() { } /** * Returns the value of the field on the specified object. The name * parameter is a <code>String</code> specifying the simple name of the * desired field.<p> * * The object is first searched for any matching field. If no matching * field is found, the superclasses are recursively searched. * * @exception NoSuchFieldException if a field with the specified name is * not found. */ public static Object getField(final Object object, final String name) throws NoSuchFieldException { if (object == null) { throw new IllegalArgumentException("Invalid null object argument"); } for (Class cls = object.getClass(); cls != null; cls = cls.getSuperclass()) { try { Field field = cls.getDeclaredField(name); field.setAccessible(true); return field.get(object); } catch (Exception ex) { /* in case of an exception, we will throw a new * NoSuchFieldException object */ ; } } throw new NoSuchFieldException("Could get value for field " + object.getClass().getName() + "." + name); } /** * Returns the value of the field on the specified class. The name * parameter is a <code>String</code> specifying the simple name of the * desired field.<p> * * The class is first searched for any matching field. If no matching * field is found, the superclasses are recursively searched. * * @exception NoSuchFieldException if a field with the specified name is * not found. */ public static Object getField(final Class cls, final String name) throws NoSuchFieldException { if (cls == null) { throw new IllegalArgumentException("Invalid null cls argument"); } Class base = cls; while (base != null) { try { Field field = base.getDeclaredField(name); field.setAccessible(true); return field.get(base); } catch (Exception ex) { /* in case of an exception, we will throw a new * NoSuchFieldException object */ ; } base = base.getSuperclass(); } throw new NoSuchFieldException("Could not get value for static field " + cls.getName() + "." + name); } /** * Sets the field represented by the name value on the specified object * argument to the specified new value. The new value is automatically * unwrapped if the underlying field has a primitive type.<p> * * The object is first searched for any matching field. If no matching * field is found, the superclasses are recursively searched. * * @exception NoSuchFieldException if a field with the specified name is * not found. */ public static void setField(final Object object, final String name, final Object value) throws NoSuchFieldException { if (object == null) { throw new IllegalArgumentException("Invalid null object argument"); } for (Class cls = object.getClass(); cls != null; cls = cls.getSuperclass()) { try { Field field = cls.getDeclaredField(name); field.setAccessible(true); field.set(object, value); return; } catch (Exception ex) { /* in case of an exception, we will throw a new * NoSuchFieldException object */ ; } } throw new NoSuchFieldException("Could set value for field " + object.getClass().getName() + "." + name); } /** * Sets the field represented by the name value on the specified class * argument to the specified new value. The new value is automatically * unwrapped if the underlying field has a primitive type.<p> * * The class is first searched for any matching field. If no matching * field is found, the superclasses are recursively searched. * * @exception NoSuchFieldException if a field with the specified name is * not found. */ public static void setField(final Class cls, final String name, final Object value) throws NoSuchFieldException { if (cls == null) { throw new IllegalArgumentException("Invalid null cls argument"); } Class base = cls; while (base != null) { try { Field field = base.getDeclaredField(name); field.setAccessible(true); field.set(base, value); return; } catch (Exception ex) { /* in case of an exception, we will throw a new * NoSuchFieldException object */ ; } base = base.getSuperclass(); } throw new NoSuchFieldException("Could set value for static field " + cls.getName() + "." + name); } /** * Invokes the method represented by the name value on the specified object * with the specified parameters. Individual parameters are automatically * unwrapped to match primitive formal parameters, and both primitive and * reference parameters are subject to widening conversions as necessary. * The value returned by the method is automatically wrapped in an object * if it has a primitive type.<p> * * The object is first searched for any matching method. If no matching * method is found, the superclasses are recursively searched. * * @exception NoSuchMethodException if a matching method is not found or * if the name is "<init>"or "<clinit>". */ public static Object invoke(final Object object, final String name, final Class parameterTypes[], final Object args[]) throws Throwable { if (object == null) { throw new IllegalArgumentException("Invalid null object argument"); } Class cls = object.getClass(); while (cls != null) { try { Method method = cls.getDeclaredMethod(name, parameterTypes); method.setAccessible(true); return method.invoke(object, args); } catch (InvocationTargetException e) { /* if the method throws an exception, it is embedded into an * InvocationTargetException. */ throw e.getTargetException(); } catch (Exception ex) { /* in case of an exception, we will throw a new * NoSuchFieldException object */ ; } cls = cls.getSuperclass(); } throw new NoSuchMethodException("Failed method invocation: " + object.getClass().getName() + "." + name + "()"); } /** * Invokes the method represented by the name value on the specified class * with the specified parameters. Individual parameters are automatically * unwrapped to match primitive formal parameters, and both primitive and * reference parameters are subject to widening conversions as necessary. * The value returned by the method is automatically wrapped in an object * if it has a primitive type.<p> * * The class is first searched for any matching method. If no matching * class is found, the superclasses are recursively searched. * * @exception NoSuchMethodException if a matching method is not found or * if the name is "<init>"or "<clinit>". */ public static Object invoke(final Class cls, final String name, final Class parameterTypes[], final Object args[]) throws Exception { if (cls == null) { throw new IllegalArgumentException("Invalid null cls argument"); } Class base = cls; while (base != null) { try { Method method = base.getDeclaredMethod(name, parameterTypes); method.setAccessible(true); return method.invoke(base, args); } catch (InvocationTargetException e) { /* if the method throws an exception, it is embedded into an * InvocationTargetException. */ throw (Exception)e.getTargetException(); } catch (Exception ex) { /* in case of an exception, we will throw a new * NoSuchFieldException object */ ; } base = base.getSuperclass(); } throw new NoSuchMethodException("Failed static method invocation: " + cls.getName() + "." + name + "()"); } }
mit
andreasb242/settlers-remake
jsettlers.testutils/src/main/java/jsettlers/algorithms/path/astar/DummyEmptyAStarMap.java
2239
/******************************************************************************* * Copyright (c) 2015 * * 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 jsettlers.algorithms.path.astar; import jsettlers.algorithms.path.IPathCalculatable; import jsettlers.algorithms.path.astar.IAStarPathMap; import jsettlers.common.Color; /** * Dummy map for testing purposes of AStar. * * @author Andreas Eberle * */ public class DummyEmptyAStarMap implements IAStarPathMap { private final boolean[][] blocked; public DummyEmptyAStarMap(short width, short height) { this.blocked = new boolean[width][height]; } @Override public boolean isBlocked(IPathCalculatable requester, int x, int y) { return blocked[x][y]; } @Override public float getCost(int sx, int sy, int tx, int ty) { return 1; } @Override public void markAsOpen(int x, int y) { } @Override public void markAsClosed(int x, int y) { } public void setBlocked(int x, int y, boolean b) { blocked[x][y] = b; } @Override public void setDebugColor(int x, int y, Color color) { } @Override public short getBlockedPartition(int x, int y) { return 1; } }
mit
zbsz/robolectric
robolectric-shadows/shadows-maps/src/test/java/org/robolectric/shadows/ShadowGeocoderTest.java
2261
package org.robolectric.shadows; import android.app.Activity; import android.location.Address; import android.location.Geocoder; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.internal.ShadowExtractor; import org.robolectric.util.TestRunnerWithManifest; import java.util.List; import static junit.framework.Assert.assertFalse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(TestRunnerWithManifest.class) public class ShadowGeocoderTest { private Geocoder geocoder; @Before public void setUp() throws Exception { geocoder = new Geocoder(new Activity()); } @Test public void shouldRecordLastLocationName() throws Exception { geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1); String lastLocationName = shadowOf(geocoder).getLastLocationName(); assertEquals("731 Market St, San Francisco, CA 94103", lastLocationName); } @Test public void setsUpHasLocationInAddressFromLocationName() throws Exception { shadowOf(geocoder).setSimulatedHasLatLong(true, true); Address address = geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1).get(0); assertTrue(address.hasLatitude()); assertTrue(address.hasLongitude()); shadowOf(geocoder).setSimulatedHasLatLong(false, false); address = geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1).get(0); assertFalse(address.hasLatitude()); assertFalse(address.hasLongitude()); } @Test public void canReturnNoAddressesOnRequest() throws Exception { shadowOf(geocoder).setReturnNoResults(true); List<Address> result = geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1); assertEquals(0, result.size()); } @Test public void answersWhetherResolutionHappened() throws Exception { assertFalse(shadowOf(geocoder).didResolution()); shadowOf(geocoder).setReturnNoResults(true); geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1); assertTrue(shadowOf(geocoder).didResolution()); } private ShadowGeocoder shadowOf(Geocoder geocoder) { return (ShadowGeocoder) ShadowExtractor.extract(geocoder); } }
mit
mercadolibre/HoloEverywhere
demo/src/org/holoeverywhere/demo/fragments/dialogs/DialogsAlertDialogFragment.java
853
package org.holoeverywhere.demo.fragments.dialogs; import org.holoeverywhere.app.AlertDialog; import org.holoeverywhere.app.AlertDialog.Builder; import org.holoeverywhere.app.DialogFragment; import org.holoeverywhere.demo.R; import android.os.Bundle; public class DialogsAlertDialogFragment extends DialogFragment { public DialogsAlertDialogFragment() { setDialogType(DialogType.AlertDialog); } @Override public AlertDialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getSupportActivity()); builder.setTitle(R.string.library_name); builder.setIcon(R.drawable.icon); prepareBuilder(builder); return builder.create(); } protected void prepareBuilder(Builder builder) { builder.setMessage("Hello, Dialog!"); } }
mit
davetrux/CodeMash-2.0.1.5
services/oauth-spring/src/main/java/com/codemash/service/NameGenerator.java
2116
package com.codemash.service; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by david on 12/22/14. */ public class NameGenerator { public Person getRandomName() { Person result = new Person(); Random generator = new Random(); int r = generator.nextInt(Constants.getSurnames().length); result.setLastName(Constants.getSurnames()[r]); if(r % 2 == 0){ r = generator.nextInt(Constants.getFemale().length); result.setFirstName(Constants.getFemale()[r]); result.setGender("f"); } else { r = generator.nextInt(Constants.getMale().length); result.setFirstName(Constants.getMale()[r]); result.setGender("m"); } return result; } public Person getRandomName(String gender) { Person result = new Person(); Random generator = new Random(); int r = generator.nextInt(Constants.getSurnames().length); result.setLastName(Constants.getSurnames()[r]); if(gender.equalsIgnoreCase("f")){ r = generator.nextInt(Constants.getFemale().length); result.setFirstName(Constants.getFemale()[r]); result.setGender("f"); } else { r = generator.nextInt(Constants.getMale().length); result.setFirstName(Constants.getMale()[r]); result.setGender("m"); } return result; } public List<Person> getRandomPersons(int count) { List<Person> result = new ArrayList<Person>(); for(int i = 0; i < count; i++){ result.add(getRandomName()); } return result; } private Person getStaticPerson() { Person result = new Person(); result.setFirstName("Dave"); result.setLastName("Truxall"); result.setGender("m"); return result; } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListServiceSasResponseInner.java
1244
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.storage.fluent.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; /** The List service SAS credentials operation response. */ @Immutable public final class ListServiceSasResponseInner { @JsonIgnore private final ClientLogger logger = new ClientLogger(ListServiceSasResponseInner.class); /* * List service SAS credentials of specific resource. */ @JsonProperty(value = "serviceSasToken", access = JsonProperty.Access.WRITE_ONLY) private String serviceSasToken; /** * Get the serviceSasToken property: List service SAS credentials of specific resource. * * @return the serviceSasToken value. */ public String serviceSasToken() { return this.serviceSasToken; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
mit
PhilipMay/cucumber-jvm
guice/src/test/java/cucumber/runtime/java/guice/Mappings.java
206
package cucumber.runtime.java.guice; import cucumber.annotation.en.Given; public class Mappings { @Given("^I have (\\d+) cukes in my belly$") public void I_have_cukes_in_my_belly(int n) { } }
mit
theyelllowdart/jmockit
samples/TimingFramework/src/org/jdesktop/animation/timing/interpolation/KeyFrames.java
9290
/** * Copyright (c) 2006, Sun Microsystems, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the TimingFramework project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jdesktop.animation.timing.interpolation; /** * KeyFrames holds information about the times at which values are sampled * (KeyTimes) and the values at those times (KeyValues). It also holds * information about how to interpolate between these values for * times that lie between the sampling points. * * @author Chet */ public final class KeyFrames<T> { private KeyValues<T> keyValues; private KeyTimes keyTimes; private KeyInterpolators interpolators; /** * Simplest variation; determine keyTimes based on even division of * 0-1 range based on number of keyValues. This constructor * assumes LINEAR interpolation. * @param keyValues values that will be assumed at each time in keyTimes */ public KeyFrames(KeyValues<T> keyValues) { init(keyValues, null, (Interpolator)null); } /** * This variant takes both keyValues (values at each * point in time) and keyTimes (times at which values are sampled). * @param keyValues values that the animation will assume at each of the * corresponding times in keyTimes * @param keyTimes times at which the animation will assume the * corresponding values in keyValues * @throws IllegalArgumentException keyTimes and keySizes must have the * same number of elements since these structures are meant to have * corresponding entries; an exception is thrown otherwise. */ public KeyFrames(KeyValues<T> keyValues, KeyTimes keyTimes) { init(keyValues, keyTimes, (Interpolator)null); } /** * Full constructor: caller provides an instance of all key structures which will be used to * calculate between all times in the keyTimes list. A null interpolator parameter * is equivalent to calling {@link KeyFrames#KeyFrames(KeyValues, KeyTimes)}. * @param keyValues values that the animation will assume at each of the * corresponding times in keyTimes * @param keyTimes times at which the animation will assume the * corresponding values in keyValues * @param interpolators collection of Interpolators that control * the calculation of values in each of the intervals defined by keyFrames. * If this value is null, a {@link LinearInterpolator} will be used * for all intervals. If there is only one interpolator, that interpolator * will be used for all intervals. Otherwise, there must be a number of * interpolators equal to the number of intervals (which is one less than * the number of keyTimes). * @throws IllegalArgumentException if keyTimes and keyValues do not have the same number of * elements (these structures are meant to have corresponding entries); or if the number of * interpolators is not zero (interpolators == null), one, or one less than the size of * keyTimes. */ public KeyFrames(KeyValues<T> keyValues, KeyTimes keyTimes, Interpolator... interpolators) { init(keyValues, keyTimes, interpolators); } /** * Utility constructor that assumes even division of times according to * size of keyValues and interpolation according to interpolators * parameter. * @param keyValues values that the animation will assume at each of the * corresponding times in keyTimes * @param interpolators collection of Interpolators that control * the calculation of values in each of the intervals defined by keyFrames. * If this value is null, a {@link LinearInterpolator} will be used * for all intervals. If there is only one interpolator, that interpolator * will be used for all intervals. Otherwise, there must be a number of * interpolators equal to the number of intervals (which is one less than * the number of keyTimes). * @throws IllegalArgumentException The number of interpolators must either * be zero (interpolators == null), one, or one less than the size of * keyTimes. */ public KeyFrames(KeyValues<T> keyValues, Interpolator... interpolators) { init(keyValues, null, interpolators); } /** * Utility function called by constructors to perform common initialization chores. */ @SuppressWarnings({"ParameterHidesMemberVariable"}) private void init(KeyValues<T> keyValues, KeyTimes keyTimes, Interpolator... interpolators) { int numFrames = keyValues.getSize(); // If keyTimes null, create our own. if (keyTimes == null) { float[] keyTimesArray = new float[numFrames]; float timeVal = 0.0f; keyTimesArray[0] = timeVal; for (int i = 1; i < numFrames - 1; ++i) { timeVal += 1.0f / (numFrames - 1); keyTimesArray[i] = timeVal; } keyTimesArray[numFrames - 1] = 1.0f; this.keyTimes = new KeyTimes(keyTimesArray); } else { this.keyTimes = keyTimes; } this.keyValues = keyValues; if (numFrames != this.keyTimes.getSize()) { throw new IllegalArgumentException("keyValues and keyTimes must be of equal size"); } if (interpolators != null && interpolators.length != numFrames - 1 && interpolators.length != 1) { throw new IllegalArgumentException( "interpolators must be either null (implying interpolation for all intervals), " + "a single interpolator (which will be used for all intervals), or a number of " + "interpolators equal to one less than the number of times."); } this.interpolators = new KeyInterpolators(numFrames - 1, interpolators); } KeyValues<T> getKeyValues() { return keyValues; } KeyTimes getKeyTimes() { return keyTimes; } /** * Returns time interval that contains this time fraction. */ public int getInterval(float fraction) { return keyTimes.getInterval(fraction); } /** * Returns a value for the given fraction elapsed of the animation * cycle. Given the fraction, this method will determine what * interval the fraction lies within, how much of that interval has * elapsed, what the boundary values are (from KeyValues), what the * interpolated fraction is (from the Interpolator for the interval), * and what the final interpolated intermediate value is (using the * appropriate Evaluator). * This method will call into the Interpolator for the time interval * to get the interpolated method. To ensure that future operations * succeed, the value received from the interpolation will be clamped * to the interval [0,1]. */ T getValue(float fraction) { // First, figure out the real fraction to use, given the // interpolation type and keyTimes int interval = getInterval(fraction); float t0 = keyTimes.getTime(interval); float t1 = keyTimes.getTime(interval + 1); float t = (fraction - t0) / (t1 - t0); float interpolatedT = interpolators.interpolate(interval, t); // clamp to avoid problems with buggy Interpolators if (interpolatedT < 0.0f) { interpolatedT = 0.0f; } else if (interpolatedT > 1.0f) { interpolatedT = 1.0f; } return keyValues.getValue(interval, interval + 1, interpolatedT); } }
mit
openhab/openhab2
bundles/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/api/exception/PageNotFoundApiException.java
1056
/** * 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.opensprinkler.internal.api.exception; /** * The {@link PageNotFoundApiException} exception is thrown when result from the OpenSprinkler * API is "result" : 32. * * @author Chris Graham - Initial contribution */ public class PageNotFoundApiException extends GeneralApiException { /** * Serial ID of this error class. */ private static final long serialVersionUID = -6395534685500451473L; /** * Basic constructor allowing the storing of a single message. * * @param message Descriptive message about the error. */ public PageNotFoundApiException(String message) { super(message); } }
epl-1.0
eclipse/packagedrone
bundles/org.eclipse.packagedrone.utils/src/org/eclipse/packagedrone/utils/Exceptions.java
2915
/******************************************************************************* * Copyright (c) 2015 IBH SYSTEMS GmbH. * 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: * IBH SYSTEMS GmbH - initial API and implementation *******************************************************************************/ package org.eclipse.packagedrone.utils; import java.util.concurrent.Callable; import java.util.function.Function; public class Exceptions { @FunctionalInterface public interface ThrowingRunnable { public void run () throws Exception; } /** * Call and wrap {@link Exception}s into a {@link RuntimeException} * * @param callable * the {@link Callable} to call * @param <T> * argument type * @return the return value of the callable */ public static <T> T wrapException ( final Callable<T> callable ) { try { return callable.call (); } catch ( final RuntimeException e ) { throw e; } catch ( final Exception e ) { throw new RuntimeException ( e ); } } public static void wrapException ( final ThrowingRunnable run ) { wrapException ( () -> { run.run (); return null; } ); } /** * Call and wrap {@link Exception}s into an exception provided by the * function. * <p> * If the function returns {@code null}, a {@link RuntimeException} will be * created instead. * </p> * * @param callable * the {@link Callable} to call * @param <T> * argument type * @return the return value of the callable */ public static <T> T wrapException ( final Callable<T> callable, final Function<Exception, RuntimeException> func ) { try { return callable.call (); } catch ( final RuntimeException e ) { throw e; } catch ( final Exception e ) { RuntimeException t = func.apply ( e ); if ( t == null ) { t = new RuntimeException ( e ); } else { // fixing the stack trace to be a bit more precise t.setStackTrace ( Thread.currentThread ().getStackTrace () ); } throw t; } } public static void wrapException ( final ThrowingRunnable run, final Function<Exception, RuntimeException> func ) { wrapException ( () -> { run.run (); return null; }, func ); } }
epl-1.0
sguan-actuate/birt
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/PDFImageBlockContainerLM.java
1492
package org.eclipse.birt.report.engine.layout.pdf; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.extension.IReportItemExecutor; import org.eclipse.birt.report.engine.layout.IBlockStackingLayoutManager; import org.eclipse.birt.report.engine.layout.area.impl.AreaFactory; import org.eclipse.birt.report.engine.layout.area.impl.ContainerArea; import org.eclipse.birt.report.engine.layout.content.ItemExecutorWrapper; import org.eclipse.birt.report.engine.layout.content.LineStackingExecutor; public class PDFImageBlockContainerLM extends PDFBlockContainerLM implements IBlockStackingLayoutManager { public PDFImageBlockContainerLM( PDFLayoutEngineContext context, PDFStackingLM parent, IContent content, IReportItemExecutor executor ) { super( context, parent, content, executor ); child = new PDFLineAreaLM( context, this, new LineStackingExecutor( new ItemExecutorWrapper( executor, content ), executor ) ); } protected boolean traverseChildren( ) throws BirtException { return traverseSingleChild( ); } protected void closeLayout( ) { /** * set root height. * For Image block container, OffsetY and box property should be zero */ root.setHeight( getCurrentBP( )); } protected void createRoot( ) { root = (ContainerArea)AreaFactory.createLogicContainer( content.getReportContent( ) ); } protected void closeExecutor( ) { } }
epl-1.0
IncQueryLabs/incquery-examples-cps
domains/org.eclipse.viatra.examples.cps.deployment/src/org/eclipse/viatra/examples/cps/deployment/impl/BehaviorTransitionImpl.java
7337
/** * Copyright (c) 2014-2016 IncQuery Labs Ltd. * 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: * Akos Horvath, Abel Hegedus, Tamas Borbas, Zoltan Ujhelyi, Istvan David - initial API and implementation */ package org.eclipse.viatra.examples.cps.deployment.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectResolvingEList; import org.eclipse.viatra.examples.cps.deployment.BehaviorState; import org.eclipse.viatra.examples.cps.deployment.BehaviorTransition; import org.eclipse.viatra.examples.cps.deployment.DeploymentPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Behavior Transition</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.eclipse.viatra.examples.cps.deployment.impl.BehaviorTransitionImpl#getDescription <em>Description</em>}</li> * <li>{@link org.eclipse.viatra.examples.cps.deployment.impl.BehaviorTransitionImpl#getTo <em>To</em>}</li> * <li>{@link org.eclipse.viatra.examples.cps.deployment.impl.BehaviorTransitionImpl#getTrigger <em>Trigger</em>}</li> * </ul> * * @generated */ public class BehaviorTransitionImpl extends MinimalEObjectImpl.Container implements BehaviorTransition { /** * The default value of the '{@link #getDescription() <em>Description</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDescription() * @generated * @ordered */ protected static final String DESCRIPTION_EDEFAULT = null; /** * The cached value of the '{@link #getDescription() <em>Description</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDescription() * @generated * @ordered */ protected String description = DESCRIPTION_EDEFAULT; /** * The cached value of the '{@link #getTo() <em>To</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTo() * @generated * @ordered */ protected BehaviorState to; /** * The cached value of the '{@link #getTrigger() <em>Trigger</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTrigger() * @generated * @ordered */ protected EList<BehaviorTransition> trigger; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BehaviorTransitionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DeploymentPackage.Literals.BEHAVIOR_TRANSITION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getDescription() { return description; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDescription(String newDescription) { String oldDescription = description; description = newDescription; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DeploymentPackage.BEHAVIOR_TRANSITION__DESCRIPTION, oldDescription, description)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BehaviorState getTo() { if (to != null && to.eIsProxy()) { InternalEObject oldTo = (InternalEObject)to; to = (BehaviorState)eResolveProxy(oldTo); if (to != oldTo) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, DeploymentPackage.BEHAVIOR_TRANSITION__TO, oldTo, to)); } } return to; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BehaviorState basicGetTo() { return to; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTo(BehaviorState newTo) { BehaviorState oldTo = to; to = newTo; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DeploymentPackage.BEHAVIOR_TRANSITION__TO, oldTo, to)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<BehaviorTransition> getTrigger() { if (trigger == null) { trigger = new EObjectResolvingEList<BehaviorTransition>(BehaviorTransition.class, this, DeploymentPackage.BEHAVIOR_TRANSITION__TRIGGER); } return trigger; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DeploymentPackage.BEHAVIOR_TRANSITION__DESCRIPTION: return getDescription(); case DeploymentPackage.BEHAVIOR_TRANSITION__TO: if (resolve) return getTo(); return basicGetTo(); case DeploymentPackage.BEHAVIOR_TRANSITION__TRIGGER: return getTrigger(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case DeploymentPackage.BEHAVIOR_TRANSITION__DESCRIPTION: setDescription((String)newValue); return; case DeploymentPackage.BEHAVIOR_TRANSITION__TO: setTo((BehaviorState)newValue); return; case DeploymentPackage.BEHAVIOR_TRANSITION__TRIGGER: getTrigger().clear(); getTrigger().addAll((Collection<? extends BehaviorTransition>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case DeploymentPackage.BEHAVIOR_TRANSITION__DESCRIPTION: setDescription(DESCRIPTION_EDEFAULT); return; case DeploymentPackage.BEHAVIOR_TRANSITION__TO: setTo((BehaviorState)null); return; case DeploymentPackage.BEHAVIOR_TRANSITION__TRIGGER: getTrigger().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case DeploymentPackage.BEHAVIOR_TRANSITION__DESCRIPTION: return DESCRIPTION_EDEFAULT == null ? description != null : !DESCRIPTION_EDEFAULT.equals(description); case DeploymentPackage.BEHAVIOR_TRANSITION__TO: return to != null; case DeploymentPackage.BEHAVIOR_TRANSITION__TRIGGER: return trigger != null && !trigger.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (description: "); result.append(description); result.append(')'); return result.toString(); } } //BehaviorTransitionImpl
epl-1.0
monnimeter/smarthome
bundles/io/org.eclipse.smarthome.io.rest.core/src/main/java/org/eclipse/smarthome/io/rest/core/thing/setup/ThingSetupManagerResource.java
12207
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) 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 */ package org.eclipse.smarthome.io.rest.core.thing.setup; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.eclipse.smarthome.config.core.Configuration; import org.eclipse.smarthome.core.items.GroupItem; import org.eclipse.smarthome.core.items.dto.ItemDTO; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.core.thing.setup.ThingSetupManager; import org.eclipse.smarthome.io.rest.RESTResource; import org.eclipse.smarthome.io.rest.core.item.EnrichedItemDTO; import org.eclipse.smarthome.io.rest.core.item.EnrichedItemDTOMapper; import org.eclipse.smarthome.io.rest.core.thing.EnrichedThingDTO; import org.eclipse.smarthome.io.rest.core.thing.EnrichedThingDTOMapper; import org.eclipse.smarthome.io.rest.core.thing.ThingResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** * This class acts as a REST resource for the setup manager. * * @author Dennis Nobel - Initial contribution * @author Yordan Zhelev - Added Swagger annotations */ @Path(ThingSetupManagerResource.PATH_SETUP) @Api(value = ThingSetupManagerResource.PATH_SETUP, hidden = true) public class ThingSetupManagerResource implements RESTResource { private final Logger logger = LoggerFactory.getLogger(ThingSetupManagerResource.class); /** The URI path to this resource */ public static final String PATH_SETUP = "setup"; private ThingSetupManager thingSetupManager; @Context private UriInfo uriInfo; @POST @Path("things") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Adds a new thing to the registry.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response addThing(@ApiParam(value = "thing data", required = true) EnrichedThingDTO thingBean, @QueryParam("enableChannels") @DefaultValue("true") @ApiParam(value = "enable channels", required = false) boolean enableChannels) throws IOException { ThingUID thingUIDObject = new ThingUID(thingBean.UID); ThingUID bridgeUID = null; if (thingBean.bridgeUID != null) { bridgeUID = new ThingUID(thingBean.bridgeUID); } Configuration configuration = ThingResource.getConfiguration(thingBean); thingSetupManager.addThing(thingUIDObject, configuration, bridgeUID, thingBean.item.label, thingBean.item.groupNames, enableChannels); return Response.ok().build(); } @PUT @Path("things") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Updates a thing.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response updateThing(@ApiParam(value = "thing data", required = true) EnrichedThingDTO thingBean) throws IOException { ThingUID thingUID = new ThingUID(thingBean.UID); ThingUID bridgeUID = null; if (thingBean.bridgeUID != null) { bridgeUID = new ThingUID(thingBean.bridgeUID); } Configuration configuration = ThingResource.getConfiguration(thingBean); Thing thing = thingSetupManager.getThing(thingUID); if (thingBean.item != null && thing != null) { String label = thingBean.item.label; List<String> groupNames = thingBean.item.groupNames; @SuppressWarnings("deprecation") GroupItem thingGroupItem = thing.getLinkedItem(); if (thingGroupItem != null) { boolean labelChanged = false; if (thingGroupItem.getLabel() == null || !thingGroupItem.getLabel().equals(label)) { thingGroupItem.setLabel(label); labelChanged = true; } boolean groupsChanged = setGroupNames(thingGroupItem, groupNames); if (labelChanged || groupsChanged) { thingSetupManager.updateItem(thingGroupItem); } } } if (thing != null) { if (bridgeUID != null) { thing.setBridgeUID(bridgeUID); } ThingResource.updateConfiguration(thing, configuration); thingSetupManager.updateThing(thing); } return Response.ok().build(); } @DELETE @Path("/things/{thingUID}") @ApiOperation(value = "Removes a thing from the registry. Set \'force\' to __true__ if you want the thing te be removed immediately") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response removeThing(@PathParam("thingUID") @ApiParam(value = "thingUID") String thingUID, @DefaultValue("false") @QueryParam("force") @ApiParam(value = "force") boolean force) { thingSetupManager.removeThing(new ThingUID(thingUID), force); return Response.ok().build(); } @DELETE @Path("/things/channels/{channelUID}") @ApiOperation(value = "Removes corresponding item and the link for the channel.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response disableChannel(@PathParam("channelUID") @ApiParam(value = "channelUID") String channelUID) { thingSetupManager.disableChannel(new ChannelUID(channelUID)); return Response.ok().build(); } @PUT @Path("/things/channels/{channelUID}") @ApiOperation(value = "Adds corresponding item and the link for the channel.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response enableChannel(@PathParam("channelUID") @ApiParam(value = "channelUID") String channelUID) { thingSetupManager.enableChannel(new ChannelUID(channelUID)); return Response.ok().build(); } @GET @Path("things") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Gets all available things.", response = EnrichedThingDTO.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response getThings() { List<EnrichedThingDTO> thingBeans = new ArrayList<>(); Collection<Thing> things = thingSetupManager.getThings(); for (Thing thing : things) { EnrichedThingDTO thingItemBean = EnrichedThingDTOMapper.map(thing, uriInfo.getBaseUri()); thingBeans.add(thingItemBean); } return Response.ok(thingBeans).build(); } @PUT @Path("/things/{thingUID}/label") @Consumes(MediaType.TEXT_PLAIN) @ApiOperation(value = "Sets the label for a given thing UID") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response setLabel(@PathParam("thingUID") @ApiParam(value = "thingUID") String thingUID, @ApiParam(value = "label") String label) { thingSetupManager.setLabel(new ThingUID(thingUID), label); return Response.ok().build(); } @PUT @Path("/things/{thingUID}/groups") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Sets group names to the group item linked to the thing.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response setGroups(@PathParam("thingUID") @ApiParam(value = "thingUID") String thingUID, @ApiParam(value = "group names") List<String> groupNames) { Thing thing = thingSetupManager.getThing(new ThingUID(thingUID)); if (thing != null) { @SuppressWarnings("deprecation") GroupItem thingGroupItem = thing.getLinkedItem(); if (thingGroupItem != null) { boolean groupsChanged = setGroupNames(thingGroupItem, groupNames); if (groupsChanged) { thingSetupManager.updateItem(thingGroupItem); } } } return Response.ok().build(); } @GET @Path("groups") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Gets all available group items with tag \'home-group\'.", response = EnrichedItemDTO.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response getHomeGroups() { List<EnrichedItemDTO> itemBeans = new ArrayList<>(); Collection<GroupItem> homeGroups = thingSetupManager.getHomeGroups(); for (GroupItem homeGroupItem : homeGroups) { EnrichedItemDTO itemBean = EnrichedItemDTOMapper.map(homeGroupItem, true, uriInfo.getBaseUri()); itemBeans.add(itemBean); } return Response.ok(itemBeans).build(); } @POST @Path("groups") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Creates a group item.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response addHomeGroup(@ApiParam(value = "item data") ItemDTO itemBean) { thingSetupManager.addHomeGroup(itemBean.name, itemBean.label); return Response.ok().build(); } @DELETE @Path("groups/{itemName}") @ApiOperation(value = "Removes a group item.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response removeHomeGroup(@PathParam("itemName") @ApiParam(value = "item name") String itemName) { thingSetupManager.removeHomeGroup(itemName); return Response.ok().build(); } @PUT @Path("groups/{itemName}/label") @Consumes(MediaType.TEXT_PLAIN) @ApiOperation(value = "Sets label of the group item.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Group item not found") }) public Response setHomeGroupLabel(@PathParam("itemName") @ApiParam(value = "item name") String itemName, @ApiParam(value = "label") String label) { try { thingSetupManager.setHomeGroupLabel(itemName, label); } catch (IllegalArgumentException ex) { logger.info("Received HTTP PUT request for set home group label at '{}' for the unknown group item '{}'.", uriInfo.getPath(), itemName); return Response.status(Status.NOT_FOUND).build(); } return Response.ok().build(); } protected void setThingSetupManager(ThingSetupManager thingSetupManager) { this.thingSetupManager = thingSetupManager; } protected void unsetThingSetupManager(ThingSetupManager thingSetupManager) { this.thingSetupManager = null; } private boolean setGroupNames(GroupItem thingGroupItem, List<String> groupNames) { boolean itemUpdated = false; for (String groupName : groupNames) { if (!thingGroupItem.getGroupNames().contains(groupName)) { thingGroupItem.addGroupName(groupName); itemUpdated = true; } } for (String groupName : thingGroupItem.getGroupNames()) { if (!groupNames.contains(groupName)) { thingGroupItem.removeGroupName(groupName); itemUpdated = true; } } return itemUpdated; } }
epl-1.0
Charling-Huang/birt
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/content/impl/ObjectContent.java
1997
package org.eclipse.birt.report.engine.content.impl; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; public class ObjectContent extends ImageContent { /* Attributes described in W3C recommendation. declare (declare) #IMPLIED -- declare but don't instantiate flag -- classid %URI; #IMPLIED -- identifies an implementation -- codebase %URI; #IMPLIED -- base URI for classid, data, archive-- data %URI; #IMPLIED -- reference to object's data -- type %ContentType; #IMPLIED -- content type for data -- codetype %ContentType; #IMPLIED -- content type for code -- archive CDATA #IMPLIED -- space-separated list of URIs -- standby %Text; #IMPLIED -- message to show while loading -- height %Length; #IMPLIED -- override height -- width %Length; #IMPLIED -- override width -- usemap %URI; #IMPLIED -- use client-side image map -- name CDATA #IMPLIED -- submit as part of form -- tabindex NUMBER #IMPLIED -- position in tabbing order -- */ private HashMap<String, String> params = new HashMap<String, String>( ); ObjectContent( ReportContent report ) { super( report ); } public void addParam( String name, String value ) { if ( null != name ) { params.put( name, value ); } } public HashMap<String, String> getParamters( ) { return params; } public String getParamValueByName( String name ) { return params.get( name ); } public void readContent( DataInputStream in, ClassLoader loader ) throws IOException { throw new IOException( "Unsupported operation: Object content can not be serialized" ); } public void writeContent( DataOutputStream out ) throws IOException { throw new IOException( "Unsupported operation: Object content can not be serialized" ); } }
epl-1.0
ESSICS/cs-studio
applications/apputil/apputil-plugins/org.csstudio.utility.screenshot/src/org/csstudio/utility/screenshot/menu/action/HelpDocumentationAction.java
2253
/* * Copyright (c) 2007 Stiftung Deutsches Elektronen-Synchrotron, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.utility.screenshot.menu.action; import org.csstudio.utility.screenshot.ScreenshotWorker; import org.csstudio.utility.screenshot.internal.localization.ScreenshotMessages; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; public class HelpDocumentationAction extends Action { ScreenshotWorker worker = null; public HelpDocumentationAction(ScreenshotWorker w) { worker = w; this.setText(ScreenshotMessages.getString("ScreenshotView.MENU_HELP_DOC")); this.setToolTipText(ScreenshotMessages.getString("ScreenshotView.MENU_HELP_DOC_TT")); this.setEnabled(false); } @Override public void run() { MessageDialog.openInformation(null, ScreenshotMessages.getString("ScreenshotPlugin.Screenshot"), ScreenshotMessages.getString("ScreenshotView.MESSAGE_NOT_IMPLEMENTED")); } }
epl-1.0
Anthchirp/dawnsci
org.eclipse.dawnsci.plotting.api/src/org/eclipse/dawnsci/plotting/api/remote/IRemotePlottingSystem.java
9383
/*- * Copyright 2014 Diamond Light Source Ltd. * * 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 */ package org.eclipse.dawnsci.plotting.api.remote; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.Collection; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; import org.eclipse.dawnsci.plotting.api.IPlotActionSystem; import org.eclipse.dawnsci.plotting.api.PlotType; import org.eclipse.dawnsci.plotting.api.annotation.IAnnotation; import org.eclipse.dawnsci.plotting.api.axis.IClickListener; import org.eclipse.dawnsci.plotting.api.axis.IPositionListener; import org.eclipse.dawnsci.plotting.api.region.IRegion; import org.eclipse.dawnsci.plotting.api.region.IRegion.RegionType; import org.eclipse.dawnsci.plotting.api.region.IRegionListener; import org.eclipse.dawnsci.plotting.api.trace.ColorOption; import org.eclipse.dawnsci.plotting.api.trace.IImageStackTrace; import org.eclipse.dawnsci.plotting.api.trace.IImageTrace; import org.eclipse.dawnsci.plotting.api.trace.IIsosurfaceTrace; import org.eclipse.dawnsci.plotting.api.trace.ILineStackTrace; import org.eclipse.dawnsci.plotting.api.trace.ILineTrace; import org.eclipse.dawnsci.plotting.api.trace.IMulti2DTrace; import org.eclipse.dawnsci.plotting.api.trace.IScatter3DTrace; import org.eclipse.dawnsci.plotting.api.trace.ISurfaceTrace; import org.eclipse.dawnsci.plotting.api.trace.ITrace; import org.eclipse.dawnsci.plotting.api.trace.ITraceListener; import org.eclipse.dawnsci.plotting.api.trace.IVectorTrace; import org.eclipse.dawnsci.plotting.api.trace.TraceEvent; import org.eclipse.dawnsci.plotting.api.trace.TraceWillPlotEvent; /** * The methods of IPlottingSystem with RemoteExceptions declared. * Used for Jython scripting of plotting system. */ public interface IRemotePlottingSystem extends Remote { public IImageTrace createImageTrace(String traceName) throws RemoteException; public ILineTrace createLineTrace(String traceName) throws RemoteException; public IVectorTrace createVectorTrace(String traceName) throws RemoteException; public ISurfaceTrace createSurfaceTrace(String traceName) throws RemoteException; public IIsosurfaceTrace createIsosurfaceTrace(String traceName) throws RemoteException; public IMulti2DTrace createMulti2DTrace(String traceName) throws RemoteException; public ILineStackTrace createLineStackTrace(String traceName) throws RemoteException; public IScatter3DTrace createScatter3DTrace(String traceName) throws RemoteException; public IImageStackTrace createImageStackTrace(String traceName) throws RemoteException; public void addTrace(ITrace trace) throws RemoteException; public void removeTrace(ITrace trace) throws RemoteException; public ITrace getTrace(String name) throws RemoteException; public Collection<ITrace> getTraces() throws RemoteException; public Collection<ITrace> getTraces(Class<? extends ITrace> clazz) throws RemoteException; public void addTraceListener(ITraceListener l) throws RemoteException; public void removeTraceListener(ITraceListener l) throws RemoteException; public void renameTrace(ITrace trace, String name) throws RemoteException; public IRegion createRegion(String name, RegionType regionType) throws RemoteException; public void addRegion(IRegion region) throws RemoteException; public void removeRegion(IRegion region) throws RemoteException; public IRegion getRegion(String name) throws RemoteException; public Collection<IRegion> getRegions(RegionType type) throws RemoteException; public boolean addRegionListener(IRegionListener l) throws RemoteException; public boolean removeRegionListener(IRegionListener l) throws RemoteException; public void clearRegions() throws RemoteException; public void clearTraces() throws RemoteException; public Collection<IRegion> getRegions() throws RemoteException; public void renameRegion(IRegion region, String name) throws RemoteException; public IRemoteAxis createAxis(String title, boolean isYAxis, int side) throws RemoteException; public IRemoteAxis getSelectedYAxis() throws RemoteException; public void setSelectedYAxis(IRemoteAxis yAxis) throws RemoteException; public IRemoteAxis getSelectedXAxis() throws RemoteException; public void setSelectedXAxis(IRemoteAxis xAxis) throws RemoteException; public void autoscaleAxes() throws RemoteException; public IAnnotation createAnnotation(String name) throws RemoteException; public void addAnnotation(IAnnotation annot) throws RemoteException; public void removeAnnotation(IAnnotation annot) throws RemoteException; public IAnnotation getAnnotation(String name) throws RemoteException; public void clearAnnotations() throws RemoteException; public void renameAnnotation(IAnnotation annotation, String name) throws RemoteException; public void printPlotting() throws RemoteException; public void copyPlotting() throws RemoteException; public String savePlotting(String filename) throws RemoteException; public void savePlotting(String filename, String filetype) throws RemoteException; public String getTitle() throws RemoteException; public void setTitle(String title) throws RemoteException; public String getPlotName() throws RemoteException; public List<ITrace> createPlot1D(IDataset x, List<? extends IDataset> ys, IProgressMonitor monitor) throws RemoteException; public List<ITrace> createPlot1D(IDataset x, List<? extends IDataset> ys, String title, IProgressMonitor monitor) throws RemoteException; public List<ITrace> updatePlot1D(IDataset x, List<? extends IDataset> ys, IProgressMonitor monitor) throws RemoteException; public ITrace createPlot2D(IDataset image, List<? extends IDataset> axes, IProgressMonitor monitor) throws RemoteException; public ITrace updatePlot2D(IDataset image, List<? extends IDataset> axes, IProgressMonitor monitor) throws RemoteException; public void setPlotType(PlotType plotType) throws RemoteException; public void append(String dataSetName, Number xValue, Number yValue, IProgressMonitor monitor) throws RemoteException; public void reset() throws RemoteException; public void resetAxes() throws RemoteException; public void clear() throws RemoteException; public void dispose() throws RemoteException; public void repaint() throws RemoteException; public void repaint(boolean autoScale) throws RemoteException; public PlotType getPlotType() throws RemoteException; public boolean is2D() throws RemoteException; public IPlotActionSystem getPlotActionSystem() throws RemoteException; public void setDefaultCursor(int cursorType) throws RemoteException; public IRemoteAxis removeAxis(IRemoteAxis axis) throws RemoteException; public List<IRemoteAxis> getAxes() throws RemoteException; public IRemoteAxis getAxis(String name) throws RemoteException; public void addPositionListener(IPositionListener l) throws RemoteException; public void removePositionListener(IPositionListener l) throws RemoteException; public void setKeepAspect(boolean b) throws RemoteException; public boolean isShowIntensity() throws RemoteException; public void setShowIntensity(boolean b) throws RemoteException; public void setShowLegend(boolean b) throws RemoteException; public Object getAdapter(Class adapter) throws RemoteException; public boolean isDisposed() throws RemoteException; public void setColorOption(ColorOption colorOption) throws RemoteException; public boolean isRescale() throws RemoteException; public void setRescale(boolean rescale) throws RemoteException; public void setFocus() throws RemoteException; public boolean isXFirst() throws RemoteException; /** * Set if the first plot is the x-axis. * @param xFirst */ public void setXFirst(boolean xFirst) throws RemoteException; public void fireWillPlot(TraceWillPlotEvent evt) throws RemoteException; /** * May be used to force a trace to fire update listeners in the plotting system. * @param evt */ public void fireTraceUpdated(TraceEvent evt) throws RemoteException; public void fireTraceAdded(TraceEvent evt) throws RemoteException; public List<ITrace> createPlot1D(IDataset x, List<? extends IDataset> ys, List<String> dataNames, String title, IProgressMonitor monitor) throws RemoteException; public List<ITrace> updatePlot1D(IDataset x, List<? extends IDataset> ys, List<String> dataNames, IProgressMonitor monitor) throws RemoteException; public ITrace createPlot2D(IDataset image, List<? extends IDataset> axes, String dataName, IProgressMonitor monitor) throws RemoteException; public ITrace updatePlot2D(IDataset image, List<? extends IDataset> axes, String dataName, IProgressMonitor monitor) throws RemoteException; public void setEnabled(boolean enabled) throws RemoteException; public boolean isEnabled() throws RemoteException; public void addClickListener(IClickListener l) throws RemoteException; public void removeClickListener(IClickListener l) throws RemoteException; public void clearRegionTool() throws RemoteException; public void printScaledPlotting() throws RemoteException; }
epl-1.0
mandeepdhami/netvirt-ctrl
sdnplatform/src/main/java/org/sdnplatform/devicemanager/web/AbstractDeviceResource.java
8605
/* * Copyright (c) 2012,2013 Big Switch Networks, Inc. * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html * * 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 file incorporates work covered by the following copyright and * permission notice: * * Originally created by David Erickson, Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.sdnplatform.devicemanager.web; import java.util.Iterator; import org.openflow.util.HexString; import org.restlet.data.Form; import org.restlet.data.Status; import org.restlet.resource.ServerResource; import org.sdnplatform.devicemanager.IDevice; import org.sdnplatform.devicemanager.IDeviceService; import org.sdnplatform.devicemanager.SwitchPort; import org.sdnplatform.devicemanager.internal.Device; import org.sdnplatform.packet.IPv4; import org.sdnplatform.util.FilterIterator; /** * Resource for querying and displaying devices that exist in the system */ public abstract class AbstractDeviceResource extends ServerResource { public static final String MAC_ERROR = "Invalid MAC address: must be a 48-bit quantity, " + "expressed in hex as AA:BB:CC:DD:EE:FF"; public static final String VLAN_ERROR = "Invalid VLAN: must be an integer in the range 0-4095"; public static final String IPV4_ERROR = "Invalid IPv4 address: must be in dotted decimal format, " + "234.0.59.1"; public static final String DPID_ERROR = "Invalid Switch DPID: must be a 64-bit quantity, expressed in " + "hex as AA:BB:CC:DD:EE:FF:00:11"; public static final String PORT_ERROR = "Invalid Port: must be a positive integer"; public Iterator<? extends IDevice> getDevices() { IDeviceService deviceManager = (IDeviceService)getContext().getAttributes(). get(IDeviceService.class.getCanonicalName()); Long macAddress = null; Short vlan = null; Integer ipv4Address = null; Long switchDPID = null; Integer switchPort = null; Form form = getQuery(); String macAddrStr = form.getFirstValue("mac", true); String vlanStr = form.getFirstValue("vlan", true); String ipv4Str = form.getFirstValue("ipv4", true); String dpid = form.getFirstValue("dpid", true); String port = form.getFirstValue("port", true); if (macAddrStr != null) { try { macAddress = HexString.toLong(macAddrStr); } catch (Exception e) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, MAC_ERROR); return null; } } if (vlanStr != null) { try { vlan = Short.parseShort(vlanStr); if (vlan > 4095 || vlan < 0) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, VLAN_ERROR); return null; } } catch (Exception e) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, VLAN_ERROR); return null; } } if (ipv4Str != null) { try { ipv4Address = IPv4.toIPv4Address(ipv4Str); } catch (Exception e) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, IPV4_ERROR); return null; } } if (dpid != null) { try { switchDPID = HexString.toLong(dpid); } catch (Exception e) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, DPID_ERROR); return null; } } if (port != null) { try { switchPort = Integer.parseInt(port); if (switchPort < 0) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, PORT_ERROR); return null; } } catch (Exception e) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, PORT_ERROR); return null; } } @SuppressWarnings("unchecked") Iterator<Device> diter = (Iterator<Device>) deviceManager.queryDevices(macAddress, vlan, ipv4Address, switchDPID, switchPort); final String macStartsWith = form.getFirstValue("mac__startswith", true); final String vlanStartsWith = form.getFirstValue("vlan__startswith", true); final String ipv4StartsWith = form.getFirstValue("ipv4__startswith", true); final String dpidStartsWith = form.getFirstValue("dpid__startswith", true); final String portStartsWith = form.getFirstValue("port__startswith", true); return new FilterIterator<Device>(diter) { @Override protected boolean matches(Device value) { if (macStartsWith != null) { if (!value.getMACAddressString().startsWith(macStartsWith)) return false; } if (vlanStartsWith != null) { boolean match = false; for (Short v : value.getVlanId()) { if (v != null && v.toString().startsWith(vlanStartsWith)) { match = true; break; } } if (!match) return false; } if (ipv4StartsWith != null) { boolean match = false; for (Integer v : value.getIPv4Addresses()) { String str; if (v != null && (str = IPv4.fromIPv4Address(v)) != null && str.startsWith(ipv4StartsWith)) { match = true; break; } } if (!match) return false; } if (dpidStartsWith != null) { boolean match = false; for (SwitchPort v : value.getAttachmentPoints(true)) { String str; if (v != null && (str = HexString.toHexString(v.getSwitchDPID(), 8)) != null && str.startsWith(dpidStartsWith)) { match = true; break; } } if (!match) return false; } if (portStartsWith != null) { boolean match = false; for (SwitchPort v : value.getAttachmentPoints(true)) { String str; if (v != null && (str = Integer.toString(v.getPort())) != null && str.startsWith(portStartsWith)) { match = true; break; } } if (!match) return false; } return true; } }; } }
epl-1.0
PatrickSHYee/idecore
com.salesforce.ide.core/src/com/salesforce/ide/core/internal/utils/Utils.java
41663
/******************************************************************************* * Copyright (c) 2014 Salesforce.com, inc.. * 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: * Salesforce.com, inc. - initial API and implementation ******************************************************************************/ package com.salesforce.ide.core.internal.utils; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.log4j.Logger; import org.apache.xerces.parsers.DOMParser; import org.eclipse.core.internal.resources.OS; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ProjectScope; import org.eclipse.core.resources.ResourceAttributes; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.WorkbenchException; import org.osgi.framework.Bundle; import org.w3c.dom.Document; import org.xml.sax.InputSource; import com.salesforce.ide.api.metadata.types.MetadataExt; import com.salesforce.ide.core.ForceIdeCorePlugin; import com.salesforce.ide.core.internal.utils.TestContext.TestContextEnum; import com.salesforce.ide.core.model.Component; import com.salesforce.ide.core.services.PackageDeployService; import com.salesforce.ide.core.services.PackageRetrieveService; import com.sforce.soap.metadata.FileProperties; import com.sforce.soap.metadata.ManageableState; import com.sforce.soap.partner.fault.wsc.ApiFault; /** * Common utilities methods */ @SuppressWarnings("restriction") public class Utils { private static final Logger logger = Logger.getLogger(Utils.class); public static final String DIALOG_TITLE_ERROR = "Error"; public static final String DIALOG_TITLE_WARNING = "Warning"; public static final String TEST_CONTEXT_PROP = "TestContext"; public static boolean isEmpty(Object obj) { return null == obj; } public static boolean isNotEmpty(Object obj) { return null != obj; } public static boolean isEmpty(Object[] objs) { return objs == null || objs.length == 0; } public static boolean isNotEmpty(Object[] objs) { return objs != null && 0 < objs.length; } public static boolean isEmpty(byte[] objs) { return objs == null || objs.length == 0; } public static boolean isNotEmpty(byte[] objs) { return objs != null && 0 < objs.length; } public static boolean isEmpty(Collection<?> col) { return col == null || col.isEmpty(); } public static boolean isNotEmpty(Collection<?> col) { return col != null && !col.isEmpty(); } public static boolean isEmpty(List<?> col) { return col == null || col.isEmpty(); } public static boolean isNotEmpty(List<?> col) { return col != null && !col.isEmpty(); } public static boolean isEmpty(Map<?, ?> map) { return map == null || map.isEmpty(); } public static boolean isNotEmpty(Map<?, ?> map) { return map != null && !map.isEmpty(); } public static boolean isWorkspaceCaseSensitive() { return Platform.OS_MACOSX.equals(Platform.getOS()) ? false : new java.io.File("a").compareTo(new java.io.File("A")) != 0; } public static void openForcePerspective() { IWorkbench workbench = ForceIdeCorePlugin.getDefault().getWorkbench(); IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IAdaptable input; if (page != null) { input = page.getInput(); } else { input = ResourcesPlugin.getWorkspace().getRoot(); } try { workbench.showPerspective(Constants.FORCE_PLUGIN_PREFIX + ".perspective", window, input); } catch (WorkbenchException e) { logger.error("Unable to open Force.com Perspective", e); } } public static Shell getShell() { Shell shell = PlatformUI.getWorkbench().getWorkbenchWindows()[0] .getShell(); return shell; } public static void openError(Exception e, String message, String details) { IStatus status = new Status(IStatus.ERROR, ForceIdeCorePlugin .getPluginId(), Constants.ERROR_CODE__44, details, e); ErrorDialog.openError(getShell(), DIALOG_TITLE_ERROR, message, status); } public static void openError(Throwable pThrowable, boolean includeStackTrace, String messageSummary) { IStatus status = null; messageSummary = Utils.isEmpty(messageSummary) ? ForceExceptionUtils .getRootExceptionMessage(pThrowable) : messageSummary; if (includeStackTrace && logger.isDebugEnabled()) { status = new MultiStatus(ForceIdeCorePlugin.getPluginId(), Constants.ERROR_CODE__44, getStatusMessage(pThrowable), ForceExceptionUtils.getRootCause(pThrowable)); addTraceToStatus((MultiStatus) status, pThrowable.getStackTrace(), IStatus.ERROR); } else { status = new Status(IStatus.ERROR, ForceIdeCorePlugin.getPluginId(), Constants.ERROR_CODE__44, getStatusMessage(pThrowable), null); } openErrorDialog(DIALOG_TITLE_ERROR, messageSummary, status); } public static void openError(Shell shell, Throwable pThrowable, boolean includeStackTrace, String messageSummary) { IStatus status = null; messageSummary = Utils.isEmpty(messageSummary) ? ForceExceptionUtils .getRootCause(pThrowable).getMessage() : messageSummary; if (includeStackTrace && logger.isDebugEnabled()) { status = new MultiStatus(ForceIdeCorePlugin.getPluginId(), Constants.ERROR_CODE__44, getStatusMessage(pThrowable), ForceExceptionUtils.getRootCause(pThrowable)); addTraceToStatus((MultiStatus) status, pThrowable.getStackTrace(), IStatus.ERROR); } else { status = new Status(IStatus.ERROR, ForceIdeCorePlugin.getPluginId(), Constants.ERROR_CODE__44, getStatusMessage(pThrowable), null); } openErrorDialog(shell, DIALOG_TITLE_ERROR, messageSummary, status); } public static void openWarning(Throwable pThrowable, boolean includeStackTrace, String messageSummary) { IStatus status = null; if (includeStackTrace && logger.isDebugEnabled()) { status = new MultiStatus(ForceIdeCorePlugin.getPluginId(), Constants.ERROR_CODE__44, getStatusMessage(pThrowable), ForceExceptionUtils.getRootCause(pThrowable)); addTraceToStatus((MultiStatus) status, pThrowable.getStackTrace(), IStatus.WARNING); } else { status = new Status(IStatus.WARNING, ForceIdeCorePlugin .getPluginId(), Constants.ERROR_CODE__44, getStatusMessage(pThrowable), null); } openErrorDialog(DIALOG_TITLE_WARNING, messageSummary, status); } private static String getStatusMessage(Throwable th) { if (th == null) { return null; } if (th instanceof ApiFault) { ApiFault apiFault = (ApiFault) th; return apiFault.getExceptionCode().name() + " - " + apiFault.getExceptionMessage(); } else if (th.getCause() instanceof ApiFault) { ApiFault apiFault = (ApiFault) th.getCause(); return apiFault.getExceptionCode().name() + " - " + apiFault.getExceptionMessage(); } else { return ForceExceptionUtils.getStrippedRootCauseMessage(th); } } private static void openErrorDialog(String type, String message, IStatus status) { Shell newShell = getShell(); if (newShell == null) { newShell = new Shell(); } ErrorDialog.openError(newShell, type, message, status); } private static void openErrorDialog(Shell shell, String type, String message, IStatus status) { ErrorDialog.openError(shell, type, message, status); } public static void addTraceToStatus(MultiStatus multiStatus, StackTraceElement[] trace, int errorCode) { for (int i = 1; i < trace.length; i++) { IStatus stat = new Status(errorCode, ForceIdeCorePlugin .getPluginId(), Constants.ERROR_CODE__44, trace[i] .getClassName() + "." + trace[i].getMethodName() + " (" + trace[i].getFileName() + " " + trace[i].getLineNumber() + ")", null); multiStatus.add(stat); } } public static String generateCoreExceptionLog(CoreException ex) { if(ex==null){ throw new IllegalArgumentException(); } StringBuffer strBuff = new StringBuffer(ex.getMessage()); if (ex.getStatus() != null && ex.getStatus().isMultiStatus() && isNotEmpty(((MultiStatus) ex.getStatus()).getChildren())) { strBuff.append(" Cause(s):\n"); IStatus[] stats = ((MultiStatus) ex.getStatus()).getChildren(); int cnt = 0; for (IStatus status : stats) { strBuff.append(" (").append(++cnt).append(") ").append( status.getMessage()); if (status.getException() != null) { strBuff.append("\n Root Exception: ").append( status.getException().getMessage()); } } } else if (ex.getStatus() != null) { strBuff.append(" Cause:\n"); strBuff.append(" (1) ").append(ex.getStatus().getMessage()); if (ex.getStatus().getException() != null) { strBuff.append("\n Root Exception: ").append( ex.getStatus().getException().getMessage()); } } return strBuff.toString(); } public static boolean openConfirm(String pTitle, String pMessage) { return MessageDialog.openConfirm(getShell(), pTitle, pMessage); } public static boolean openConfirm(Shell shell, String pTitle, String pMessage) { return MessageDialog.openConfirm(shell, pTitle, pMessage); } public static boolean openQuestion(String pTitle, String pMessage) { return MessageDialog.openQuestion(getShell(), pTitle, pMessage); } public static boolean openQuestion(Shell shell, String pTitle, String pMessage) { return MessageDialog.openQuestion(shell, pTitle, pMessage); } public static void openError(String pTitle, String pMessage) { MessageDialog.openError(getShell(), pTitle, pMessage); } public static void openInfo(String pTitle, String pMessage) { MessageDialog.openInformation(getShell(), pTitle, pMessage); } public static void openWarn(String pTitle, String pMessage) { MessageDialog.openWarning(getShell(), pTitle, pMessage); } public static void openWarn(Shell shell, String pTitle, String pMessage) { MessageDialog.openWarning(shell, pTitle, pMessage); } public static void openDialog(IProject project, WizardDialog dialog) { TestContext testContext = TestContext .getTestContextBy(getTestContextEnum(project)); testContext.execAsyncRunnables(); dialog.open(); } public static boolean openQuestion(IProject project, Shell shell, String title, String message) { TestContext testContext = TestContext .getTestContextBy(getTestContextEnum(project)); testContext.execAsyncRunnables(); return openQuestion(shell, title, message); } public static IResource getCurrentSelectionResource() { IWorkbenchWindow workbenchWindow = ForceIdeCorePlugin.getDefault() .getWorkbench().getActiveWorkbenchWindow(); if (workbenchWindow == null) { return null; } ISelection selection = workbenchWindow.getSelectionService() .getSelection(); if (selection instanceof IStructuredSelection) { Object firstSelected = ((IStructuredSelection) selection) .getFirstElement(); if (firstSelected instanceof IResource) { return (IResource) firstSelected; } } return null; } public static IStatus getStatus(Exception e) { String msg = e.getMessage(); if (e instanceof CoreException) { CoreException ce = (CoreException) e; IStatus status = ce.getStatus(); return status; } IStatus status = new Status(IStatus.ERROR, ForceIdeCorePlugin .getPluginId(), IStatus.OK, msg, null); return status; } public static String getDisplayDate(Calendar cal) { if (cal == null) { return "n/a"; } SimpleDateFormat formatter = new SimpleDateFormat( "E yyyy.MM.dd 'at' hh:mm:ss a zzz"); return formatter.format(cal.getTime()); } public static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } public static boolean isValidFullUrl(String endpoint) { if (Utils.isEmpty(endpoint)) { return false; } try { new URL(endpoint); } catch (MalformedURLException e) { return false; } return true; } public static boolean validateDomainName(String domainName) { String oneAlpha = "(.)*((\\p{Alpha})|[-])(.)*"; String domainIdentifier = "((\\p{Alnum})([-]|(\\p{Alnum}))*(\\p{Alnum}))|(\\p{Alnum})"; String domainNameRule = "(" + domainIdentifier + ")((\\.)(" + domainIdentifier + "))*"; if (domainName == null || domainName.length() > 63) { return false; } return domainName.matches(domainNameRule) && domainName.matches(oneAlpha); } public static String getServerNameFromUrl(String url) { if (Utils.isEmpty(url)) { return url; } String protocol = (url.startsWith(Constants.HTTPS) ? Constants.HTTPS : Constants.HTTP) + "://"; return url.substring(url.indexOf(protocol) + protocol.length(), url .indexOf("/", protocol.length() + 1)); } public static boolean isInternalMode() { String mode = System.getProperty(Constants.SYS_SETTING_SFDC_INTERNAL); return Utils.isNotEmpty(mode) && Constants.SYS_SETTING_SFDC_INTERNAL_VALUE.equals(mode) ? true : false; } public static boolean isXForceProxy() { String forceProxy = System.getProperty(Constants.SYS_SETTING_X_FORCE_PROXY); return Utils.isNotEmpty(forceProxy) && Constants.SYS_SETTING_SFDC_INTERNAL_VALUE.equals(forceProxy) ? true : false; } public static int getApexManifestTimeoutMS() { String apexManifestTimeoutMS = System.getProperty(Constants.SYS_SETTING_APEX_MANIFEST_TIMEOUT); if (Utils.isNotEmpty(apexManifestTimeoutMS)) { try { return Integer.parseInt(apexManifestTimeoutMS); } catch (Exception e) { return Constants.APEX_MANIFEST_TIMEOUT_IN_MS_DEFAULT; } } else { return Constants.APEX_MANIFEST_TIMEOUT_IN_MS_DEFAULT; } } public static String getDefaultSystemApiVersion() { String apiVersion = System .getProperty(Constants.SYS_SETTING_DEFAULT_API_VERSION); return Utils.isNotEmpty(apiVersion) ? apiVersion : Constants.EMPTY_STRING; } public static String getPollLimit() { String pollLimit = System .getProperty(Constants.SYS_SETTING_POLL_LIMIT_MILLIS); return Utils.isNotEmpty(pollLimit) ? pollLimit : Constants.EMPTY_STRING; } public static String getLocaleFormattedDateTime(long datetime) { return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.getDefault()).format( new Date(datetime)); } public static String getCurrentFormattedDateTime() { return (new SimpleDateFormat(Constants.STANDARD_DATE_FORMAT)) .format(new Date()); } public static String getFormattedTimestamp(File file) { return file != null && file.exists() ? getLocaleFormattedDateTime(file.lastModified()) : null; } public static File getCacheFile(IProject project) { try { Bundle bundle = ForceIdeCorePlugin.getDefault().getBundle(); IPath state = null; if (project != null) { state = project.getWorkingLocation(ForceIdeCorePlugin .getPluginId()); } else { state = Platform.getStateLocation(bundle); } return new File(state.toFile(), Constants.CACHE_FILENAME); } catch (Exception e) { logger.warn("Unable to get cache file: " + e.getMessage()); } return null; } public static URL getCacheUrl(IProject project) { File file = Utils.getCacheFile(project); if (file != null) { try { if (logger.isDebugEnabled()) { logger.debug("Manifest cache file (does" + (file.exists() ? " " : " not ") + "exist): " + file.toURI().toURL().toExternalForm()); } return file.toURI().toURL(); } catch (MalformedURLException e) { logger.warn("Unable to get url from file: " + e.getMessage()); } } if (logger.isInfoEnabled()) { logger.info("Manifest cache file: n/a"); } return null; } public static boolean isDebugMode() { String debug = System.getProperty(Constants.SYS_SETTING_DEBUG); return logger != null && logger.isDebugEnabled() || Utils.isNotEmpty(debug) && Constants.SYS_SETTING_DEBUG_VALUE.equals(debug); } public static boolean isManifestListenerEnabled() { String listener = System .getProperty(Constants.SYS_SETTING_MANIFEST_LISTENER); return Utils.isNotEmpty(listener) ? Boolean.parseBoolean(listener) : true; } public static boolean hasDefaultProperties() { String propFilePath = System .getProperty(Constants.SYS_SETTING_PROPERTIES); return Utils.isNotEmpty(propFilePath) && (new java.io.File(propFilePath)).exists(); } public static Properties getDefaultProperties() { Properties props = null; String propFilePath = System .getProperty(Constants.SYS_SETTING_PROPERTIES); if (Utils.isEmpty(propFilePath)) { return props; } java.io.File propFile = new java.io.File(propFilePath); if (!propFile.exists()) { return props; } try (final QuietCloseable<FileInputStream> c = QuietCloseable.make(new FileInputStream(propFile))) { final FileInputStream fis = c.get(); if (fis.available() > 0) { logger.debug("Loading properties found in prop file '" + propFilePath + "'"); props = new Properties(); props.load(fis); } else { logger.debug("No content found in prop file '" + propFilePath + "'"); } } catch (Exception e) { logger.warn("Unable to load prop file '" + propFilePath + "'", e); } return props; } /** * remove service level version number from bundle version which composed by * <major_version_#>.<minor_version_#>.<service_level_version_#>.qualifier * * @param bundleVersion * @return */ public static String removeServiceLevelFromPluginVersion( String bundleVersion) { String[] subBundleVersion = bundleVersion.split("\\."); StringBuffer strBuffer = new StringBuffer(); for (int i = 0; i < subBundleVersion.length; i++) { if (i == 2) { continue; // skip service level version } strBuffer.append(subBundleVersion[i]).append("."); } String newBundleVersion = strBuffer.toString(); return newBundleVersion.substring(0, newBundleVersion.length() - 1); } public static void logStats() { OperationStats[] operationsStats = new OperationStats[2]; OperationStats aggregatedStats = new OperationStats( OperationStats.AGGREGATED_OPERATIONS); int idx = 0; if (PackageDeployService.getOperationStats() != null) { PackageDeployService.getOperationStats().logStats(); operationsStats[idx] = PackageDeployService.getOperationStats(); } if (PackageRetrieveService.getOperationStats() != null) { PackageRetrieveService.getOperationStats().logStats(); operationsStats[++idx] = PackageRetrieveService.getOperationStats(); } if (isNotEmpty(operationsStats)) { aggregatedStats.aggregateStats(operationsStats); aggregatedStats.logStats(); } ForceIdeCorePlugin.logStats(); } public static String timeoutToSecs(String timeout) { return timeoutToSecs(Long.parseLong(timeout)); } public static String timeoutToSecs(long timeout) { return timeout < 1 ? "0 secs" : timeout / Constants.SECONDS_TO_MILISECONDS + " secs"; } // REVIEWME: should this be moved to ProjectService? public static TestContextEnum getTestContextEnum(IProject project) { if (project == null) { return TestContextEnum.NONE; } IEclipsePreferences node = getPreferences(project); return node != null ? TestContextEnum.valueOf(node.get(TEST_CONTEXT_PROP, TestContextEnum.NONE.toString())) : TestContextEnum.NONE; } public static IEclipsePreferences getPreferences(IProject project) { if (project == null) { return null; } ProjectScope projectScope = new ProjectScope(project); IEclipsePreferences node = projectScope .getNode(Constants.PLUGIN_PREFIX); return node; } public static Method getGetter(Class<?> clazz, String field) { if (clazz == null) { return null; } Method[] methods = clazz.getDeclaredMethods(); if (isEmpty(methods)) { return null; } for (Method method : methods) { if (Utils.isNotEmpty(field) && method.getName().startsWith("get"+field) && method.getGenericParameterTypes().length==0) { return method; } } return null; } public static List<String> getProperties(Class<?> clazz) { if (clazz == null) { return null; } List<String> properties = new ArrayList<>(); Method[] methods = clazz.getDeclaredMethods(); if (isNotEmpty(methods)) { for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getGenericParameterTypes().length == 0) { properties.add(method.getName().substring(3)); } } } return properties; } public static Object getPropertyValue(Object obj, String propertyName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (obj == null || propertyName == null) { return null; } Object propertyValue = null; Method getterMethod = getGetterMethod(obj.getClass(), propertyName); if (getterMethod != null) { Object[] args = null; propertyValue = getterMethod.invoke(obj, args); } return propertyValue; } public static Method getGetterMethod(Class<?> clazz, String methodNameWithoutGetPrefix) { Method getterMethod = null; Method[] methods = clazz.getDeclaredMethods(); if (isNotEmpty(methods)) { for (Method method : methods) { if (method.getName().equals("get" + methodNameWithoutGetPrefix) && method.getGenericParameterTypes().length==0) { getterMethod = method; break; } } } return getterMethod; } @SuppressWarnings("unchecked") public static Class<? extends MetadataExt> getMetadataClassForComponentType( String componentType) throws ClassNotFoundException { if (Utils.isEmpty(componentType)) { return null; } return (Class<? extends MetadataExt>) Class .forName(Constants.COMPONENT_TYPE_API_CLASS_PACKAGE + "." + componentType); } public static void saveDocument(Document doc, Bundle bundle, String fileName) throws IOException, TransformerException { IPath state = Platform.getStateLocation(bundle); saveDocument(doc, state.toPortableString() + File.separator + fileName); } public static void saveDocument(Document doc, String fullPath) throws IOException, TransformerException { File f = new File(fullPath); f.createNewFile(); TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setAttribute("indent-number", new Integer(2)); Transformer xform = tfactory.newTransformer(); xform.setOutputProperty(OutputKeys.INDENT, "yes"); // xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", // "4"); Source src = new DOMSource(doc); try (final QuietCloseable<OutputStreamWriter> c = QuietCloseable.make(new OutputStreamWriter(new FileOutputStream(f, false), Constants.FORCE_DEFAULT_ENCODING_CHARSET))) { final OutputStreamWriter writer = c.get(); Result result = new StreamResult(writer); xform.transform(src, result); } } public static Document loadDocument(URL fileUrl) { Document doc = null; DOMParser parser = new DOMParser(); if (logger.isDebugEnabled()) { logger.debug("Loading document from " + fileUrl.toExternalForm()); } try { InputSource inputSource = new InputSource(fileUrl.openStream()); parser.parse(inputSource); doc = parser.getDocument(); } catch (Exception e) { logger.warn("Unable to load document: " + e.getMessage()); } return doc; } public static void adjustResourceReadOnly(IResource resource, boolean readyOnly, boolean recursive) { if (resource == null || !resource.exists()) { return; } // no need to set read-only if resource is already set to desired // read-only setting if (resource.getResourceAttributes() != null && resource.getResourceAttributes().isReadOnly() != readyOnly) { ResourceAttributes resourceAttributes = new ResourceAttributes(); resourceAttributes.setReadOnly(readyOnly); try { resource.setResourceAttributes(resourceAttributes); if (logger.isDebugEnabled()) { logger.debug("Set resource '" + resource.getProjectRelativePath() .toPortableString() + "' read-only=" + readyOnly); } } catch (CoreException e) { String logMessage = Utils.generateCoreExceptionLog(e); logger.warn("Unable to set read-only attribute on file " + resource.getName() + ": " + logMessage); } } if (recursive && resource instanceof IContainer) { try { IResource[] children = ((IContainer) resource).members(); if (Utils.isNotEmpty(children)) { for (IResource childResource : children) { adjustResourceReadOnly(childResource, readyOnly, recursive); } } } catch (CoreException e) { String logMessage = Utils.generateCoreExceptionLog(e); logger.warn("Unable to get children for folder " + resource.getName() + ": " + logMessage); } } } // !!! ADD NEW METHODS ABOVE THE FOLLOWING STRING UTILS SECTION !!! // (S T A R T) M O V E T O S T R I N G U T I L S private final static String[] IDE_INVALID_CHARS = new String[] { ">", "<", ",", ":", ";", "/", "\\" }; private final static String[] HOST_PORT_INVALID_CHARS = new String[] { ">", "<", ",", ";", "/", "\\", " " }; public static boolean isEqual(String str, String str2,boolean isCaseSensitive) { return isNotEmpty(str) && isNotEmpty(str2) ? isCaseSensitive ? str.equals(str2) : str.equalsIgnoreCase(str2) : false; } public static boolean isEqual(String str, String compareStr) { return isNotEmpty(str) && isNotEmpty(compareStr) && str.equals(compareStr); } public static boolean isNotEqual(String str, String str2) { return !isEqual(str, str2, true); } public static boolean isEmpty(String str) { return str == null || str.length() == 0; } public static boolean isNotEmpty(String str) { return str != null && 0 < str.length(); } public static boolean startsWith(String str, String suffix) { return isNotEmpty(str) && isNotEmpty(suffix) && str.startsWith(suffix); } public static boolean endsWith(String str, String suffix) { return isNotEmpty(str) && isNotEmpty(suffix) && str.endsWith(suffix); } public static boolean contains(String str, String contains) { return isNotEmpty(str) && isNotEmpty(contains) && str.contains(contains); } public static InputStream openContentStream(String contents) { return new ByteArrayInputStream(contents.getBytes()); } public static String getContentString(IFile file) throws IOException, CoreException { String contentStr = null; if (file != null && file.exists()) { StringBuffer strBuff = new StringBuffer(); try (final QuietCloseable<BufferedReader> c = QuietCloseable.make(new BufferedReader(new InputStreamReader(file.getContents(), Constants.UTF_8)))) { final BufferedReader reader = c.get(); String line = reader.readLine(); if (line != null) { strBuff.append(line); } while ((line = reader.readLine()) != null) { strBuff.append(Constants.NEW_LINE); strBuff.append(line); } } catch (IOException e) { logger.error("Unable to load body from file " + file.getName(), e); throw e; } catch (CoreException e) { throw e; } if (logger.isDebugEnabled()) { logger.debug("Loaded body size [" + strBuff.toString().getBytes().length + "] bytes from file '" + file.getName() + "'"); } contentStr = strBuff.toString(); } return contentStr; } public static String getStringFromStream(InputStream is, long length) throws IOException { return getStringFromBytes(getBytesFromStream(is, length)); } public static byte[] getBytesFromStream(InputStream is, long length) throws IOException { try (final QuietCloseable<InputStream> c0 = QuietCloseable.make(is)) { final InputStream in = c0.get(); try (final QuietCloseable<ByteArrayOutputStream> c = QuietCloseable.make(new ByteArrayOutputStream())) { final ByteArrayOutputStream out = c.get(); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); } return out.toByteArray(); } } } public static String getStringFromBytes(byte[] bytes) { return new String(bytes); } public static byte[] getBytesFromFile(File file) throws IOException { if (file == null || !file.exists()) { return null; } return getBytesFromStream(new FileInputStream(file), file.length()); } public static byte[] getBytesFromFile(IFile file) throws IOException, CoreException { if (file == null || !file.exists()) { return null; } return getBytesFromStream(file.getContents(), 0); } public static String trim(String str) { return Utils.isNotEmpty(str) ? str.trim() : str; } public static String replaceSpaceWithUnderscore(String str) { return str.replaceAll(" ", "_"); } public static String stripExtension(Object obj) { if (obj == null) { return null; } String tmpName = null; if (obj instanceof Component) { tmpName = ((Component) obj).getName(); } else if (obj instanceof IFile) { tmpName = ((IFile) obj).getName(); } else if (obj instanceof String) { tmpName = (String) obj; } if (null == tmpName) return null; if (tmpName.contains(".")) { tmpName = tmpName.substring(0, tmpName.indexOf(".")); } // strip "-meta" typically found on folder metadata files if (tmpName.endsWith("-meta")) { tmpName = tmpName.substring(0, tmpName.indexOf("-meta")); } return tmpName; } public static String stripSourceFolder(String filePath) { if (isEmpty(filePath)) { return filePath; } String[] folderPrefixes = new String[] { Constants.SOURCE_FOLDER_NAME + "/", Constants.REFERENCED_PACKAGE_FOLDER_NAME + "/" }; for (String folderPrefix : folderPrefixes) { if (filePath.startsWith(folderPrefix)) { return filePath.substring(filePath.indexOf(folderPrefix) + folderPrefix.length()); } } return filePath; } public static String stripNamespace(String str, String namespace) { if (isEmpty(namespace) || isEmpty(str) || !str.startsWith(namespace + Constants.NAMESPACE_SEPARATOR)) { return str; } if (logger.isDebugEnabled()) { logger.debug("Remove prepended namespace '" + namespace + "' from '" + str + "'"); } return str.substring(namespace.length() + Constants.NAMESPACE_SEPARATOR.length()); } public static String getNameFromFilePath(String filePath) { if (isNotEmpty(filePath) && filePath.contains("/")) { int idx = filePath.lastIndexOf("/") + 1; filePath = filePath.substring(idx); if (isNotEmpty(filePath) && filePath.contains(".")) { filePath = stripExtension(filePath); } } return filePath; } public static String getPlural(String str) { if (isEmpty(str)) { return str; } if (str.endsWith("x") || str.endsWith("ss")) { return str + "es"; } else if (str.endsWith("s")) { return str; } else { return str + "s"; } } public static String stripUnsupportedChars(String str) { if (isEmpty(str)) { return str; } return str.replaceAll(":", ""); } public static boolean isAlphaNumericValid(String str) { if (isEmpty(str)) { return true; } String regex = "(\\w+)"; return str.matches(regex); } /** * Metadata names are (where needed) encoded such that they are reasonable * file names & do not contain '.'. The basic encoding is URL encoding, * excluding '+' (spaces are preserved), but also escaping '.' to '%2E' and * '__' to '%5F%5F' */ public static String encode(String name) { if (isEmpty(name)) { return name; } try { String replaceStr = URLEncoder.encode(name, Constants.FORCE_DEFAULT_ENCODING_CHARSET); replaceStr = replaceStr.replace('+', ' '); // Javadoc of URLEncoder.encode() - The special characters ".", "-", // "*", and "_" remain the same. // replaceStr = replaceStr.replace(".", "%2E"); // replaceStr = replaceStr.replace("__", "%5F%5F"); if (logger.isDebugEnabled() && !name.equals(replaceStr)) { logger.debug("Encoded name '" + name + "' to '" + replaceStr + "'"); } return replaceStr; } catch (UnsupportedEncodingException uee) { throw new RuntimeException(uee); } } public static boolean containsInvalidChars(String str) { if (isEmpty(str)) { return false; } for (String invalidChar : getInvalidChars()) { if (str.contains(invalidChar)) { return true; } } return false; } protected static String[] getInvalidChars() { Set<String> invalidCharSet = new HashSet<>(); // invalid resource chars provided by eclipse platform for (char osInvalidChar : OS.INVALID_RESOURCE_CHARACTERS) { invalidCharSet.add(String.valueOf(osInvalidChar)); } // invalid chars defined by IDE for (String ideInvalidChar : IDE_INVALID_CHARS) { invalidCharSet.add(ideInvalidChar); } return invalidCharSet.toArray(new String[invalidCharSet.size()]); } public static boolean containsInvalidHostPortChars(String str) { if (isEmpty(str)) { return false; } for (String invalidChar : HOST_PORT_INVALID_CHARS) { if (str.contains(invalidChar)) { return true; } } return false; } public static String stripNonAlphaNumericChars(String str) { if (isEmpty(str)) { return str; } str = str.replaceAll("[^a-zA-Z0-9 _]", ""); // clean up nonAlphaNumeric // char in front/trail of _. // Ex. -__a__b__c__- would // become __a__b__c__ str = str.replaceAll("^_*", ""); // strips all starting "_". Ex // __a__b__c__ would become // a__b__c__ str = str.replaceAll("_*$", ""); // strips all trailing "_". Ex // a__b__c__ would become a__b__c str = str.replaceAll("_+", "_"); // replaces all leftover multiple // occurances of "_" with 1 "_". Ex. // a__b__c would become a_b_c return str; } public static boolean containsNonAlphaNumericChars(String str) { if (isEmpty(str)) { return false; } Pattern p = Pattern.compile("[^a-zA-Z0-9]"); return p.matcher(str).matches(); } public static String generateNameFromLabel(String str) { if (isEmpty(str)) { return str; } if (startsWithNumeric(str)) { str = "X" + str; } str = stripNonAlphaNumericChars(str); return replaceSpaceWithUnderscore(str); } public static boolean startsWithNumeric(String str) { if (isEmpty(str)) { return false; } Pattern p = Pattern.compile("[0-9].*"); return p.matcher(str).matches(); } public static String capitalizeFirstLetter(String name) { return isNotEmpty(name) ? Character.toUpperCase(name.charAt(0)) + name.toLowerCase().substring(1) : name; } /** * * @param name * - string need to cap first letter and letter after specific * token * @param token * - token * @param escape * - does this token needs escape? * @return */ public static String capFirstLetterAndLetterAfterToken(String name, String token, boolean escape) { if (name.indexOf(token.toUpperCase()) == -1 && name.indexOf(token.toLowerCase()) == -1) { return capitalizeFirstLetter(name); } String[] segments = name.toLowerCase().split( escape ? "\\" + token : token.toLowerCase()); // escaping . StringBuffer sb = new StringBuffer(); for (String segment : segments) { sb = sb.append(capitalizeFirstLetter(segment)).append( token.toLowerCase()); } return sb.substring(0, sb.length() - 1); } public static boolean firstLetterCapitalized(String name) { return isNotEmpty(name) ? Character.isUpperCase(name.charAt(0)) : false; } public static String camelCaseToSpaces(String str) { if (isEmpty(str)) { return str; } StringBuffer result = new StringBuffer(); char prevChar = ' '; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (Character.isUpperCase(c) && !Character.isUpperCase(prevChar)) { result.append(' '); result.append(Character.toUpperCase(c)); } else { result.append(c); } prevChar = c; } return result.toString(); } /** * Return null if filePath doesn't have file extension but this method will * fail: 1) if filePath param doesn't have valid file extension and having . * in filePath 2) if filePath is pointing to folder metadata file See * testcase: UtilsTest_unit.testGetExtensionFromFilePath() for usage */ public static String getExtensionFromFilePath(String filePath) { if (Utils.isEmpty(filePath)) { logger.error("Filepath cannot be null"); throw new IllegalArgumentException("Filepath cannot be null"); } String fileExtension = null; String[] splitFilePath = filePath.split("\\."); if (splitFilePath.length == 1) { return null; // no extension found! } if (filePath.endsWith(Constants.DEFAULT_METADATA_FILE_EXTENSION)) { // if it's metadata file, file extension should be // <component-file-extension>-meta.xml fileExtension = splitFilePath[splitFilePath.length - 2] + Constants.DOT + splitFilePath[splitFilePath.length - 1]; } else { // if it's regular component file, file extension should very last // string append after . fileExtension = splitFilePath[splitFilePath.length - 1]; } return fileExtension; } public static boolean isSkipCompatibilityCheck() { String mode = System .getProperty(Constants.SYS_SETTING_SKIP_COMPATIBILITY_CHECK); return Utils.isNotEmpty(mode) && Constants.SYS_SETTING_SKIP_COMPATIBILITY_CHECK_VALUE .equals(mode) ? true : false; } public static boolean isUpgradeEnabled() { String mode = System.getProperty(Constants.SYS_SETTING_UPGRADE_ENABLE); return Utils.isEmpty(mode) || isEqual("true", mode) ? true : false; } /** * if the input array contains any packaged components, returns a new * FileProperties array which lacks any packaged components otherwise just * returns the input array */ public static FileProperties[] removePackagedFiles(FileProperties[] props, String organizationNamespace) { if (Utils.isEmpty(props)) { logger .debug("Input file properties is empty. Skip remove packaged file check."); return props; } List<FileProperties> newProps = new ArrayList<>(); for (FileProperties prop : props) { if (prop.getManageableState() != ManageableState.installed && (Utils.isEmpty(prop.getNamespacePrefix()) || prop .getNamespacePrefix().equals(organizationNamespace))) { newProps.add(prop); } else if (logger.isDebugEnabled()) { logger.debug(prop.getFullName() + " removed from FileProperties"); //$NON-NLS-1$ } } if (newProps.size() != props.length) { return newProps.toArray(new FileProperties[newProps.size()]); } return props; } public static String replaceColonToSurroundingGenericBlock(String type) { return type.indexOf(":") > -1 ? type.replace(":", "<") + ">" : type; // replace // List:@KeyType // to // List<@KeyType> } public static String recursiveReplaceAll(String str, String regex, String replacement) { String replaced = str.replaceAll(regex, replacement); boolean flag = true; while (flag) { String replaced_again = replaced.replaceAll(regex, replacement); if (replaced.equalsIgnoreCase(replaced_again)) { flag = false; } else { replaced = replaced_again; } } return replaced; } }
epl-1.0
iotk/iochibity-java
jni-cxx/src/java/org/iotivity/base/ObserveAction.java
1370
/* ******************************************************************* * * Copyright 2015 Intel Corporation. * *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */ package org.iotivity.base; public enum ObserveAction { REGISTER(0), UNREGISTER(1),; private int value; private ObserveAction(int value) { this.value = value; } public int getValue() { return this.value; } public static ObserveAction get(int val) { for (ObserveAction observeAction : ObserveAction.values()) { if (observeAction.getValue() == val) return observeAction; } throw new IllegalArgumentException("Unexpected ObserveAction value"); } }
epl-1.0
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/ai/instance/illuminaryObelisk/Western_Shield_GeneratorAI2.java
10119
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package ai.instance.illuminaryObelisk; import com.aionemu.commons.network.util.ThreadPoolManager; import com.aionemu.gameserver.ai2.*; import com.aionemu.gameserver.ai2.manager.WalkManager; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.*; import com.aionemu.gameserver.utils.*; /** * @author Rinzler * @rework Ever * @Blackfire */ @AIName("western_shield_generator") public class Western_Shield_GeneratorAI2 extends NpcAI2 { private boolean isInstanceDestroyed; private boolean wave1 = true; private boolean wave2; private boolean wave3; private boolean restrict; private boolean isFull; @Override protected void handleDialogStart(Player player) { if (!restrict) { if (isFull) { PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402203)); } else { if (player.getInventory().getFirstItemByItemId(164000289) != null) { PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 1011)); } else { PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402211)); } } } else { String str = "You can start charging this again after 8 seconds"; PacketSendUtility.sendMessage(player, str); } } @Override public boolean onDialogSelect(final Player player, int dialogId, int questId, int extendedRewardIndex) { if (dialogId == 10000 && player.getInventory().decreaseByItemId(164000289, 3)) { if (wave1) { restrict = true; PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402195)); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { startWaveWesternShieldGenerator1(); PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402198)); wave1 = false; wave2 = true; restrict = false; } }, 8000); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402225)); spawn(702015, 255.7034f, 171.83853f, 325.81653f, (byte) 0, 18); } }, 4000); } if (wave2) { restrict = true; PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402195)); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402198)); PacketSendUtility.sendPacket(player, new SM_USE_OBJECT(player.getObjectId(), getObjectId(), 0, 0)); startWaveWesternShieldGenerator2(); wave2 = false; wave3 = true; restrict = false; } }, 8000); } if (wave3) { restrict = true; PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402195)); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402198)); PacketSendUtility.sendPacket(player, new SM_USE_OBJECT(player.getObjectId(), getObjectId(), 0, 0)); startWaveWesternShieldGenerator3(); wave3 = false; restrict = false; isFull = true; } }, 8000); } } PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 0)); return true; } /** * The higher the phase of the charge will spawn more difficult monsters, in the 3rd phase elite monsters will spawn. * Charging a shield to the 3rd phase continuously can be hard because of all the mobs you will have to handle. * A few easy monsters will spawn after a certain time if you leave the shield unit alone. * After all units have been charged to the 3rd phase, defeat the remaining monsters. * *************************** * Western Shield Generator * * ************************** */ private void startWaveWesternShieldGenerator1() { sp(233722, 258.37912f, 176.03621f, 325.59268f, (byte) 30, 1000, "WesternShieldGenerator1"); sp(233723, 255.55922f, 176.17963f, 325.49332f, (byte) 29, 1000, "WesternShieldGenerator2"); sp(233882, 252.49738f, 176.27466f, 325.52942f, (byte) 29, 1000, "WesternShieldGenerator3"); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { sp(233731, 258.37912f, 176.03621f, 325.59268f, (byte) 30, 1000, "WesternShieldGenerator1"); sp(233732, 255.55922f, 176.17963f, 325.49332f, (byte) 29, 1000, "WesternShieldGenerator2"); sp(233733, 252.49738f, 176.27466f, 325.52942f, (byte) 29, 1000, "WesternShieldGenerator3"); } }, 15000); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { spawn(702221, 255.38777f, 212.00926f, 321.37292f, (byte) 90); } }, 30000); } private void startWaveWesternShieldGenerator2() { sp(233728, 258.37912f, 176.03621f, 325.59268f, (byte) 30, 1000, "WesternShieldGenerator1"); sp(233729, 255.55922f, 176.17963f, 325.49332f, (byte) 29, 1000, "WesternShieldGenerator2"); sp(233730, 252.49738f, 176.27466f, 325.52942f, (byte) 29, 1000, "WesternShieldGenerator3"); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { sp(233737, 258.37912f, 176.03621f, 325.59268f, (byte) 30, 1000, "WesternShieldGenerator1"); sp(233738, 255.55922f, 176.17963f, 325.49332f, (byte) 29, 1000, "WesternShieldGenerator2"); sp(233739, 252.49738f, 176.27466f, 325.52942f, (byte) 29, 1000, "WesternShieldGenerator3"); } }, 15000); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { spawn(702222, 255.38777f, 212.00926f, 321.37292f, (byte) 90); } }, 30000); } private void startWaveWesternShieldGenerator3() { sp(233734, 258.37912f, 176.03621f, 325.59268f, (byte) 30, 6000, "WesternShieldGenerator1"); sp(233735, 255.55922f, 176.17963f, 325.49332f, (byte) 29, 6000, "WesternShieldGenerator2"); sp(233736, 252.49738f, 176.27466f, 325.52942f, (byte) 29, 6000, "WesternShieldGenerator3"); sp(233728, 258.37912f, 176.03621f, 325.59268f, (byte) 30, 23000, "WesternShieldGenerator1"); sp(233729, 255.55922f, 176.17963f, 325.49332f, (byte) 29, 23000, "WesternShieldGenerator2"); sp(233730, 252.49738f, 176.27466f, 325.52942f, (byte) 29, 23000, "WesternShieldGenerator3"); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { sp(233731, 258.37912f, 176.03621f, 325.59268f, (byte) 30, 6000, "WesternShieldGenerator1"); sp(233732, 255.55922f, 176.17963f, 325.49332f, (byte) 29, 6000, "WesternShieldGenerator2"); sp(233739, 252.49738f, 176.27466f, 325.52942f, (byte) 29, 6000, "WesternShieldGenerator3"); sp(233727, 258.37912f, 176.03621f, 325.59268f, (byte) 30, 23000, "WesternShieldGenerator1"); sp(233726, 255.55922f, 176.17963f, 325.49332f, (byte) 29, 23000, "WesternShieldGenerator2"); sp(233725, 252.49738f, 176.27466f, 325.52942f, (byte) 29, 23000, "WesternShieldGenerator3"); } }, 15000); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { spawn(702223, 255.38777f, 212.00926f, 321.37292f, (byte) 90); } }, 30000); } protected void sp(final int npcId, final float x, final float y, final float z, final byte h, final int time, final String walkerId) { ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { if (!isInstanceDestroyed) { Npc npc = (Npc) spawn(npcId, x, y, z, h); npc.getSpawn().setWalkerId(walkerId); WalkManager.startWalking((NpcAI2) npc.getAi2()); } } }, time); } public void onInstanceDestroy() { isInstanceDestroyed = true; } }
gpl-2.0
cfriedt/classpath
test/java.io/BufferedInputStreamTest.java
7324
/************************************************************************* /* BufferedInputStreamTest.java -- Tests BufferedInputStream's /* /* Copyright (c) 1998 Free Software Foundation, Inc. /* Written by Aaron M. Renn (arenn@urbanophile.com) /* /* This program is free software; you can redistribute it and/or modify /* it under the terms of the GNU General Public License as published /* by the Free Software Foundation, 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 General Public License for more details. /* /* You should have received a copy of the GNU General Public License /* along with this program; if not, write to the Free Software Foundation /* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /*************************************************************************/ import java.io.*; public class BufferedInputStreamTest extends BufferedInputStream { public BufferedInputStreamTest(InputStream in, int size) { super(in, size); } public static int marktest(InputStream ins) throws IOException { BufferedInputStream bis = new BufferedInputStream(ins, 15); int bytes_read; int total_read = 0; byte[] buf = new byte[12]; bytes_read = bis.read(buf); total_read += bytes_read; System.out.print(new String(buf, 0, bytes_read)); bytes_read = bis.read(buf); total_read += bytes_read; System.out.print(new String(buf, 0, bytes_read)); bis.mark(75); bis.read(); bis.read(buf); bis.read(buf); bis.read(buf); bis.reset(); bytes_read = bis.read(buf); total_read += bytes_read; System.out.print(new String(buf, 0, bytes_read)); bis.mark(555); bytes_read = bis.read(buf); total_read += bytes_read; System.out.print(new String(buf, 0, bytes_read)); bis.reset(); bis.read(buf); bytes_read = bis.read(buf); total_read += bytes_read; System.out.print(new String(buf, 0, bytes_read)); bytes_read = bis.read(buf); total_read += bytes_read; System.out.print(new String(buf, 0, bytes_read)); bis.mark(14); bis.read(buf); bis.reset(); bytes_read = bis.read(buf); total_read += bytes_read; System.out.print(new String(buf, 0, bytes_read)); while ((bytes_read = bis.read(buf)) != -1) { System.out.print(new String(buf, 0, bytes_read)); total_read += bytes_read; } return(total_read); } public static void main(String[] argv) { System.out.println("Started test of BufferedInputStream"); try { System.out.println("Test 1: Protected Variables Test"); String str = "This is a test line of text for this pass"; StringBufferInputStream sbis = new StringBufferInputStream(str); BufferedInputStreamTest bist = new BufferedInputStreamTest(sbis, 12); bist.read(); bist.mark(5); boolean passed = true; if (bist.buf.length != 12) { passed = false; System.out.println("buf.length is wrong. Expected 12, but got " + bist.buf.length); } if (bist.count != 12) { passed = false; System.out.println("count is wrong. Expected 12, but got " + bist.count); } if (bist.marklimit != 5) { passed = false; System.out.println("marklimit is wrong. Expected 5, but got " + bist.marklimit); } if (bist.markpos != 1) { passed = false; System.out.println("markpos is wrong. Expected 5, but got " + bist.markpos); } if (bist.pos != 1) { passed = false; System.out.println("pos is wrong. Expected 1, but got " + bist.pos); } if (passed) System.out.println("PASSED: Protected Variables Test"); else System.out.println("FAILED: Protected Variables Test"); } catch(IOException e) { System.out.println("FAILED: Protected Variables Test: " + e); } try { System.out.println("Test 2: Simple Read Test"); String str = "One of my 8th grade teachers was Mr. Russell.\n" + "He used to start each year off by telling the class that the\n" + "earth was flat. He did it to teach people to question\n" + "things they are told. But everybody knew that he did it\n" + "so it lost its effect.\n"; StringBufferInputStream sbis = new StringBufferInputStream(str); BufferedInputStream bis = new BufferedInputStream(sbis, 15); byte[] buf = new byte[12]; int bytes_read; while((bytes_read = bis.read(buf)) != -1) System.out.print(new String(buf, 0, bytes_read)); bis.close(); System.out.println("PASSED: Simple Read Test"); } catch (IOException e) { System.out.println("FAILED: Simple Read Test: " + e); } try { System.out.println("Test 3: First mark/reset Test"); String str = "My 6th grade teacher was named Mrs. Hostetler.\n" + "She had a whole list of rules that you were supposed to follow\n" + "in class and if you broke a rule she would make you write the\n" + "rules out several times. The number varied depending on what\n" + "rule you broke. Since I knew I would get in trouble, I would\n" + "just go ahead and write out a few sets on the long school bus\n" + "ride home so that if had to stay in during recess and write\n" + "rules, five minutes later I could just tell the teacher I was\n" + "done so I could go outside and play kickball.\n"; StringBufferInputStream sbis = new StringBufferInputStream(str); int total_read = marktest(sbis); if (total_read == str.length()) System.out.println("PASSED: First mark/reset Test"); else System.out.println("FAILED: First mark/reset Test"); } catch (IOException e) { System.out.println("FAILED: First mark/reset Test: " + e); } try { System.out.println("Test 4: Second mark/reset Test"); String str = "My first day of college was fun. A bunch of us\n" + "got pretty drunk, then this guy named Rick Flake (I'm not\n" + "making that name up) took a piss in the bed of a Physical\n" + "Plant dept pickup truck. Later on we were walking across\n" + "campus, saw a cop, and took off running for no reason.\n" + "When we got back to the dorm we found an even drunker guy\n" + "passed out in a shopping cart outside.\n"; ByteArrayInputStream sbis = new ByteArrayInputStream(str.getBytes()); int total_read = marktest(sbis); if (total_read == str.length()) System.out.println("PASSED: Second mark/reset Test"); else System.out.println("FAILED: Second mark/reset Test"); } catch (IOException e) { System.out.println("FAILED: Second mark/reset Test: " + e); } System.out.println("Finished test of BufferedInputStream"); } // main } // class BufferedInputStreamTest
gpl-2.0
SpoonLabs/astor
examples/Math-issue-288/src/main/java/org/apache/commons/math/stat/descriptive/SynchronizedMultivariateSummaryStatistics.java
7475
/* * 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.math.stat.descriptive; import org.apache.commons.math.DimensionMismatchException; import org.apache.commons.math.linear.RealMatrix; /** * Implementation of * {@link org.apache.commons.math.stat.descriptive.MultivariateSummaryStatistics} that * is safe to use in a multithreaded environment. Multiple threads can safely * operate on a single instance without causing runtime exceptions due to race * conditions. In effect, this implementation makes modification and access * methods atomic operations for a single instance. That is to say, as one * thread is computing a statistic from the instance, no other thread can modify * the instance nor compute another statistic. * @since 1.2 * @version $Revision$ $Date$ */ public class SynchronizedMultivariateSummaryStatistics extends MultivariateSummaryStatistics { /** Serialization UID */ private static final long serialVersionUID = 7099834153347155363L; /** * Construct a SynchronizedMultivariateSummaryStatistics instance * @param k dimension of the data * @param isCovarianceBiasCorrected if true, the unbiased sample * covariance is computed, otherwise the biased population covariance * is computed */ public SynchronizedMultivariateSummaryStatistics(int k, boolean isCovarianceBiasCorrected) { super(k, isCovarianceBiasCorrected); } /** * {@inheritDoc} */ @Override public synchronized void addValue(double[] value) throws DimensionMismatchException { super.addValue(value); } /** * {@inheritDoc} */ @Override public synchronized int getDimension() { return super.getDimension(); } /** * {@inheritDoc} */ @Override public synchronized long getN() { return super.getN(); } /** * {@inheritDoc} */ @Override public synchronized double[] getSum() { return super.getSum(); } /** * {@inheritDoc} */ @Override public synchronized double[] getSumSq() { return super.getSumSq(); } /** * {@inheritDoc} */ @Override public synchronized double[] getSumLog() { return super.getSumLog(); } /** * {@inheritDoc} */ @Override public synchronized double[] getMean() { return super.getMean(); } /** * {@inheritDoc} */ @Override public synchronized double[] getStandardDeviation() { return super.getStandardDeviation(); } /** * {@inheritDoc} */ @Override public synchronized RealMatrix getCovariance() { return super.getCovariance(); } /** * {@inheritDoc} */ @Override public synchronized double[] getMax() { return super.getMax(); } /** * {@inheritDoc} */ @Override public synchronized double[] getMin() { return super.getMin(); } /** * {@inheritDoc} */ @Override public synchronized double[] getGeometricMean() { return super.getGeometricMean(); } /** * {@inheritDoc} */ @Override public synchronized String toString() { return super.toString(); } /** * {@inheritDoc} */ @Override public synchronized void clear() { super.clear(); } /** * {@inheritDoc} */ @Override public synchronized boolean equals(Object object) { return super.equals(object); } /** * {@inheritDoc} */ @Override public synchronized int hashCode() { return super.hashCode(); } /** * {@inheritDoc} */ @Override public synchronized StorelessUnivariateStatistic[] getSumImpl() { return super.getSumImpl(); } /** * {@inheritDoc} */ @Override public synchronized void setSumImpl(StorelessUnivariateStatistic[] sumImpl) throws DimensionMismatchException { super.setSumImpl(sumImpl); } /** * {@inheritDoc} */ @Override public synchronized StorelessUnivariateStatistic[] getSumsqImpl() { return super.getSumsqImpl(); } /** * {@inheritDoc} */ @Override public synchronized void setSumsqImpl(StorelessUnivariateStatistic[] sumsqImpl) throws DimensionMismatchException { super.setSumsqImpl(sumsqImpl); } /** * {@inheritDoc} */ @Override public synchronized StorelessUnivariateStatistic[] getMinImpl() { return super.getMinImpl(); } /** * {@inheritDoc} */ @Override public synchronized void setMinImpl(StorelessUnivariateStatistic[] minImpl) throws DimensionMismatchException { super.setMinImpl(minImpl); } /** * {@inheritDoc} */ @Override public synchronized StorelessUnivariateStatistic[] getMaxImpl() { return super.getMaxImpl(); } /** * {@inheritDoc} */ @Override public synchronized void setMaxImpl(StorelessUnivariateStatistic[] maxImpl) throws DimensionMismatchException { super.setMaxImpl(maxImpl); } /** * {@inheritDoc} */ @Override public synchronized StorelessUnivariateStatistic[] getSumLogImpl() { return super.getSumLogImpl(); } /** * {@inheritDoc} */ @Override public synchronized void setSumLogImpl(StorelessUnivariateStatistic[] sumLogImpl) throws DimensionMismatchException { super.setSumLogImpl(sumLogImpl); } /** * {@inheritDoc} */ @Override public synchronized StorelessUnivariateStatistic[] getGeoMeanImpl() { return super.getGeoMeanImpl(); } /** * {@inheritDoc} */ @Override public synchronized void setGeoMeanImpl(StorelessUnivariateStatistic[] geoMeanImpl) throws DimensionMismatchException { super.setGeoMeanImpl(geoMeanImpl); } /** * {@inheritDoc} */ @Override public synchronized StorelessUnivariateStatistic[] getMeanImpl() { return super.getMeanImpl(); } /** * {@inheritDoc} */ @Override public synchronized void setMeanImpl(StorelessUnivariateStatistic[] meanImpl) throws DimensionMismatchException { super.setMeanImpl(meanImpl); } }
gpl-2.0
AcademicTorrents/AcademicTorrents-Downloader
vuze/org/gudy/azureus2/plugins/tracker/TrackerPeer.java
1249
/* * File : PeerKey.java * Created : 30 nov. 2003 * By : Olivier * * Azureus - a Java Bittorrent client * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details ( see the LICENSE file ). * * You should have received a copy of the GNU 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 org.gudy.azureus2.plugins.tracker; /** * @author Olivier * */ public interface TrackerPeer { public boolean isSeed(); public long getAmountLeft(); public long getDownloaded(); public long getUploaded(); public String getIP(); public int getPort(); public byte[] getPeerID(); /** * Raw value is as read, not InetAddress lookuped * @return */ public String getIPRaw(); }
gpl-2.0
karambir252/WordPress-Android
libs/utils/WordPressUtils/src/main/java/org/wordpress/android/util/helpers/MediaFile.java
10062
package org.wordpress.android.util.helpers; import android.text.TextUtils; import android.webkit.MimeTypeMap; import org.wordpress.android.util.MapUtils; import org.wordpress.android.util.StringUtils; import java.util.Date; import java.util.Map; public class MediaFile { protected int id; protected long postID; protected String filePath = null; //path of the file into disk protected String fileName = null; //name of the file into the server protected String title = null; protected String description = null; protected String caption = null; protected int horizontalAlignment; //0 = none, 1 = left, 2 = center, 3 = right protected boolean verticalAligment = false; //false = bottom, true = top protected int width = 500, height; protected String mimeType = ""; protected String videoPressShortCode = null; protected boolean featured = false; protected boolean isVideo = false; protected boolean featuredInPost; protected String fileURL = null; // url of the file to download protected String thumbnailURL = null; // url of the thumbnail to download private String blogId; private long dateCreatedGmt; private String uploadState = null; private String mediaId; public static String VIDEOPRESS_SHORTCODE_ID = "videopress_shortcode"; public MediaFile(String blogId, Map<?, ?> resultMap, boolean isDotCom) { setBlogId(blogId); setMediaId(MapUtils.getMapStr(resultMap, "attachment_id")); setPostID(MapUtils.getMapLong(resultMap, "parent")); setTitle(MapUtils.getMapStr(resultMap, "title")); setCaption(MapUtils.getMapStr(resultMap, "caption")); setDescription(MapUtils.getMapStr(resultMap, "description")); setVideoPressShortCode(MapUtils.getMapStr(resultMap, VIDEOPRESS_SHORTCODE_ID)); // get the file name from the link String link = MapUtils.getMapStr(resultMap, "link"); setFileName(new String(link).replaceAll("^.*/([A-Za-z0-9_-]+)\\.\\w+$", "$1")); String fileType = new String(link).replaceAll(".*\\.(\\w+)$", "$1").toLowerCase(); String fileMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileType); setMimeType(fileMimeType); // make the file urls be https://... so that we can get these images with oauth when the blogs are private // assume no https for images in self-hosted blogs String fileUrl = MapUtils.getMapStr(resultMap, "link"); if (isDotCom) { fileUrl = fileUrl.replace("http:", "https:"); } setFileURL(fileUrl); String thumbnailURL = MapUtils.getMapStr(resultMap, "thumbnail"); if (thumbnailURL.startsWith("http")) { if (isDotCom) { thumbnailURL = thumbnailURL.replace("http:", "https:"); } setThumbnailURL(thumbnailURL); } Date date = MapUtils.getMapDate(resultMap, "date_created_gmt"); if (date != null) { setDateCreatedGMT(date.getTime()); } Object meta = resultMap.get("metadata"); if (meta != null && meta instanceof Map) { Map<?, ?> metadata = (Map<?, ?>) meta; setWidth(MapUtils.getMapInt(metadata, "width")); setHeight(MapUtils.getMapInt(metadata, "height")); } } public MediaFile() { // default constructor } public MediaFile(MediaFile mediaFile) { this.id = mediaFile.id; this.postID = mediaFile.postID; this.filePath = mediaFile.filePath; this.fileName = mediaFile.fileName; this.title = mediaFile.title; this.description = mediaFile.description; this.caption = mediaFile.caption; this.horizontalAlignment = mediaFile.horizontalAlignment; this.verticalAligment = mediaFile.verticalAligment; this.width = mediaFile.width; this.height = mediaFile.height; this.mimeType = mediaFile.mimeType; this.videoPressShortCode = mediaFile.videoPressShortCode; this.featured = mediaFile.featured; this.isVideo = mediaFile.isVideo; this.featuredInPost = mediaFile.featuredInPost; this.fileURL = mediaFile.fileURL; this.thumbnailURL = mediaFile.thumbnailURL; this.blogId = mediaFile.blogId; this.dateCreatedGmt = mediaFile.dateCreatedGmt; this.uploadState = mediaFile.uploadState; this.mediaId = mediaFile.mediaId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMediaId() { return mediaId; } public void setMediaId(String id) { mediaId = id; } public boolean isFeatured() { return featured; } public void setFeatured(boolean featured) { this.featured = featured; } public long getPostID() { return postID; } public void setPostID(long postID) { this.postID = postID; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getFileURL() { return fileURL; } public void setFileURL(String fileURL) { this.fileURL = fileURL; } public String getThumbnailURL() { return thumbnailURL; } public void setThumbnailURL(String thumbnailURL) { this.thumbnailURL = thumbnailURL; } public boolean isVerticalAlignmentOnTop() { return verticalAligment; } public void setVerticalAlignmentOnTop(boolean verticalAligment) { this.verticalAligment = verticalAligment; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getMimeType() { return StringUtils.notNullStr(mimeType); } public void setMimeType(String type) { mimeType = StringUtils.notNullStr(type); } public String getVideoPressShortCode() { return videoPressShortCode; } public void setVideoPressShortCode(String videoPressShortCode) { this.videoPressShortCode = videoPressShortCode; } public int getHorizontalAlignment() { return horizontalAlignment; } public void setHorizontalAlignment(int horizontalAlignment) { this.horizontalAlignment = horizontalAlignment; } public boolean isVideo() { return isVideo; } public void setVideo(boolean isVideo) { this.isVideo = isVideo; } public boolean isFeaturedInPost() { return featuredInPost; } public void setFeaturedInPost(boolean featuredInPost) { this.featuredInPost = featuredInPost; } public String getBlogId() { return blogId; } public void setBlogId(String blogId) { this.blogId = blogId; } public void setDateCreatedGMT(long date_created_gmt) { this.dateCreatedGmt = date_created_gmt; } public long getDateCreatedGMT() { return dateCreatedGmt; } public void setUploadState(String uploadState) { this.uploadState = uploadState; } public String getUploadState() { return uploadState; } /** * Outputs the Html for an image * If a fullSizeUrl exists, a link will be created to it from the resizedPictureUrl */ public String getImageHtmlForUrls(String fullSizeUrl, String resizedPictureURL, boolean shouldAddImageWidthCSS) { String alignment = ""; switch (getHorizontalAlignment()) { case 0: alignment = "alignnone"; break; case 1: alignment = "alignleft"; break; case 2: alignment = "aligncenter"; break; case 3: alignment = "alignright"; break; } String alignmentCSS = "class=\"" + alignment + " size-full\" "; if (shouldAddImageWidthCSS) { alignmentCSS += "style=\"max-width: " + getWidth() + "px\" "; } // Check if we uploaded a featured picture that is not added to the Post content (normal case) if ((fullSizeUrl != null && fullSizeUrl.equalsIgnoreCase("")) || (resizedPictureURL != null && resizedPictureURL.equalsIgnoreCase(""))) { return ""; // Not featured in Post. Do not add to the content. } if (fullSizeUrl == null && resizedPictureURL != null) { fullSizeUrl = resizedPictureURL; } else if (fullSizeUrl != null && resizedPictureURL == null) { resizedPictureURL = fullSizeUrl; } String mediaTitle = StringUtils.notNullStr(getTitle()); String content = String.format("<a href=\"%s\"><img title=\"%s\" %s alt=\"image\" src=\"%s\" /></a>", fullSizeUrl, mediaTitle, alignmentCSS, resizedPictureURL); if (!TextUtils.isEmpty(getCaption())) { content = String.format("[caption id=\"\" align=\"%s\" width=\"%d\"]%s%s[/caption]", alignment, getWidth(), content, TextUtils.htmlEncode(getCaption())); } return content; } }
gpl-2.0
unofficial-opensource-apple/gcc_40
libjava/javax/print/attribute/HashAttributeSet.java
10110
/* HashAttributeSet.java -- Copyright (C) 2003, 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.print.attribute; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; public class HashAttributeSet implements AttributeSet, Serializable { private static final long serialVersionUID = 5311560590283707917L; private Class interfaceName; private HashMap attributeMap = new HashMap(); /** * Creates an empty <code>HashAttributeSet</code> object. */ public HashAttributeSet() { this(Attribute.class); } /** * Creates a <code>HashAttributeSet</code> object with the given * attribute in it. * * @param attribute the attribute to put into the set * * @exception NullPointerException if attribute is null */ public HashAttributeSet(Attribute attribute) { this(attribute, Attribute.class); } /** * Creates a <code>HashAttributeSet</code> object with the given * attributes in it. * * @param attributes the attributes to put into the set * * @exception NullPointerException If attributes is null */ public HashAttributeSet(Attribute[] attributes) { this(attributes, Attribute.class); } /** * Creates a <code>HashAttributeSet</code> object with the given * attributes in it. * * @param attributes the attributes to put into the set * * @exception NullPointerException If attributes is null */ public HashAttributeSet(AttributeSet attributes) { this(attributes, Attribute.class); } /** * Creates an empty <code>HashAttributeSet</code> object. * * @param interfaceName the interface that all members must implement * * @exception NullPointerException if interfaceName is null */ protected HashAttributeSet(Class interfaceName) { if (interfaceName == null) throw new NullPointerException("interfaceName may not be null"); this.interfaceName = interfaceName; } /** * Creates an empty <code>HashAttributeSet</code> object. * * @exception ClassCastException if attribute is not an interface of * interfaceName * @exception NullPointerException if attribute or interfaceName is null */ protected HashAttributeSet(Attribute attribute, Class interfaceName) { this(interfaceName); if (attribute == null) throw new NullPointerException(); addInternal(attribute, interfaceName); } /** * Creates an empty <code>HashAttributeSet</code> object. * * @exception ClassCastException if any element of attributes is not an * interface of interfaceName * @exception NullPointerException if attributes or interfaceName is null */ protected HashAttributeSet(Attribute[] attributes, Class interfaceName) { this(interfaceName); if (attributes == null) throw new NullPointerException(); for (int index = 0; index < attributes.length; index++) addInternal(attributes[index], interfaceName); } /** * Creates an empty <code>HashAttributeSet</code> object. * * @exception ClassCastException if any element of attributes is not an * interface of interfaceName */ protected HashAttributeSet(AttributeSet attributes, Class interfaceName) { this(interfaceName); if (attributes != null) addAllInternal(attributes, interfaceName); } /** * Adds the given attribute to the set. * * @param attribute the attribute to add * * @return true if the attribute set has changed, false otherwise * * @exception NullPointerException if attribute is null * @exception UnmodifiableSetException if this attribute set does not * support this action. */ public boolean add(Attribute attribute) { return addInternal(attribute, interfaceName); } private boolean addInternal(Attribute attribute, Class interfaceName) { if (attribute == null) throw new NullPointerException("attribute may not be null"); AttributeSetUtilities.verifyAttributeCategory(interfaceName, this.interfaceName); Object old = attributeMap.put (attribute.getCategory(), AttributeSetUtilities.verifyAttributeValue (attribute, interfaceName)); return !attribute.equals(old); } /** * Adds the given attributes to the set. * * @param attributes the attributes to add * * @return true if the attribute set has changed, false otherwise * * @exception UnmodifiableSetException if this attribute set does not * support this action. */ public boolean addAll(AttributeSet attributes) { return addAllInternal(attributes, interfaceName); } private boolean addAllInternal(AttributeSet attributes, Class interfaceName) { boolean modified = false; Attribute[] array = attributes.toArray(); for (int index = 0; index < array.length; index++) if (addInternal(array[index], interfaceName)) modified = true; return modified; } /** * Removes all attributes from this attribute set. * * @exception UnmodifiableSetException if this attribute set does not * support this action. */ public void clear() { attributeMap.clear(); } /** * Checks if this attribute set contains an entry with the given category. * * @param category the category to test for * * @return true if the category exists in this attribute set, false otherwise. */ public boolean containsKey(Class category) { return attributeMap.containsKey(category); } /** * Checks if this attribute set contains an entry with the given attribute. * * @param attribute the attribute to test for * * @return true if the attribute exists in this attribute set, * false otherwise. */ public boolean containsValue(Attribute attribute) { return attributeMap.containsValue(attribute); } /** * Tests of obj is equal to this object. * * @param obj the object to test * * @return true if both objects are equal, false otherwise. */ public boolean equals(Object obj) { if (! (obj instanceof HashAttributeSet)) return false; return attributeMap.equals(((HashAttributeSet) obj).attributeMap); } /** * Returns the attribute value that is connected to the given attribute * category. If the attribute set does not contains the given category null * will be returned. * * @param category the attribute category to return the attribute value for * * @return the attribute associated to category, or null */ public Attribute get(Class category) { return (Attribute) attributeMap.get(category); } /** * Returns the hashcode for this object. * * @return the hashcode */ public int hashCode() { return attributeMap.hashCode() + interfaceName.hashCode(); } /** * Checks if the attribute set is empty. * * @return true if the attribute set is empty, false otherwise */ public boolean isEmpty() { return attributeMap.isEmpty(); } /** * Removes the entry with the given attribute in it. * * @param attribute the attribute value of the entry to be removed * * @return true if the attribute set has changed, false otherwise. * * @exception UnmodifiableSetException if this attribute set does not * support this action. */ public boolean remove(Attribute attribute) { if (attribute == null) return false; return attributeMap.remove(attribute.getCategory()) != null; } /** * Removes the entry with the given category in it. * * @param category the category value of the entry to be removed * * @return true if the attribute set has changed, false otherwise. */ public boolean remove(Class category) { if (category == null) return false; return attributeMap.remove(category) != null; } /** * Returns the number of elements in this attribute set. * * @return the number of elements. */ public int size() { return attributeMap.size(); } /** * Returns the content of the attribute set as an array * * @return an array of attributes */ public Attribute[] toArray() { int index = 0; Iterator it = attributeMap.entrySet().iterator(); Attribute[] array = new Attribute[size()]; while (it.hasNext()) { array[index] = (Attribute) it.next(); index++; } return array; } }
gpl-2.0
jacek-lewandowski/jmh-jl
jmh-core/src/main/java/org/openjdk/jmh/runner/ActionPlan.java
2319
/* * Copyright (c) 2005, 2013, 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. */ package org.openjdk.jmh.runner; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ActionPlan implements Serializable { private static final long serialVersionUID = 7250784375093638099L; private final List<Action> actions; private final ActionType type; public ActionPlan(ActionType type) { this.type = type; actions = new ArrayList<Action>(); } public ActionType getType() { return type; } public void add(Action action) { actions.add(action); } public void mixIn(ActionPlan other) { actions.addAll(other.actions); } public List<Action> getActions() { return actions; } public List<Action> getMeasurementActions() { List<Action> result = new ArrayList<Action>(); for (Action action : actions) { switch (action.getMode()) { case MEASUREMENT: case WARMUP_MEASUREMENT: result.add(action); break; } } return result; } }
gpl-2.0
graalvm/graal-core
graal/org.graalvm.compiler.core.sparc/src/org/graalvm/compiler/core/sparc/SPARCNodeMatchRules.java
7780
/* * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.core.sparc; import static jdk.vm.ci.sparc.SPARCKind.BYTE; import static jdk.vm.ci.sparc.SPARCKind.HWORD; import static jdk.vm.ci.sparc.SPARCKind.WORD; import static jdk.vm.ci.sparc.SPARCKind.XWORD; import org.graalvm.compiler.core.common.LIRKind; import org.graalvm.compiler.core.common.calc.Condition; import org.graalvm.compiler.core.gen.NodeMatchRules; import org.graalvm.compiler.core.match.ComplexMatchResult; import org.graalvm.compiler.core.match.MatchRule; import org.graalvm.compiler.debug.GraalError; import org.graalvm.compiler.lir.LIRFrameState; import org.graalvm.compiler.lir.LabelRef; import org.graalvm.compiler.lir.gen.LIRGeneratorTool; import org.graalvm.compiler.lir.sparc.SPARCAddressValue; import org.graalvm.compiler.nodes.DeoptimizingNode; import org.graalvm.compiler.nodes.IfNode; import org.graalvm.compiler.nodes.ValueNode; import org.graalvm.compiler.nodes.calc.CompareNode; import org.graalvm.compiler.nodes.calc.SignExtendNode; import org.graalvm.compiler.nodes.calc.ZeroExtendNode; import org.graalvm.compiler.nodes.java.LogicCompareAndSwapNode; import org.graalvm.compiler.nodes.memory.Access; import org.graalvm.compiler.nodes.memory.LIRLowerableAccess; import jdk.vm.ci.meta.JavaConstant; import jdk.vm.ci.meta.Value; import jdk.vm.ci.sparc.SPARCKind; /** * This class implements the SPARC specific portion of the LIR generator. */ public class SPARCNodeMatchRules extends NodeMatchRules { public SPARCNodeMatchRules(LIRGeneratorTool gen) { super(gen); } protected LIRFrameState getState(Access access) { if (access instanceof DeoptimizingNode) { return state((DeoptimizingNode) access); } return null; } protected LIRKind getLirKind(LIRLowerableAccess access) { return gen.getLIRKind(access.getAccessStamp()); } private ComplexMatchResult emitSignExtendMemory(Access access, int fromBits, int toBits) { assert fromBits <= toBits && toBits <= 64; SPARCKind toKind = null; SPARCKind fromKind = null; if (fromBits == toBits) { return null; } toKind = toBits > 32 ? XWORD : WORD; switch (fromBits) { case 8: fromKind = BYTE; break; case 16: fromKind = HWORD; break; case 32: fromKind = WORD; break; default: throw GraalError.unimplemented("unsupported sign extension (" + fromBits + " bit -> " + toBits + " bit)"); } SPARCKind localFromKind = fromKind; SPARCKind localToKind = toKind; return builder -> { return getLIRGeneratorTool().emitSignExtendLoad(LIRKind.value(localFromKind), LIRKind.value(localToKind), operand(access.getAddress()), getState(access)); }; } private ComplexMatchResult emitZeroExtendMemory(Access access, int fromBits, int toBits) { assert fromBits <= toBits && toBits <= 64; SPARCKind toKind = null; SPARCKind fromKind = null; if (fromBits == toBits) { return null; } toKind = toBits > 32 ? XWORD : WORD; switch (fromBits) { case 8: fromKind = BYTE; break; case 16: fromKind = HWORD; break; case 32: fromKind = WORD; break; default: throw GraalError.unimplemented("unsupported sign extension (" + fromBits + " bit -> " + toBits + " bit)"); } SPARCKind localFromKind = fromKind; SPARCKind localToKind = toKind; return builder -> { // Loads are always zero extending load return getLIRGeneratorTool().emitZeroExtendLoad(LIRKind.value(localFromKind), LIRKind.value(localToKind), operand(access.getAddress()), getState(access)); }; } @MatchRule("(SignExtend Read=access)") @MatchRule("(SignExtend FloatingRead=access)") public ComplexMatchResult signExtend(SignExtendNode root, Access access) { return emitSignExtendMemory(access, root.getInputBits(), root.getResultBits()); } @MatchRule("(ZeroExtend Read=access)") @MatchRule("(ZeroExtend FloatingRead=access)") public ComplexMatchResult zeroExtend(ZeroExtendNode root, Access access) { return emitZeroExtendMemory(access, root.getInputBits(), root.getResultBits()); } @MatchRule("(If (ObjectEquals=compare value LogicCompareAndSwap=cas))") @MatchRule("(If (PointerEquals=compare value LogicCompareAndSwap=cas))") @MatchRule("(If (FloatEquals=compare value LogicCompareAndSwap=cas))") @MatchRule("(If (IntegerEquals=compare value LogicCompareAndSwap=cas))") public ComplexMatchResult ifCompareLogicCas(IfNode root, CompareNode compare, ValueNode value, LogicCompareAndSwapNode cas) { JavaConstant constant = value.asJavaConstant(); assert compare.condition() == Condition.EQ; if (constant != null && cas.usages().count() == 1) { long constantValue = constant.asLong(); boolean successIsTrue; if (constantValue == 0) { successIsTrue = false; } else if (constantValue == 1) { successIsTrue = true; } else { return null; } return builder -> { LIRKind kind = getLirKind(cas); LabelRef trueLabel = getLIRBlock(root.trueSuccessor()); LabelRef falseLabel = getLIRBlock(root.falseSuccessor()); double trueLabelProbability = root.probability(root.trueSuccessor()); Value expectedValue = operand(cas.getExpectedValue()); Value newValue = operand(cas.getNewValue()); SPARCAddressValue address = (SPARCAddressValue) operand(cas.getAddress()); Condition condition = successIsTrue ? Condition.EQ : Condition.NE; Value result = getLIRGeneratorTool().emitValueCompareAndSwap(address, expectedValue, newValue); getLIRGeneratorTool().emitCompareBranch(kind.getPlatformKind(), result, expectedValue, condition, false, trueLabel, falseLabel, trueLabelProbability); return null; }; } return null; } @Override public SPARCLIRGenerator getLIRGeneratorTool() { return (SPARCLIRGenerator) super.getLIRGeneratorTool(); } protected SPARCArithmeticLIRGenerator getArithmeticLIRGenerator() { return (SPARCArithmeticLIRGenerator) getLIRGeneratorTool().getArithmetic(); } }
gpl-2.0
smarr/graal
graal/com.oracle.graal.api.meta/src/com/oracle/graal/api/meta/RawConstant.java
1301
/* * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.api.meta; public class RawConstant extends PrimitiveConstant { private static final long serialVersionUID = -242269518888560348L; public RawConstant(long rawValue) { super(Kind.Int, rawValue); } }
gpl-2.0
166MMX/openjdk.java.net-openjfx-8u40-rt
apps/scenebuilder/SceneBuilderKit/src/com/oracle/javafx/scenebuilder/kit/editor/search/SearchController.java
3709
/* * Copyright (c) 2012, 2014, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * - Neither the name of Oracle Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.oracle.javafx.scenebuilder.kit.editor.search; import com.oracle.javafx.scenebuilder.kit.editor.EditorController; import com.oracle.javafx.scenebuilder.kit.editor.panel.util.AbstractFxmlController; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.fxml.FXML; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.StackPane; /** * * */ public class SearchController extends AbstractFxmlController { @FXML private TextField searchField; // This StackPane contains the searchImage. @FXML private StackPane searchIcon; public SearchController(EditorController c) { super(SearchController.class.getResource("Search.fxml"), c); //NOI18N } public final StringProperty textProperty() { return searchField.textProperty(); } public void requestFocus() { searchField.requestFocus(); } @Override protected void controllerDidLoadFxml() { if (searchField.getLength() == 0) { searchIcon.getStyleClass().add("search-magnifying-glass"); //NOI18N } // For SQE tests searchField.setId("Search Text"); //NOI18N searchField.textProperty().addListener((ChangeListener<String>) (ov, oldStr, newStr) -> { if (newStr.isEmpty()) { searchIcon.getStyleClass().clear(); searchIcon.getStyleClass().add("search-magnifying-glass"); //NOI18N } else { searchIcon.getStyleClass().clear(); searchIcon.getStyleClass().add("search-clear"); //NOI18N } }); searchField.addEventHandler(KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.ESCAPE) { searchField.clear(); } }); searchIcon.setOnMouseClicked(t -> searchField.clear()); } }
gpl-2.0
lostdj/Jaklin-OpenJDK-JDK
test/javax/swing/JCheckBox/4449413/bug4449413.java
3991
/* * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test * @bug 4449413 * @summary Tests that checkbox and radiobuttons' check marks are visible when background is black * @author Ilya Boyandin * @library ../../../../lib/testlibrary * @build jdk.testlibrary.OSInfo * @run applet/manual=yesno bug4449413.html */ import javax.swing.*; import javax.swing.plaf.metal.*; import java.awt.event.*; import java.awt.*; import jdk.testlibrary.OSInfo; public class bug4449413 extends JApplet { @Override public void init() { try { if (OSInfo.getOSType() == OSInfo.OSType.MACOSX) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } final MetalTheme oceanTheme = (MetalTheme) sun.awt.AppContext.getAppContext().get("currentMetalTheme"); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { getContentPane().setLayout(new FlowLayout()); final JPanel panel = new JPanel(); JCheckBox box = new JCheckBox("Use Ocean theme", true); getContentPane().add(box); box.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { MetalLookAndFeel.setCurrentTheme(oceanTheme); } else { MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); } SwingUtilities.updateComponentTreeUI(panel); } }); getContentPane().add(panel); panel.setLayout(new GridLayout(4, 6, 10, 15)); for (int k = 0; k <= 3; k++) { for (int j = 1; j >= 0; j--) { AbstractButton b = createButton(j, k); panel.add(b); } } } }); } catch (Exception e) { throw new RuntimeException(e); } } static AbstractButton createButton(int enabled, int type) { AbstractButton b = null; switch (type) { case 0: b = new JRadioButton("RadioButton"); break; case 1: b = new JCheckBox("CheckBox"); break; case 2: b = new JRadioButtonMenuItem("RBMenuItem"); break; case 3: b = new JCheckBoxMenuItem("CBMenuItem"); break; } b.setBackground(Color.black); b.setForeground(Color.white); b.setEnabled(enabled == 1); b.setSelected(true); return b; } }
gpl-2.0
GiGatR00n/Aion-Core-v4.7.5
AC-Game/src/com/aionemu/gameserver/skillengine/effect/ResurrectPositionalEffect.java
2747
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package com.aionemu.gameserver.skillengine.effect; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_RESURRECT; import com.aionemu.gameserver.skillengine.model.Effect; import com.aionemu.gameserver.utils.PacketSendUtility; /** * @author Sippolo */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ResurrectPositionalEffect") public class ResurrectPositionalEffect extends ResurrectEffect { @Override public void applyEffect(Effect effect) { Player effector = (Player) effect.getEffector(); Player effected = (Player) effect.getEffected(); effected.setPlayerResActivate(true); effected.setResurrectionSkill(skillId); PacketSendUtility.sendPacket(effected, new SM_RESURRECT(effect.getEffector(), effect.getSkillId())); effected.setResPosState(true); effected.setResPosX(effector.getX()); effected.setResPosY(effector.getY()); effected.setResPosZ(effector.getZ()); } @Override public void calculate(Effect effect) { if ((effect.getEffector() instanceof Player) && (effect.getEffected() instanceof Player) && (effect.getEffected().getLifeStats().isAlreadyDead())) { super.calculate(effect, null, null); } } }
gpl-2.0
JetBrains/jdk8u_jaxp
src/com/sun/org/apache/xpath/internal/res/XPATHErrorResources_sv.java
40548
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xpath.internal.res; import java.util.ListResourceBundle; /** * Set up error messages. * We build a two dimensional array of message keys and * message strings. In order to add a new message here, * you need to first add a Static string constant for the * Key and update the contents array with Key, Value pair * Also you need to update the count of messages(MAX_CODE)or * the count of warnings(MAX_WARNING) [ Information purpose only] * @xsl.usage advanced */ public class XPATHErrorResources_sv extends ListResourceBundle { /* * General notes to translators: * * This file contains error and warning messages related to XPath Error * Handling. * * 1) Xalan (or more properly, Xalan-interpretive) and XSLTC are names of * components. * XSLT is an acronym for "XML Stylesheet Language: Transformations". * XSLTC is an acronym for XSLT Compiler. * * 2) A stylesheet is a description of how to transform an input XML document * into a resultant XML document (or HTML document or text). The * stylesheet itself is described in the form of an XML document. * * 3) A template is a component of a stylesheet that is used to match a * particular portion of an input document and specifies the form of the * corresponding portion of the output document. * * 4) An element is a mark-up tag in an XML document; an attribute is a * modifier on the tag. For example, in <elem attr='val' attr2='val2'> * "elem" is an element name, "attr" and "attr2" are attribute names with * the values "val" and "val2", respectively. * * 5) A namespace declaration is a special attribute that is used to associate * a prefix with a URI (the namespace). The meanings of element names and * attribute names that use that prefix are defined with respect to that * namespace. * * 6) "Translet" is an invented term that describes the class file that * results from compiling an XML stylesheet into a Java class. * * 7) XPath is a specification that describes a notation for identifying * nodes in a tree-structured representation of an XML document. An * instance of that notation is referred to as an XPath expression. * * 8) The context node is the node in the document with respect to which an * XPath expression is being evaluated. * * 9) An iterator is an object that traverses nodes in the tree, one at a time. * * 10) NCName is an XML term used to describe a name that does not contain a * colon (a "no-colon name"). * * 11) QName is an XML term meaning "qualified name". */ /* * static variables */ public static final String ERROR0000 = "ERROR0000"; public static final String ER_CURRENT_NOT_ALLOWED_IN_MATCH = "ER_CURRENT_NOT_ALLOWED_IN_MATCH"; public static final String ER_CURRENT_TAKES_NO_ARGS = "ER_CURRENT_TAKES_NO_ARGS"; public static final String ER_DOCUMENT_REPLACED = "ER_DOCUMENT_REPLACED"; public static final String ER_CONTEXT_HAS_NO_OWNERDOC = "ER_CONTEXT_HAS_NO_OWNERDOC"; public static final String ER_LOCALNAME_HAS_TOO_MANY_ARGS = "ER_LOCALNAME_HAS_TOO_MANY_ARGS"; public static final String ER_NAMESPACEURI_HAS_TOO_MANY_ARGS = "ER_NAMESPACEURI_HAS_TOO_MANY_ARGS"; public static final String ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS = "ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS"; public static final String ER_NUMBER_HAS_TOO_MANY_ARGS = "ER_NUMBER_HAS_TOO_MANY_ARGS"; public static final String ER_NAME_HAS_TOO_MANY_ARGS = "ER_NAME_HAS_TOO_MANY_ARGS"; public static final String ER_STRING_HAS_TOO_MANY_ARGS = "ER_STRING_HAS_TOO_MANY_ARGS"; public static final String ER_STRINGLENGTH_HAS_TOO_MANY_ARGS = "ER_STRINGLENGTH_HAS_TOO_MANY_ARGS"; public static final String ER_TRANSLATE_TAKES_3_ARGS = "ER_TRANSLATE_TAKES_3_ARGS"; public static final String ER_UNPARSEDENTITYURI_TAKES_1_ARG = "ER_UNPARSEDENTITYURI_TAKES_1_ARG"; public static final String ER_NAMESPACEAXIS_NOT_IMPLEMENTED = "ER_NAMESPACEAXIS_NOT_IMPLEMENTED"; public static final String ER_UNKNOWN_AXIS = "ER_UNKNOWN_AXIS"; public static final String ER_UNKNOWN_MATCH_OPERATION = "ER_UNKNOWN_MATCH_OPERATION"; public static final String ER_INCORRECT_ARG_LENGTH ="ER_INCORRECT_ARG_LENGTH"; public static final String ER_CANT_CONVERT_TO_NUMBER = "ER_CANT_CONVERT_TO_NUMBER"; public static final String ER_CANT_CONVERT_XPATHRESULTTYPE_TO_NUMBER = "ER_CANT_CONVERT_XPATHRESULTTYPE_TO_NUMBER"; public static final String ER_CANT_CONVERT_TO_NODELIST = "ER_CANT_CONVERT_TO_NODELIST"; public static final String ER_CANT_CONVERT_TO_MUTABLENODELIST = "ER_CANT_CONVERT_TO_MUTABLENODELIST"; public static final String ER_CANT_CONVERT_TO_TYPE ="ER_CANT_CONVERT_TO_TYPE"; public static final String ER_EXPECTED_MATCH_PATTERN = "ER_EXPECTED_MATCH_PATTERN"; public static final String ER_COULDNOT_GET_VAR_NAMED = "ER_COULDNOT_GET_VAR_NAMED"; public static final String ER_UNKNOWN_OPCODE = "ER_UNKNOWN_OPCODE"; public static final String ER_EXTRA_ILLEGAL_TOKENS ="ER_EXTRA_ILLEGAL_TOKENS"; public static final String ER_EXPECTED_DOUBLE_QUOTE = "ER_EXPECTED_DOUBLE_QUOTE"; public static final String ER_EXPECTED_SINGLE_QUOTE = "ER_EXPECTED_SINGLE_QUOTE"; public static final String ER_EMPTY_EXPRESSION = "ER_EMPTY_EXPRESSION"; public static final String ER_EXPECTED_BUT_FOUND = "ER_EXPECTED_BUT_FOUND"; public static final String ER_INCORRECT_PROGRAMMER_ASSERTION = "ER_INCORRECT_PROGRAMMER_ASSERTION"; public static final String ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL = "ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL"; public static final String ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG = "ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG"; public static final String ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG = "ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG"; public static final String ER_PREDICATE_ILLEGAL_SYNTAX = "ER_PREDICATE_ILLEGAL_SYNTAX"; public static final String ER_ILLEGAL_AXIS_NAME = "ER_ILLEGAL_AXIS_NAME"; public static final String ER_UNKNOWN_NODETYPE = "ER_UNKNOWN_NODETYPE"; public static final String ER_PATTERN_LITERAL_NEEDS_BE_QUOTED = "ER_PATTERN_LITERAL_NEEDS_BE_QUOTED"; public static final String ER_COULDNOT_BE_FORMATTED_TO_NUMBER = "ER_COULDNOT_BE_FORMATTED_TO_NUMBER"; public static final String ER_COULDNOT_CREATE_XMLPROCESSORLIAISON = "ER_COULDNOT_CREATE_XMLPROCESSORLIAISON"; public static final String ER_DIDNOT_FIND_XPATH_SELECT_EXP = "ER_DIDNOT_FIND_XPATH_SELECT_EXP"; public static final String ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH = "ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH"; public static final String ER_ERROR_OCCURED = "ER_ERROR_OCCURED"; public static final String ER_ILLEGAL_VARIABLE_REFERENCE = "ER_ILLEGAL_VARIABLE_REFERENCE"; public static final String ER_AXES_NOT_ALLOWED = "ER_AXES_NOT_ALLOWED"; public static final String ER_KEY_HAS_TOO_MANY_ARGS = "ER_KEY_HAS_TOO_MANY_ARGS"; public static final String ER_COUNT_TAKES_1_ARG = "ER_COUNT_TAKES_1_ARG"; public static final String ER_COULDNOT_FIND_FUNCTION = "ER_COULDNOT_FIND_FUNCTION"; public static final String ER_UNSUPPORTED_ENCODING ="ER_UNSUPPORTED_ENCODING"; public static final String ER_PROBLEM_IN_DTM_NEXTSIBLING = "ER_PROBLEM_IN_DTM_NEXTSIBLING"; public static final String ER_CANNOT_WRITE_TO_EMPTYNODELISTIMPL = "ER_CANNOT_WRITE_TO_EMPTYNODELISTIMPL"; public static final String ER_SETDOMFACTORY_NOT_SUPPORTED = "ER_SETDOMFACTORY_NOT_SUPPORTED"; public static final String ER_PREFIX_MUST_RESOLVE = "ER_PREFIX_MUST_RESOLVE"; public static final String ER_PARSE_NOT_SUPPORTED = "ER_PARSE_NOT_SUPPORTED"; public static final String ER_SAX_API_NOT_HANDLED = "ER_SAX_API_NOT_HANDLED"; public static final String ER_IGNORABLE_WHITESPACE_NOT_HANDLED = "ER_IGNORABLE_WHITESPACE_NOT_HANDLED"; public static final String ER_DTM_CANNOT_HANDLE_NODES = "ER_DTM_CANNOT_HANDLE_NODES"; public static final String ER_XERCES_CANNOT_HANDLE_NODES = "ER_XERCES_CANNOT_HANDLE_NODES"; public static final String ER_XERCES_PARSE_ERROR_DETAILS = "ER_XERCES_PARSE_ERROR_DETAILS"; public static final String ER_XERCES_PARSE_ERROR = "ER_XERCES_PARSE_ERROR"; public static final String ER_INVALID_UTF16_SURROGATE = "ER_INVALID_UTF16_SURROGATE"; public static final String ER_OIERROR = "ER_OIERROR"; public static final String ER_CANNOT_CREATE_URL = "ER_CANNOT_CREATE_URL"; public static final String ER_XPATH_READOBJECT = "ER_XPATH_READOBJECT"; public static final String ER_FUNCTION_TOKEN_NOT_FOUND = "ER_FUNCTION_TOKEN_NOT_FOUND"; public static final String ER_CANNOT_DEAL_XPATH_TYPE = "ER_CANNOT_DEAL_XPATH_TYPE"; public static final String ER_NODESET_NOT_MUTABLE = "ER_NODESET_NOT_MUTABLE"; public static final String ER_NODESETDTM_NOT_MUTABLE = "ER_NODESETDTM_NOT_MUTABLE"; /** Variable not resolvable: */ public static final String ER_VAR_NOT_RESOLVABLE = "ER_VAR_NOT_RESOLVABLE"; /** Null error handler */ public static final String ER_NULL_ERROR_HANDLER = "ER_NULL_ERROR_HANDLER"; /** Programmer's assertion: unknown opcode */ public static final String ER_PROG_ASSERT_UNKNOWN_OPCODE = "ER_PROG_ASSERT_UNKNOWN_OPCODE"; /** 0 or 1 */ public static final String ER_ZERO_OR_ONE = "ER_ZERO_OR_ONE"; /** rtf() not supported by XRTreeFragSelectWrapper */ public static final String ER_RTF_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER = "ER_RTF_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER"; /** asNodeIterator() not supported by XRTreeFragSelectWrapper */ public static final String ER_ASNODEITERATOR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER = "ER_ASNODEITERATOR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER"; /** fsb() not supported for XStringForChars */ public static final String ER_FSB_NOT_SUPPORTED_XSTRINGFORCHARS = "ER_FSB_NOT_SUPPORTED_XSTRINGFORCHARS"; /** Could not find variable with the name of */ public static final String ER_COULD_NOT_FIND_VAR = "ER_COULD_NOT_FIND_VAR"; /** XStringForChars can not take a string for an argument */ public static final String ER_XSTRINGFORCHARS_CANNOT_TAKE_STRING = "ER_XSTRINGFORCHARS_CANNOT_TAKE_STRING"; /** The FastStringBuffer argument can not be null */ public static final String ER_FASTSTRINGBUFFER_CANNOT_BE_NULL = "ER_FASTSTRINGBUFFER_CANNOT_BE_NULL"; /** 2 or 3 */ public static final String ER_TWO_OR_THREE = "ER_TWO_OR_THREE"; /** Variable accessed before it is bound! */ public static final String ER_VARIABLE_ACCESSED_BEFORE_BIND = "ER_VARIABLE_ACCESSED_BEFORE_BIND"; /** XStringForFSB can not take a string for an argument! */ public static final String ER_FSB_CANNOT_TAKE_STRING = "ER_FSB_CANNOT_TAKE_STRING"; /** Error! Setting the root of a walker to null! */ public static final String ER_SETTING_WALKER_ROOT_TO_NULL = "ER_SETTING_WALKER_ROOT_TO_NULL"; /** This NodeSetDTM can not iterate to a previous node! */ public static final String ER_NODESETDTM_CANNOT_ITERATE = "ER_NODESETDTM_CANNOT_ITERATE"; /** This NodeSet can not iterate to a previous node! */ public static final String ER_NODESET_CANNOT_ITERATE = "ER_NODESET_CANNOT_ITERATE"; /** This NodeSetDTM can not do indexing or counting functions! */ public static final String ER_NODESETDTM_CANNOT_INDEX = "ER_NODESETDTM_CANNOT_INDEX"; /** This NodeSet can not do indexing or counting functions! */ public static final String ER_NODESET_CANNOT_INDEX = "ER_NODESET_CANNOT_INDEX"; /** Can not call setShouldCacheNodes after nextNode has been called! */ public static final String ER_CANNOT_CALL_SETSHOULDCACHENODE = "ER_CANNOT_CALL_SETSHOULDCACHENODE"; /** {0} only allows {1} arguments */ public static final String ER_ONLY_ALLOWS = "ER_ONLY_ALLOWS"; /** Programmer's assertion in getNextStepPos: unknown stepType: {0} */ public static final String ER_UNKNOWN_STEP = "ER_UNKNOWN_STEP"; /** Problem with RelativeLocationPath */ public static final String ER_EXPECTED_REL_LOC_PATH = "ER_EXPECTED_REL_LOC_PATH"; /** Problem with LocationPath */ public static final String ER_EXPECTED_LOC_PATH = "ER_EXPECTED_LOC_PATH"; public static final String ER_EXPECTED_LOC_PATH_AT_END_EXPR = "ER_EXPECTED_LOC_PATH_AT_END_EXPR"; /** Problem with Step */ public static final String ER_EXPECTED_LOC_STEP = "ER_EXPECTED_LOC_STEP"; /** Problem with NodeTest */ public static final String ER_EXPECTED_NODE_TEST = "ER_EXPECTED_NODE_TEST"; /** Expected step pattern */ public static final String ER_EXPECTED_STEP_PATTERN = "ER_EXPECTED_STEP_PATTERN"; /** Expected relative path pattern */ public static final String ER_EXPECTED_REL_PATH_PATTERN = "ER_EXPECTED_REL_PATH_PATTERN"; /** ER_CANT_CONVERT_XPATHRESULTTYPE_TO_BOOLEAN */ public static final String ER_CANT_CONVERT_TO_BOOLEAN = "ER_CANT_CONVERT_TO_BOOLEAN"; /** Field ER_CANT_CONVERT_TO_SINGLENODE */ public static final String ER_CANT_CONVERT_TO_SINGLENODE = "ER_CANT_CONVERT_TO_SINGLENODE"; /** Field ER_CANT_GET_SNAPSHOT_LENGTH */ public static final String ER_CANT_GET_SNAPSHOT_LENGTH = "ER_CANT_GET_SNAPSHOT_LENGTH"; /** Field ER_NON_ITERATOR_TYPE */ public static final String ER_NON_ITERATOR_TYPE = "ER_NON_ITERATOR_TYPE"; /** Field ER_DOC_MUTATED */ public static final String ER_DOC_MUTATED = "ER_DOC_MUTATED"; public static final String ER_INVALID_XPATH_TYPE = "ER_INVALID_XPATH_TYPE"; public static final String ER_EMPTY_XPATH_RESULT = "ER_EMPTY_XPATH_RESULT"; public static final String ER_INCOMPATIBLE_TYPES = "ER_INCOMPATIBLE_TYPES"; public static final String ER_NULL_RESOLVER = "ER_NULL_RESOLVER"; public static final String ER_CANT_CONVERT_TO_STRING = "ER_CANT_CONVERT_TO_STRING"; public static final String ER_NON_SNAPSHOT_TYPE = "ER_NON_SNAPSHOT_TYPE"; public static final String ER_WRONG_DOCUMENT = "ER_WRONG_DOCUMENT"; /* Note to translators: The XPath expression cannot be evaluated with respect * to this type of node. */ /** Field ER_WRONG_NODETYPE */ public static final String ER_WRONG_NODETYPE = "ER_WRONG_NODETYPE"; public static final String ER_XPATH_ERROR = "ER_XPATH_ERROR"; //BEGIN: Keys needed for exception messages of JAXP 1.3 XPath API implementation public static final String ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED = "ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED"; public static final String ER_RESOLVE_VARIABLE_RETURNS_NULL = "ER_RESOLVE_VARIABLE_RETURNS_NULL"; public static final String ER_UNSUPPORTED_RETURN_TYPE = "ER_UNSUPPORTED_RETURN_TYPE"; public static final String ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL = "ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL"; public static final String ER_ARG_CANNOT_BE_NULL = "ER_ARG_CANNOT_BE_NULL"; public static final String ER_OBJECT_MODEL_NULL = "ER_OBJECT_MODEL_NULL"; public static final String ER_OBJECT_MODEL_EMPTY = "ER_OBJECT_MODEL_EMPTY"; public static final String ER_FEATURE_NAME_NULL = "ER_FEATURE_NAME_NULL"; public static final String ER_FEATURE_UNKNOWN = "ER_FEATURE_UNKNOWN"; public static final String ER_GETTING_NULL_FEATURE = "ER_GETTING_NULL_FEATURE"; public static final String ER_GETTING_UNKNOWN_FEATURE = "ER_GETTING_UNKNOWN_FEATURE"; public static final String ER_SECUREPROCESSING_FEATURE = "ER_SECUREPROCESSING_FEATURE"; public static final String ER_NULL_XPATH_FUNCTION_RESOLVER = "ER_NULL_XPATH_FUNCTION_RESOLVER"; public static final String ER_NULL_XPATH_VARIABLE_RESOLVER = "ER_NULL_XPATH_VARIABLE_RESOLVER"; //END: Keys needed for exception messages of JAXP 1.3 XPath API implementation public static final String WG_LOCALE_NAME_NOT_HANDLED = "WG_LOCALE_NAME_NOT_HANDLED"; public static final String WG_PROPERTY_NOT_SUPPORTED = "WG_PROPERTY_NOT_SUPPORTED"; public static final String WG_DONT_DO_ANYTHING_WITH_NS = "WG_DONT_DO_ANYTHING_WITH_NS"; public static final String WG_SECURITY_EXCEPTION = "WG_SECURITY_EXCEPTION"; public static final String WG_QUO_NO_LONGER_DEFINED = "WG_QUO_NO_LONGER_DEFINED"; public static final String WG_NEED_DERIVED_OBJECT_TO_IMPLEMENT_NODETEST = "WG_NEED_DERIVED_OBJECT_TO_IMPLEMENT_NODETEST"; public static final String WG_FUNCTION_TOKEN_NOT_FOUND = "WG_FUNCTION_TOKEN_NOT_FOUND"; public static final String WG_COULDNOT_FIND_FUNCTION = "WG_COULDNOT_FIND_FUNCTION"; public static final String WG_CANNOT_MAKE_URL_FROM ="WG_CANNOT_MAKE_URL_FROM"; public static final String WG_EXPAND_ENTITIES_NOT_SUPPORTED = "WG_EXPAND_ENTITIES_NOT_SUPPORTED"; public static final String WG_ILLEGAL_VARIABLE_REFERENCE = "WG_ILLEGAL_VARIABLE_REFERENCE"; public static final String WG_UNSUPPORTED_ENCODING ="WG_UNSUPPORTED_ENCODING"; /** detach() not supported by XRTreeFragSelectWrapper */ public static final String ER_DETACH_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER = "ER_DETACH_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER"; /** num() not supported by XRTreeFragSelectWrapper */ public static final String ER_NUM_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER = "ER_NUM_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER"; /** xstr() not supported by XRTreeFragSelectWrapper */ public static final String ER_XSTR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER = "ER_XSTR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER"; /** str() not supported by XRTreeFragSelectWrapper */ public static final String ER_STR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER = "ER_STR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER"; // Error messages... private static final Object[][] _contents = new Object[][]{ { "ERROR0000" , "{0}" }, { ER_CURRENT_NOT_ALLOWED_IN_MATCH, "Funktionen current() \u00E4r inte till\u00E5ten i ett matchningsm\u00F6nster!" }, { ER_CURRENT_TAKES_NO_ARGS, "Funktionen current() tar inte emot argument!" }, { ER_DOCUMENT_REPLACED, "Implementeringen av funktionen document() har inte ersatts av com.sun.org.apache.xalan.internal.xslt.FuncDocument!"}, { ER_CONTEXT_HAS_NO_OWNERDOC, "context har inget \u00E4gardokument!"}, { ER_LOCALNAME_HAS_TOO_MANY_ARGS, "local-name() har f\u00F6r m\u00E5nga argument."}, { ER_NAMESPACEURI_HAS_TOO_MANY_ARGS, "namespace-uri() har f\u00F6r m\u00E5nga argument."}, { ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS, "normalize-space() har f\u00F6r m\u00E5nga argument."}, { ER_NUMBER_HAS_TOO_MANY_ARGS, "number() har f\u00F6r m\u00E5nga argument."}, { ER_NAME_HAS_TOO_MANY_ARGS, "name() har f\u00F6r m\u00E5nga argument."}, { ER_STRING_HAS_TOO_MANY_ARGS, "string() har f\u00F6r m\u00E5nga argument."}, { ER_STRINGLENGTH_HAS_TOO_MANY_ARGS, "string-length() har f\u00F6r m\u00E5nga argument."}, { ER_TRANSLATE_TAKES_3_ARGS, "Funktionen translate() tar emot tre argument!"}, { ER_UNPARSEDENTITYURI_TAKES_1_ARG, "Funktionen unparsed-entity-uri borde ta emot ett argument!"}, { ER_NAMESPACEAXIS_NOT_IMPLEMENTED, "namnrymdsaxeln \u00E4r inte implementerad \u00E4n!"}, { ER_UNKNOWN_AXIS, "ok\u00E4nd axel: {0}"}, { ER_UNKNOWN_MATCH_OPERATION, "ok\u00E4nd matchnings\u00E5tg\u00E4rd!"}, { ER_INCORRECT_ARG_LENGTH, "Felaktig argumentl\u00E4ngd p\u00E5 nodtest f\u00F6r processing-instruction()!"}, { ER_CANT_CONVERT_TO_NUMBER, "Kan inte konvertera {0} till ett tal"}, { ER_CANT_CONVERT_TO_NODELIST, "Kan inte konvertera {0} till NodeList!"}, { ER_CANT_CONVERT_TO_MUTABLENODELIST, "Kan inte konvertera {0} till NodeSetDTM!"}, { ER_CANT_CONVERT_TO_TYPE, "Kan inte konvertera {0} till type#{1}"}, { ER_EXPECTED_MATCH_PATTERN, "F\u00F6rv\u00E4ntat matchningsm\u00F6nster i getMatchScore!"}, { ER_COULDNOT_GET_VAR_NAMED, "Kunde inte h\u00E4mta variabeln {0}"}, { ER_UNKNOWN_OPCODE, "FEL! Ok\u00E4nd op-kod: {0}"}, { ER_EXTRA_ILLEGAL_TOKENS, "Extra otill\u00E5tna token: {0}"}, { ER_EXPECTED_DOUBLE_QUOTE, "Litteral omges av fel sorts citattecken... dubbla citattecken f\u00F6rv\u00E4ntade!"}, { ER_EXPECTED_SINGLE_QUOTE, "Litteral omges av fel sorts citattecken... enkla citattecken f\u00F6rv\u00E4ntade!"}, { ER_EMPTY_EXPRESSION, "Tomt uttryck!"}, { ER_EXPECTED_BUT_FOUND, "F\u00F6rv\u00E4ntade {0}, men hittade: {1}"}, { ER_INCORRECT_PROGRAMMER_ASSERTION, "Programmerarens utsaga \u00E4r inte korrekt! - {0}"}, { ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL, "Argumentet boolean(...) \u00E4r inte l\u00E4ngre valfritt med 19990709 XPath-utkast."}, { ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG, "Hittade ',' utan f\u00F6reg\u00E5ende argument!"}, { ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG, "Hittade ',' utan efterf\u00F6ljande argument!"}, { ER_PREDICATE_ILLEGAL_SYNTAX, "'..[predikat]' eller '.[predikat]' \u00E4r otill\u00E5ten syntax. Anv\u00E4nd 'self::node()[predikat]' ist\u00E4llet."}, { ER_ILLEGAL_AXIS_NAME, "otill\u00E5tet axelnamn: {0}"}, { ER_UNKNOWN_NODETYPE, "Ok\u00E4nd nodtyp: {0}"}, { ER_PATTERN_LITERAL_NEEDS_BE_QUOTED, "M\u00F6nsterlitteralen ({0}) m\u00E5ste omges av citattecken!"}, { ER_COULDNOT_BE_FORMATTED_TO_NUMBER, "{0} kunde inte formateras till ett tal!"}, { ER_COULDNOT_CREATE_XMLPROCESSORLIAISON, "Kunde inte skapa XML TransformerFactory Liaison: {0}"}, { ER_DIDNOT_FIND_XPATH_SELECT_EXP, "Fel! Hittade inte xpath select-uttryck (-select)."}, { ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH, "FEL! Hittade inte ENDOP efter OP_LOCATIONPATH"}, { ER_ERROR_OCCURED, "Ett fel har intr\u00E4ffat!"}, { ER_ILLEGAL_VARIABLE_REFERENCE, "VariableReference angiven f\u00F6r variabel som \u00E4r utanf\u00F6r kontext eller som saknar definition! Namn = {0}"}, { ER_AXES_NOT_ALLOWED, "Endast underordnade:: och attribut::-axlar \u00E4r till\u00E5tna i matchningsm\u00F6nster! Regelvidriga axlar = {0}"}, { ER_KEY_HAS_TOO_MANY_ARGS, "key() har felaktigt antal argument."}, { ER_COUNT_TAKES_1_ARG, "Funktionen count borde ta emot ett argument!"}, { ER_COULDNOT_FIND_FUNCTION, "Hittade inte funktionen: {0}"}, { ER_UNSUPPORTED_ENCODING, "Kodning utan st\u00F6d: {0}"}, { ER_PROBLEM_IN_DTM_NEXTSIBLING, "Problem intr\u00E4ffade i DTM i getNextSibling... f\u00F6rs\u00F6ker \u00E5terskapa"}, { ER_CANNOT_WRITE_TO_EMPTYNODELISTIMPL, "Programmerarfel: kan inte skriva till EmptyNodeList."}, { ER_SETDOMFACTORY_NOT_SUPPORTED, "setDOMFactory st\u00F6ds inte i XPathContext!"}, { ER_PREFIX_MUST_RESOLVE, "Prefix m\u00E5ste matchas till en namnrymd: {0}"}, { ER_PARSE_NOT_SUPPORTED, "tolkning (InputSource-k\u00E4lla) st\u00F6ds inte i XPathContext! Kan inte \u00F6ppna {0}"}, { ER_SAX_API_NOT_HANDLED, "SAX API-tecken(char ch[]... hanteras inte av DTM!"}, { ER_IGNORABLE_WHITESPACE_NOT_HANDLED, "ignorableWhitespace(char ch[]... hanteras inte av DTM!"}, { ER_DTM_CANNOT_HANDLE_NODES, "DTMLiaison kan inte hantera noder av typ {0}"}, { ER_XERCES_CANNOT_HANDLE_NODES, "DOM2Helper kan inte hantera noder av typ {0}"}, { ER_XERCES_PARSE_ERROR_DETAILS, "Fel i DOM2Helper.parse: SystemID - {0} rad - {1}"}, { ER_XERCES_PARSE_ERROR, "Fel i DOM2Helper.parse"}, { ER_INVALID_UTF16_SURROGATE, "Ogiltigt UTF-16-surrogat uppt\u00E4ckt: {0} ?"}, { ER_OIERROR, "IO-fel"}, { ER_CANNOT_CREATE_URL, "Kan inte skapa URL f\u00F6r: {0}"}, { ER_XPATH_READOBJECT, "I XPath.readObject: {0}"}, { ER_FUNCTION_TOKEN_NOT_FOUND, "funktionstoken hittades inte."}, { ER_CANNOT_DEAL_XPATH_TYPE, "Kan inte hantera XPath-typ: {0}"}, { ER_NODESET_NOT_MUTABLE, "Detta NodeSet \u00E4r of\u00F6r\u00E4nderligt"}, { ER_NODESETDTM_NOT_MUTABLE, "Detta NodeSetDTM \u00E4r of\u00F6r\u00E4nderligt"}, { ER_VAR_NOT_RESOLVABLE, "Variabeln kan inte matchas: {0}"}, { ER_NULL_ERROR_HANDLER, "Felhanterare med v\u00E4rde null"}, { ER_PROG_ASSERT_UNKNOWN_OPCODE, "Programmerarens utsaga: ok\u00E4nd op-kod: {0}"}, { ER_ZERO_OR_ONE, "0 eller 1"}, { ER_RTF_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER, "rtf() st\u00F6ds inte av XRTreeFragSelectWrapper"}, { ER_RTF_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER, "asNodeIterator() st\u00F6ds inte av XRTreeFragSelectWrapper"}, /** detach() not supported by XRTreeFragSelectWrapper */ { ER_DETACH_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER, "detach() st\u00F6ds inte av XRTreeFragSelectWrapper"}, /** num() not supported by XRTreeFragSelectWrapper */ { ER_NUM_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER, "num() st\u00F6ds inte av XRTreeFragSelectWrapper"}, /** xstr() not supported by XRTreeFragSelectWrapper */ { ER_XSTR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER, "xstr() st\u00F6ds inte av XRTreeFragSelectWrapper"}, /** str() not supported by XRTreeFragSelectWrapper */ { ER_STR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER, "str() st\u00F6ds inte av XRTreeFragSelectWrapper"}, { ER_FSB_NOT_SUPPORTED_XSTRINGFORCHARS, "fsb() st\u00F6ds inte f\u00F6r XStringForChars"}, { ER_COULD_NOT_FIND_VAR, "Hittade inte variabel med namnet {0}"}, { ER_XSTRINGFORCHARS_CANNOT_TAKE_STRING, "XStringForChars kan inte ta emot en str\u00E4ng f\u00F6r argument"}, { ER_FASTSTRINGBUFFER_CANNOT_BE_NULL, "FastStringBuffer-argumentet f\u00E5r inte vara null"}, { ER_TWO_OR_THREE, "2 eller 3"}, { ER_VARIABLE_ACCESSED_BEFORE_BIND, "\u00C5tkomst till variabel innan den \u00E4r bunden!"}, { ER_FSB_CANNOT_TAKE_STRING, "XStringForFSB kan inte ta emot en str\u00E4ng f\u00F6r argument!"}, { ER_SETTING_WALKER_ROOT_TO_NULL, "\n !!!! Fel! Anger roten f\u00F6r en ''walker'' som null!!!"}, { ER_NODESETDTM_CANNOT_ITERATE, "Detta NodeSetDTM kan inte iterera till en tidigare nod!"}, { ER_NODESET_CANNOT_ITERATE, "Detta NodeSet kan inte iterera till en tidigare nod!"}, { ER_NODESETDTM_CANNOT_INDEX, "Detta NodeSetDTM kan inte utf\u00F6ra funktioner som indexerar eller r\u00E4knar!"}, { ER_NODESET_CANNOT_INDEX, "Detta NodeSet kan inte utf\u00F6ra funktioner som indexerar eller r\u00E4knar!"}, { ER_CANNOT_CALL_SETSHOULDCACHENODE, "Kan inte anropa setShouldCacheNodes efter anropat nextNode!"}, { ER_ONLY_ALLOWS, "{0} till\u00E5ter endast {1} argument"}, { ER_UNKNOWN_STEP, "Programmerarens utsaga i getNextStepPos: ok\u00E4nt stepType: {0}"}, //Note to translators: A relative location path is a form of XPath expression. // The message indicates that such an expression was expected following the // characters '/' or '//', but was not found. { ER_EXPECTED_REL_LOC_PATH, "En relativ s\u00F6kv\u00E4g f\u00F6rv\u00E4ntades efter token '/' eller '//'."}, // Note to translators: A location path is a form of XPath expression. // The message indicates that syntactically such an expression was expected,but // the characters specified by the substitution text were encountered instead. { ER_EXPECTED_LOC_PATH, "En s\u00F6kv\u00E4g f\u00F6rv\u00E4ntades, men f\u00F6ljande token p\u00E5tr\u00E4ffades: {0}"}, // Note to translators: A location path is a form of XPath expression. // The message indicates that syntactically such a subexpression was expected, // but no more characters were found in the expression. { ER_EXPECTED_LOC_PATH_AT_END_EXPR, "En s\u00F6kv\u00E4g f\u00F6rv\u00E4ntades, men slutet av XPath-uttrycket hittades ist\u00E4llet."}, // Note to translators: A location step is part of an XPath expression. // The message indicates that syntactically such an expression was expected // following the specified characters. { ER_EXPECTED_LOC_STEP, "Ett platssteg f\u00F6rv\u00E4ntades efter token '/' eller '//'."}, // Note to translators: A node test is part of an XPath expression that is // used to test for particular kinds of nodes. In this case, a node test that // consists of an NCName followed by a colon and an asterisk or that consists // of a QName was expected, but was not found. { ER_EXPECTED_NODE_TEST, "Ett nodtest som matchar antingen NCName:* eller QName f\u00F6rv\u00E4ntades."}, // Note to translators: A step pattern is part of an XPath expression. // The message indicates that syntactically such an expression was expected, // but the specified character was found in the expression instead. { ER_EXPECTED_STEP_PATTERN, "Ett stegm\u00F6nster f\u00F6rv\u00E4ntades, men '/' p\u00E5tr\u00E4ffades."}, // Note to translators: A relative path pattern is part of an XPath expression. // The message indicates that syntactically such an expression was expected, // but was not found. { ER_EXPECTED_REL_PATH_PATTERN, "Ett m\u00F6nster f\u00F6r relativ s\u00F6kv\u00E4g f\u00F6rv\u00E4ntades."}, // Note to translators: The substitution text is the name of a data type. The // message indicates that a value of a particular type could not be converted // to a value of type boolean. { ER_CANT_CONVERT_TO_BOOLEAN, "XPathResult i XPath-uttrycket ''{0}'' inneh\u00E5ller XPathResultType {1} som inte kan konverteras till booleskt v\u00E4rde."}, // Note to translators: Do not translate ANY_UNORDERED_NODE_TYPE and // FIRST_ORDERED_NODE_TYPE. { ER_CANT_CONVERT_TO_SINGLENODE, "XPathResult i XPath-uttrycket ''{0}'' inneh\u00E5ller XPathResultType {1} som inte kan konverteras till enskild nod. Metoden getSingleNodeValue anv\u00E4nds endast till typ ANY_UNORDERED_NODE_TYPE och FIRST_ORDERED_NODE_TYPE."}, // Note to translators: Do not translate UNORDERED_NODE_SNAPSHOT_TYPE and // ORDERED_NODE_SNAPSHOT_TYPE. { ER_CANT_GET_SNAPSHOT_LENGTH, "Metoden getSnapshotLength kan inte anropas vid XPathResult fr\u00E5n XPath-uttrycket ''{0}'' eftersom XPathResultType \u00E4r {1}. Metoden anv\u00E4nds endast till typ UNORDERED_NODE_SNAPSHOT_TYPE och ORDERED_NODE_SNAPSHOT_TYPE."}, { ER_NON_ITERATOR_TYPE, "Metoden iterateNext kan inte anropas vid XPathResult fr\u00E5n XPath-uttrycket ''{0}'' eftersom XPathResultType \u00E4r {1}. Metoden anv\u00E4nds endast till typ UNORDERED_NODE_ITERATOR_TYPE och ORDERED_NODE_ITERATOR_TYPE."}, // Note to translators: This message indicates that the document being operated // upon changed, so the iterator object that was being used to traverse the // document has now become invalid. { ER_DOC_MUTATED, "Dokumentet har muterats sedan resultatet genererades. Iteratorn \u00E4r ogiltig."}, { ER_INVALID_XPATH_TYPE, "Ogiltigt XPath-typargument: {0}"}, { ER_EMPTY_XPATH_RESULT, "Tomt XPath-resultatobjekt"}, { ER_INCOMPATIBLE_TYPES, "XPathResult i XPath-uttrycket ''{0}'' inneh\u00E5ller XPathResultType {1} som inte kan tvingas till angiven XPathResultType {2}."}, { ER_NULL_RESOLVER, "Kan inte matcha prefix med prefixmatchning som \u00E4r null."}, // Note to translators: The substitution text is the name of a data type. The // message indicates that a value of a particular type could not be converted // to a value of type string. { ER_CANT_CONVERT_TO_STRING, "XPathResult i XPath-uttrycket ''{0}'' inneh\u00E5ller XPathResultType {1} som inte kan konverteras till en str\u00E4ng."}, // Note to translators: Do not translate snapshotItem, // UNORDERED_NODE_SNAPSHOT_TYPE and ORDERED_NODE_SNAPSHOT_TYPE. { ER_NON_SNAPSHOT_TYPE, "Metoden snapshotItem kan inte anropas vid XPathResult fr\u00E5n XPath-uttrycket ''{0}'' eftersom XPathResultType \u00E4r {1}. Metoden anv\u00E4nds endast till typ UNORDERED_NODE_SNAPSHOT_TYPE och ORDERED_NODE_SNAPSHOT_TYPE."}, // Note to translators: XPathEvaluator is a Java interface name. An // XPathEvaluator is created with respect to a particular XML document, and in // this case the expression represented by this object was being evaluated with // respect to a context node from a different document. { ER_WRONG_DOCUMENT, "Kontextnoden tillh\u00F6r inte dokumentet som \u00E4r bundet till denna XPathEvaluator."}, // Note to translators: The XPath expression cannot be evaluated with respect // to this type of node. { ER_WRONG_NODETYPE, "Kontextnodtypen st\u00F6ds inte."}, { ER_XPATH_ERROR, "Ok\u00E4nt fel i XPath."}, { ER_CANT_CONVERT_XPATHRESULTTYPE_TO_NUMBER, "XPathResult i XPath-uttrycket ''{0}'' inneh\u00E5ller XPathResultType {1} som inte kan konverteras till ett tal."}, //BEGIN: Definitions of error keys used in exception messages of JAXP 1.3 XPath API implementation /** Field ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED */ { ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED, "Till\u00E4ggsfunktion: ''{0}'' kan inte anropas om funktionen XMLConstants.FEATURE_SECURE_PROCESSING anges som true."}, /** Field ER_RESOLVE_VARIABLE_RETURNS_NULL */ { ER_RESOLVE_VARIABLE_RETURNS_NULL, "resolveVariable f\u00F6r variabeln {0} returnerar null"}, /** Field ER_UNSUPPORTED_RETURN_TYPE */ { ER_UNSUPPORTED_RETURN_TYPE, "Det finns inget st\u00F6d f\u00F6r returtypen: {0}"}, /** Field ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL */ { ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL, "K\u00E4lla och/eller returtyp f\u00E5r inte vara null"}, /** Field ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL */ { ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL, "K\u00E4lla och/eller returtyp f\u00E5r inte vara null"}, /** Field ER_ARG_CANNOT_BE_NULL */ { ER_ARG_CANNOT_BE_NULL, "Argumentet {0} kan inte vara null"}, /** Field ER_OBJECT_MODEL_NULL */ { ER_OBJECT_MODEL_NULL, "{0}#isObjectModelSupported( String objectModel ) kan inte anropas med objectModel == null"}, /** Field ER_OBJECT_MODEL_EMPTY */ { ER_OBJECT_MODEL_EMPTY, "{0}#isObjectModelSupported( String objectModel ) kan inte anropas med objectModel == \"\""}, /** Field ER_OBJECT_MODEL_EMPTY */ { ER_FEATURE_NAME_NULL, "F\u00F6rs\u00F6ker ange en funktion med null-namn: {0}#setFeature( null, {1})"}, /** Field ER_FEATURE_UNKNOWN */ { ER_FEATURE_UNKNOWN, "F\u00F6rs\u00F6ker ange en ok\u00E4nd funktion \"{0}\":{1}#setFeature({0},{2})"}, /** Field ER_GETTING_NULL_FEATURE */ { ER_GETTING_NULL_FEATURE, "F\u00F6rs\u00F6ker h\u00E4mta en funktion med null-namn: {0}#getFeature(null)"}, /** Field ER_GETTING_NULL_FEATURE */ { ER_GETTING_UNKNOWN_FEATURE, "F\u00F6rs\u00F6ker h\u00E4mta en ok\u00E4nd funktion \"{0}\":{1}#getFeature({0})"}, {ER_SECUREPROCESSING_FEATURE, "FEATURE_SECURE_PROCESSING: Kan inte ange funktionen som false om s\u00E4kerhetshanteraren anv\u00E4nds: {1}#setFeature({0},{2})"}, /** Field ER_NULL_XPATH_FUNCTION_RESOLVER */ { ER_NULL_XPATH_FUNCTION_RESOLVER, "F\u00F6rs\u00F6ker ange nullv\u00E4rde f\u00F6r XPathFunctionResolver:{0}#setXPathFunctionResolver(null)"}, /** Field ER_NULL_XPATH_VARIABLE_RESOLVER */ { ER_NULL_XPATH_VARIABLE_RESOLVER, "F\u00F6rs\u00F6ker ange nullv\u00E4rde f\u00F6r XPathVariableResolver:{0}#setXPathVariableResolver(null)"}, //END: Definitions of error keys used in exception messages of JAXP 1.3 XPath API implementation // Warnings... { WG_LOCALE_NAME_NOT_HANDLED, "spr\u00E5kkonventionsnamnet i funktionen format-number har \u00E4nnu inte hanterats!"}, { WG_PROPERTY_NOT_SUPPORTED, "XSL-egenskapen st\u00F6ds inte: {0}"}, { WG_DONT_DO_ANYTHING_WITH_NS, "G\u00F6r f\u00F6r n\u00E4rvarande inte n\u00E5gonting med namnrymden {0} i egenskap: {1}"}, { WG_SECURITY_EXCEPTION, "SecurityException vid f\u00F6rs\u00F6k att f\u00E5 \u00E5tkomst till XSL-systemegenskap: {0}"}, { WG_QUO_NO_LONGER_DEFINED, "Gammal syntax: quo(...) definieras inte l\u00E4ngre i XPath."}, { WG_NEED_DERIVED_OBJECT_TO_IMPLEMENT_NODETEST, "XPath beh\u00F6ver ett h\u00E4rledningsobjekt f\u00F6r att implementera nodeTest!"}, { WG_FUNCTION_TOKEN_NOT_FOUND, "funktionstoken hittades inte."}, { WG_COULDNOT_FIND_FUNCTION, "Hittade inte funktionen: {0}"}, { WG_CANNOT_MAKE_URL_FROM, "Kan inte skapa URL fr\u00E5n: {0}"}, { WG_EXPAND_ENTITIES_NOT_SUPPORTED, "Alternativet -E st\u00F6ds inte i DTM-parser"}, { WG_ILLEGAL_VARIABLE_REFERENCE, "VariableReference angiven f\u00F6r variabel som \u00E4r utanf\u00F6r kontext eller som saknar definition! Namn = {0}"}, { WG_UNSUPPORTED_ENCODING, "Kodning utan st\u00F6d: {0}"}, // Other miscellaneous text used inside the code... { "ui_language", "en"}, { "help_language", "en"}, { "language", "en"}, { "BAD_CODE", "Parameter f\u00F6r createMessage ligger utanf\u00F6r gr\u00E4nsv\u00E4rdet"}, { "FORMAT_FAILED", "Undantag utl\u00F6st vid messageFormat-anrop"}, { "version", ">>>>>>> Xalan version "}, { "version2", "<<<<<<<"}, { "yes", "ja"}, { "line", "Rad nr"}, { "column", "Kolumn nr"}, { "xsldone", "XSLProcessor: utf\u00F6rd"}, { "xpath_option", "xpath-alternativ: "}, { "optionIN", " [-in inputXMLURL]"}, { "optionSelect", " [-select xpath-uttryck]"}, { "optionMatch", " [-match matchningsm\u00F6nster (f\u00F6r matchningsdiagnostik)]"}, { "optionAnyExpr", "Eller bara ett xpath-uttryck skapar en diagnostikdump"}, { "noParsermsg1", "XSL-processen utf\u00F6rdes inte."}, { "noParsermsg2", "** Hittade inte parser **"}, { "noParsermsg3", "Kontrollera klass\u00F6kv\u00E4gen."}, { "noParsermsg4", "Om du inte har IBMs XML Parser f\u00F6r Java kan du ladda ned den fr\u00E5n"}, { "noParsermsg5", "IBMs AlphaWorks: http://www.alphaworks.ibm.com/formula/xml"}, { "gtone", ">1" }, { "zero", "0" }, { "one", "1" }, { "two" , "2" }, { "three", "3" } }; /** * Get the association list. * * @return The association list. */ public Object[][] getContents() { return _contents; } // ================= INFRASTRUCTURE ====================== /** Field BAD_CODE */ public static final String BAD_CODE = "BAD_CODE"; /** Field FORMAT_FAILED */ public static final String FORMAT_FAILED = "FORMAT_FAILED"; /** Field ERROR_RESOURCES */ public static final String ERROR_RESOURCES = "com.sun.org.apache.xpath.internal.res.XPATHErrorResources"; /** Field ERROR_STRING */ public static final String ERROR_STRING = "#error"; /** Field ERROR_HEADER */ public static final String ERROR_HEADER = "Error: "; /** Field WARNING_HEADER */ public static final String WARNING_HEADER = "Warning: "; /** Field XSL_HEADER */ public static final String XSL_HEADER = "XSL "; /** Field XML_HEADER */ public static final String XML_HEADER = "XML "; /** Field QUERY_HEADER */ public static final String QUERY_HEADER = "PATTERN "; }
gpl-2.0
geneos/adempiere
base/src/org/compiere/model/X_C_InvoiceTax.java
5988
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.Env; /** Generated Model for C_InvoiceTax * @author Adempiere (generated) * @version Release 3.7.0LTS - $Id$ */ public class X_C_InvoiceTax extends PO implements I_C_InvoiceTax, I_Persistent { /** * */ private static final long serialVersionUID = 20110831L; /** Standard Constructor */ public X_C_InvoiceTax (Properties ctx, int C_InvoiceTax_ID, String trxName) { super (ctx, C_InvoiceTax_ID, trxName); /** if (C_InvoiceTax_ID == 0) { setC_Invoice_ID (0); setC_Tax_ID (0); setIsTaxIncluded (false); setProcessed (false); setTaxAmt (Env.ZERO); setTaxBaseAmt (Env.ZERO); } */ } /** Load Constructor */ public X_C_InvoiceTax (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 1 - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_InvoiceTax[") .append(get_ID()).append("]"); return sb.toString(); } public org.compiere.model.I_C_Invoice getC_Invoice() throws RuntimeException { return (org.compiere.model.I_C_Invoice)MTable.get(getCtx(), org.compiere.model.I_C_Invoice.Table_Name) .getPO(getC_Invoice_ID(), get_TrxName()); } /** Set Invoice. @param C_Invoice_ID Invoice Identifier */ public void setC_Invoice_ID (int C_Invoice_ID) { if (C_Invoice_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID)); } /** Get Invoice. @return Invoice Identifier */ public int getC_Invoice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_C_Tax getC_Tax() throws RuntimeException { return (org.compiere.model.I_C_Tax)MTable.get(getCtx(), org.compiere.model.I_C_Tax.Table_Name) .getPO(getC_Tax_ID(), get_TrxName()); } /** Set Tax. @param C_Tax_ID Tax identifier */ public void setC_Tax_ID (int C_Tax_ID) { if (C_Tax_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Tax_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Tax_ID, Integer.valueOf(C_Tax_ID)); } /** Get Tax. @return Tax identifier */ public int getC_Tax_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Tax_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Price includes Tax. @param IsTaxIncluded Tax is included in the price */ public void setIsTaxIncluded (boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded)); } /** Get Price includes Tax. @return Tax is included in the price */ public boolean isTaxIncluded () { Object oo = get_Value(COLUMNNAME_IsTaxIncluded); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Tax Amount. @param TaxAmt Tax Amount for a document */ public void setTaxAmt (BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt); } /** Get Tax Amount. @return Tax Amount for a document */ public BigDecimal getTaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Tax base Amount. @param TaxBaseAmt Base for calculating the tax amount */ public void setTaxBaseAmt (BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } /** Get Tax base Amount. @return Base for calculating the tax amount */ public BigDecimal getTaxBaseAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxBaseAmt); if (bd == null) return Env.ZERO; return bd; } }
gpl-2.0
huran2014/huran.github.io
program_learning/Java/MyEclipseProfessional2014/mr/src/test/java/org/apache/mahout/math/MatrixWritableTest.java
5129
/** * 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.mahout.math; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import com.google.common.collect.Maps; import com.google.common.io.Closeables; import org.apache.hadoop.io.Writable; import org.junit.Test; public final class MatrixWritableTest extends MahoutTestCase { @Test public void testSparseMatrixWritable() throws Exception { Matrix m = new SparseMatrix(5, 5); m.set(1, 2, 3.0); m.set(3, 4, 5.0); Map<String, Integer> bindings = Maps.newHashMap(); bindings.put("A", 0); bindings.put("B", 1); bindings.put("C", 2); bindings.put("D", 3); bindings.put("default", 4); m.setRowLabelBindings(bindings); m.setColumnLabelBindings(bindings); doTestMatrixWritableEquals(m); } @Test public void testSparseRowMatrixWritable() throws Exception { Matrix m = new SparseRowMatrix(5, 5); m.set(1, 2, 3.0); m.set(3, 4, 5.0); Map<String, Integer> bindings = Maps.newHashMap(); bindings.put("A", 0); bindings.put("B", 1); bindings.put("C", 2); bindings.put("D", 3); bindings.put("default", 4); m.setRowLabelBindings(bindings); m.setColumnLabelBindings(bindings); doTestMatrixWritableEquals(m); } @Test public void testDenseMatrixWritable() throws Exception { Matrix m = new DenseMatrix(5,5); m.set(1, 2, 3.0); m.set(3, 4, 5.0); Map<String, Integer> bindings = Maps.newHashMap(); bindings.put("A", 0); bindings.put("B", 1); bindings.put("C", 2); bindings.put("D", 3); bindings.put("default", 4); m.setRowLabelBindings(bindings); m.setColumnLabelBindings(bindings); doTestMatrixWritableEquals(m); } private static void doTestMatrixWritableEquals(Matrix m) throws IOException { Writable matrixWritable = new MatrixWritable(m); MatrixWritable matrixWritable2 = new MatrixWritable(); writeAndRead(matrixWritable, matrixWritable2); Matrix m2 = matrixWritable2.get(); compareMatrices(m, m2); doCheckBindings(m2.getRowLabelBindings()); doCheckBindings(m2.getColumnLabelBindings()); } private static void compareMatrices(Matrix m, Matrix m2) { assertEquals(m.numRows(), m2.numRows()); assertEquals(m.numCols(), m2.numCols()); for (int r = 0; r < m.numRows(); r++) { for (int c = 0; c < m.numCols(); c++) { assertEquals(m.get(r, c), m2.get(r, c), EPSILON); } } Map<String,Integer> bindings = m.getRowLabelBindings(); Map<String, Integer> bindings2 = m2.getRowLabelBindings(); assertEquals(bindings == null, bindings2 == null); if (bindings != null) { assertEquals(bindings.size(), m.numRows()); assertEquals(bindings.size(), bindings2.size()); for (Map.Entry<String,Integer> entry : bindings.entrySet()) { assertEquals(entry.getValue(), bindings2.get(entry.getKey())); } } bindings = m.getColumnLabelBindings(); bindings2 = m2.getColumnLabelBindings(); assertEquals(bindings == null, bindings2 == null); if (bindings != null) { assertEquals(bindings.size(), bindings2.size()); for (Map.Entry<String,Integer> entry : bindings.entrySet()) { assertEquals(entry.getValue(), bindings2.get(entry.getKey())); } } } private static void doCheckBindings(Map<String,Integer> labels) { assertTrue("Missing label", labels.keySet().contains("A")); assertTrue("Missing label", labels.keySet().contains("B")); assertTrue("Missing label", labels.keySet().contains("C")); assertTrue("Missing label", labels.keySet().contains("D")); assertTrue("Missing label", labels.keySet().contains("default")); } private static void writeAndRead(Writable toWrite, Writable toRead) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); try { toWrite.write(dos); } finally { Closeables.close(dos, false); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DataInputStream dis = new DataInputStream(bais); try { toRead.readFields(dis); } finally { Closeables.close(dis, true); } } }
gpl-2.0
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/rm/fxch_ST0_ST7.java
1778
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.rm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class fxch_ST0_ST7 extends Executable { public fxch_ST0_ST7(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double tmp = cpu.fpu.ST(0); cpu.fpu.setST(0, cpu.fpu.ST(7)); cpu.fpu.setST(7, tmp); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
geneos/adempiere
base/src/org/compiere/model/I_C_InvoiceBatch.java
7658
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for C_InvoiceBatch * @author Adempiere (generated) * @version Release 3.7.0LTS */ public interface I_C_InvoiceBatch { /** TableName=C_InvoiceBatch */ public static final String Table_Name = "C_InvoiceBatch"; /** AD_Table_ID=767 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 1 - Org */ BigDecimal accessLevel = BigDecimal.valueOf(1); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name C_ConversionType_ID */ public static final String COLUMNNAME_C_ConversionType_ID = "C_ConversionType_ID"; /** Set Currency Type. * Currency Conversion Rate Type */ public void setC_ConversionType_ID (int C_ConversionType_ID); /** Get Currency Type. * Currency Conversion Rate Type */ public int getC_ConversionType_ID(); public org.compiere.model.I_C_ConversionType getC_ConversionType() throws RuntimeException; /** Column name C_Currency_ID */ public static final String COLUMNNAME_C_Currency_ID = "C_Currency_ID"; /** Set Currency. * The Currency for this record */ public void setC_Currency_ID (int C_Currency_ID); /** Get Currency. * The Currency for this record */ public int getC_Currency_ID(); public org.compiere.model.I_C_Currency getC_Currency() throws RuntimeException; /** Column name C_InvoiceBatch_ID */ public static final String COLUMNNAME_C_InvoiceBatch_ID = "C_InvoiceBatch_ID"; /** Set Invoice Batch. * Expense Invoice Batch Header */ public void setC_InvoiceBatch_ID (int C_InvoiceBatch_ID); /** Get Invoice Batch. * Expense Invoice Batch Header */ public int getC_InvoiceBatch_ID(); /** Column name ControlAmt */ public static final String COLUMNNAME_ControlAmt = "ControlAmt"; /** Set Control Amount. * If not zero, the Debit amount of the document must be equal this amount */ public void setControlAmt (BigDecimal ControlAmt); /** Get Control Amount. * If not zero, the Debit amount of the document must be equal this amount */ public BigDecimal getControlAmt(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name DateDoc */ public static final String COLUMNNAME_DateDoc = "DateDoc"; /** Set Document Date. * Date of the Document */ public void setDateDoc (Timestamp DateDoc); /** Get Document Date. * Date of the Document */ public Timestamp getDateDoc(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name DocumentAmt */ public static final String COLUMNNAME_DocumentAmt = "DocumentAmt"; /** Set Document Amt. * Document Amount */ public void setDocumentAmt (BigDecimal DocumentAmt); /** Get Document Amt. * Document Amount */ public BigDecimal getDocumentAmt(); /** Column name DocumentNo */ public static final String COLUMNNAME_DocumentNo = "DocumentNo"; /** Set Document No. * Document sequence number of the document */ public void setDocumentNo (String DocumentNo); /** Get Document No. * Document sequence number of the document */ public String getDocumentNo(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsSOTrx */ public static final String COLUMNNAME_IsSOTrx = "IsSOTrx"; /** Set Sales Transaction. * This is a Sales Transaction */ public void setIsSOTrx (boolean IsSOTrx); /** Get Sales Transaction. * This is a Sales Transaction */ public boolean isSOTrx(); /** Column name Processed */ public static final String COLUMNNAME_Processed = "Processed"; /** Set Processed. * The document has been processed */ public void setProcessed (boolean Processed); /** Get Processed. * The document has been processed */ public boolean isProcessed(); /** Column name Processing */ public static final String COLUMNNAME_Processing = "Processing"; /** Set Process Now */ public void setProcessing (boolean Processing); /** Get Process Now */ public boolean isProcessing(); /** Column name SalesRep_ID */ public static final String COLUMNNAME_SalesRep_ID = "SalesRep_ID"; /** Set Sales Representative. * Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID); /** Get Sales Representative. * Sales Representative or Company Agent */ public int getSalesRep_ID(); public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException; /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); }
gpl-2.0
jmogarrio/tetrad
tetrad-lib/src/test/java/edu/cmu/tetrad/test/FastIcaException.java
2348
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; 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 General Public License for more details. // // // // You should have received a copy of the GNU 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 edu.cmu.tetrad.test; /** * The <code>FastICAException</code> will be thrown if an error occurs * performing the FastIca algorithm. * * @author Michael Lambertz */ public class FastIcaException extends Exception { private static final long serialVersionUID = 3256727268784290100L; public enum Reason { NO_MORE_EIGENVALUES } private Reason reason; /** * This constructor creates a new <code>FastICAException</code> object. */ public FastIcaException(Reason reason) { this.reason = reason; } /** * Returns the reason for throwing this exception. * * @return the reason */ public Reason getReason() { return (this.reason); } }
gpl-2.0
tiagojoao/abycss
jmetal/metaheuristics/spea2/SPEA2_main.java
5708
// SPEA2_main.java // // Author: // Antonio J. Nebro <antonio@lcc.uma.es> // Juan J. Durillo <durillo@lcc.uma.es> // // Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo // // 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 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package jmetal.metaheuristics.spea2; import jmetal.core.Algorithm; import jmetal.core.Operator; import jmetal.core.Problem; import jmetal.core.SolutionSet; import jmetal.operators.crossover.CrossoverFactory; import jmetal.operators.mutation.MutationFactory; import jmetal.operators.selection.SelectionFactory; import jmetal.problems.Kursawe; import jmetal.problems.ProblemFactory; import jmetal.qualityIndicator.QualityIndicator; import jmetal.util.Configuration; import jmetal.util.JMException; import java.io.IOException; import java.util.HashMap; import java.util.logging.FileHandler; import java.util.logging.Logger; /** * Class for configuring and running the SPEA2 algorithm */ public class SPEA2_main { public static Logger logger_ ; // Logger object public static FileHandler fileHandler_ ; // FileHandler object /** * @param args Command line arguments. The first (optional) argument specifies * the problem to solve. * @throws JMException * @throws IOException * @throws SecurityException * Usage: three options * - jmetal.metaheuristics.mocell.MOCell_main * - jmetal.metaheuristics.mocell.MOCell_main problemName * - jmetal.metaheuristics.mocell.MOCell_main problemName ParetoFrontFile */ public static void main(String [] args) throws JMException, IOException, ClassNotFoundException { Problem problem ; // The problem to solve Algorithm algorithm ; // The algorithm to use Operator crossover ; // Crossover operator Operator mutation ; // Mutation operator Operator selection ; // Selection operator QualityIndicator indicators ; // Object to get quality indicators HashMap parameters ; // Operator parameters // Logger object and file to store log messages logger_ = Configuration.logger_ ; fileHandler_ = new FileHandler("SPEA2.log"); logger_.addHandler(fileHandler_) ; indicators = null ; if (args.length == 1) { Object [] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0],params); } // if else if (args.length == 2) { Object [] params = {"Real"}; problem = (new ProblemFactory()).getProblem(args[0],params); indicators = new QualityIndicator(problem, args[1]) ; } // if else { // Default problem problem = new Kursawe("Real", 3); //problem = new Water("Real"); //problem = new ZDT1("ArrayReal", 1000); //problem = new ZDT4("BinaryReal"); //problem = new WFG1("Real"); //problem = new DTLZ1("Real"); //problem = new OKA2("Real") ; } // else algorithm = new SPEA2(problem); // Algorithm parameters algorithm.setInputParameter("populationSize",100); algorithm.setInputParameter("archiveSize",100); algorithm.setInputParameter("maxEvaluations",25000); // Mutation and Crossover for Real codification parameters = new HashMap() ; parameters.put("probability", 0.9) ; parameters.put("distributionIndex", 20.0) ; crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", parameters); parameters = new HashMap() ; parameters.put("probability", 1.0/problem.getNumberOfVariables()) ; parameters.put("distributionIndex", 20.0) ; mutation = MutationFactory.getMutationOperator("PolynomialMutation", parameters); // Selection operator parameters = null ; selection = SelectionFactory.getSelectionOperator("BinaryTournament", parameters) ; // Add the operators to the algorithm algorithm.addOperator("crossover",crossover); algorithm.addOperator("mutation",mutation); algorithm.addOperator("selection",selection); // Execute the algorithm long initTime = System.currentTimeMillis(); SolutionSet population = algorithm.execute(); long estimatedTime = System.currentTimeMillis() - initTime; // Result messages logger_.info("Total execution time: "+estimatedTime + "ms"); logger_.info("Objectives values have been writen to file FUN"); population.printObjectivesToFile("FUN"); logger_.info("Variables values have been writen to file VAR"); population.printVariablesToFile("VAR"); if (indicators != null) { logger_.info("Quality indicators") ; logger_.info("Hypervolume: " + indicators.getHypervolume(population)) ; logger_.info("GD : " + indicators.getGD(population)) ; logger_.info("IGD : " + indicators.getIGD(population)) ; logger_.info("Spread : " + indicators.getSpread(population)) ; logger_.info("Epsilon : " + indicators.getEpsilon(population)) ; } // if }//main } // SPEA2_main.java
gpl-2.0
werman/RadioDroid
app/src/main/java/net/programmierecke/radiodroid2/utils/RecyclerItemSwipeHelper.java
6304
package net.programmierecke.radiodroid2.utils; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.RecyclerView; import com.mikepenz.iconics.IconicsColor; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.iconics.IconicsSize; import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial; import net.programmierecke.radiodroid2.R; import net.programmierecke.radiodroid2.Utils; public class RecyclerItemSwipeHelper<ViewHolderType extends SwipeableViewHolder> extends ItemTouchHelper.SimpleCallback { public interface SwipeCallback<ViewHolderType> { void onSwiped(ViewHolderType viewHolder, int direction); } private SwipeCallback<ViewHolderType> swipeListener; private boolean swipeToDeleteIsEnabled; private IconicsDrawable icon; private final ColorDrawable background; public RecyclerItemSwipeHelper(Context context, int dragDirs, int swipeDirs, SwipeCallback<ViewHolderType> swipeListener) { super(dragDirs, swipeDirs); this.swipeListener = swipeListener; swipeToDeleteIsEnabled = ((swipeDirs & ItemTouchHelper.LEFT) > 0) || ((swipeDirs & ItemTouchHelper.RIGHT) > 0); background = new ColorDrawable(Utils.themeAttributeToColor(R.attr.swipeDeleteBackgroundColor, context, Color.RED)); if (swipeToDeleteIsEnabled) { icon = new IconicsDrawable(context, GoogleMaterial.Icon.gmd_delete_sweep) .size(IconicsSize.dp(48)) .color(IconicsColor.colorInt(Utils.themeAttributeToColor(R.attr.swipeDeleteIconColor, context, Color.WHITE))); } } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { if (viewHolder != null) { final View foregroundView = ((SwipeableViewHolder) viewHolder).getForegroundView(); getDefaultUIUtil().onSelected(foregroundView); } } @Override public void onChildDrawOver(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { final View foregroundView = ((SwipeableViewHolder) viewHolder).getForegroundView(); getDefaultUIUtil().onDrawOver(c, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive); } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { final View foregroundView = ((SwipeableViewHolder) viewHolder).getForegroundView(); getDefaultUIUtil().clearView(foregroundView); } private void drawSwipeToDeleteBackground(Canvas c, View itemView, float dX, float dY) { int backgroundCornerOffset = 20; int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2; int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2; int iconBottom = iconTop + icon.getIntrinsicHeight(); if (dX > 0) { // Swiping to the right int iconRight = itemView.getLeft() + iconMargin + icon.getIntrinsicWidth(); int iconLeft = itemView.getLeft() + iconMargin; int magicConstraint = (itemView.getLeft() + ((int) dX) < iconRight + iconMargin) ? (int)dX - icon.getIntrinsicWidth() - ( iconMargin * 2 ) : 0; iconLeft += magicConstraint; iconRight += magicConstraint; icon.setBounds(iconLeft, iconTop, iconRight, iconBottom); background.setBounds(itemView.getLeft(), itemView.getTop(), itemView.getLeft() + ((int) dX), itemView.getBottom()); } else if (dX < 0) { // Swiping to the left int iconRight = itemView.getRight()- iconMargin; int iconLeft = itemView.getRight()- iconMargin - icon.getIntrinsicWidth(); int magicConstraint = (itemView.getRight() + ((int) dX) > iconLeft - iconMargin) ? icon.getIntrinsicWidth() + ( iconMargin * 2 ) + (int)dX : 0; iconLeft += magicConstraint; iconRight += magicConstraint; icon.setBounds(iconLeft, iconTop, iconRight, iconBottom); background.setBounds(itemView.getRight(), itemView.getTop(), itemView.getRight() + ((int) dX), itemView.getBottom()); } else { // view is unSwiped icon.setBounds(0, 0, 0, 0); background.setBounds(0, 0, 0, 0); } background.draw(c); icon.draw(c); } @Override public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { final View foregroundView = ((SwipeableViewHolder) viewHolder).getForegroundView(); if (swipeToDeleteIsEnabled) { drawSwipeToDeleteBackground(c, viewHolder.itemView, dX, dY); } getDefaultUIUtil().onDraw(c, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive); } @Override public boolean isLongPressDragEnabled() { return false; } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { @SuppressWarnings("unchecked") ViewHolderType viewHolderType = (ViewHolderType) viewHolder; swipeListener.onSwiped(viewHolderType, direction); } @Override public float getSwipeVelocityThreshold(float defaultValue) { // Effectively disable flinging because it's too easy to accidentally perform it. return 1; } @Override public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) { // Since flinging is disabled we reduce swipe threshold. return 0.35f; } }
gpl-3.0
dested/CraftbukkitMaps
src/main/java/net/minecraft/server/WorldGenTaiga1.java
3526
package net.minecraft.server; import java.util.Random; import org.bukkit.BlockChangeDelegate; // CraftBukkit public class WorldGenTaiga1 extends WorldGenerator { public WorldGenTaiga1() {} public boolean a(World world, Random random, int i, int j, int k) { // CraftBukkit start // sk: The idea is to have (our) WorldServer implement // BlockChangeDelegate and then we can implicitly cast World to // WorldServer (a safe cast, AFAIK) and no code will be broken. This // then allows plugins to catch manually-invoked generation events return generate((BlockChangeDelegate) world, random, i, j, k); } public boolean generate(BlockChangeDelegate world, Random random, int i, int j, int k) { // CraftBukkit end int l = random.nextInt(5) + 7; int i1 = l - random.nextInt(2) - 3; int j1 = l - i1; int k1 = 1 + random.nextInt(j1 + 1); boolean flag = true; if (j >= 1 && j + l + 1 <= 128) { int l1; int i2; int j2; int k2; int l2; for (l1 = j; l1 <= j + 1 + l && flag; ++l1) { boolean flag1 = true; if (l1 - j < i1) { l2 = 0; } else { l2 = k1; } for (i2 = i - l2; i2 <= i + l2 && flag; ++i2) { for (j2 = k - l2; j2 <= k + l2 && flag; ++j2) { if (l1 >= 0 && l1 < 128) { k2 = world.getTypeId(i2, l1, j2); if (k2 != 0 && k2 != Block.LEAVES.id) { flag = false; } } else { flag = false; } } } } if (!flag) { return false; } else { l1 = world.getTypeId(i, j - 1, k); if ((l1 == Block.GRASS.id || l1 == Block.DIRT.id) && j < 128 - l - 1) { world.setRawTypeId(i, j - 1, k, Block.DIRT.id); l2 = 0; for (i2 = j + l; i2 >= j + i1; --i2) { for (j2 = i - l2; j2 <= i + l2; ++j2) { k2 = j2 - i; for (int i3 = k - l2; i3 <= k + l2; ++i3) { int j3 = i3 - k; if ((Math.abs(k2) != l2 || Math.abs(j3) != l2 || l2 <= 0) && !Block.o[world.getTypeId(j2, i2, i3)]) { world.setRawTypeIdAndData(j2, i2, i3, Block.LEAVES.id, 1); } } } if (l2 >= 1 && i2 == j + i1 + 1) { --l2; } else if (l2 < k1) { ++l2; } } for (i2 = 0; i2 < l - 1; ++i2) { j2 = world.getTypeId(i, j + i2, k); if (j2 == 0 || j2 == Block.LEAVES.id) { world.setRawTypeIdAndData(i, j + i2, k, Block.LOG.id, 1); } } return true; } else { return false; } } } else { return false; } } }
gpl-3.0
ngcurrier/ProteusCFD
TPLs/hdf5/hdf5-1.10.2/java/test/TestH5R.java
11554
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * * If you do not have access to either file, you may request a copy from * * help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import hdf.hdf5lib.H5; import hdf.hdf5lib.HDF5Constants; import hdf.hdf5lib.exceptions.HDF5Exception; import hdf.hdf5lib.exceptions.HDF5LibraryException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; public class TestH5R { @Rule public TestName testname = new TestName(); private static final String H5_FILE = "testH5R.h5"; private static final int DIM_X = 4; private static final int DIM_Y = 6; long H5fid = -1; long H5dsid = -1; long H5did = -1; long H5gid = -1; long H5did2 = -1; long[] H5dims = { DIM_X, DIM_Y }; private final void _deleteFile(String filename) { File file = null; try { file = new File(filename); } catch (Throwable err) {} if (file.exists()) { try {file.delete();} catch (SecurityException e) {} } } private final long _createDataset(long fid, long dsid, String name, long dapl) { long did = -1; try { did = H5.H5Dcreate(fid, name, HDF5Constants.H5T_STD_I32BE, dsid, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT, dapl); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Dcreate: " + err); } assertTrue("TestH5R._createDataset: ",did > 0); return did; } private final long _createGroup(long fid, String name) { long gid = -1; try { gid = H5.H5Gcreate(fid, name, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Gcreate: " + err); } assertTrue("TestH5R._createGroup: ",gid > 0); return gid; } @Before public void createH5file() throws NullPointerException, HDF5Exception { assertTrue("H5 open ids is 0",H5.getOpenIDCount()==0); System.out.print(testname.getMethodName()); try { H5fid = H5.H5Fcreate(H5_FILE, HDF5Constants.H5F_ACC_TRUNC, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT); H5dsid = H5.H5Screate_simple(2, H5dims, null); H5gid = _createGroup(H5fid, "Group1"); H5did2 = _createDataset(H5gid, H5dsid, "dset2", HDF5Constants.H5P_DEFAULT); H5did = _createDataset(H5fid, H5dsid, "dset", HDF5Constants.H5P_DEFAULT); } catch (Throwable err) { err.printStackTrace(); fail("TestH5R.createH5file: " + err); } assertTrue("TestH5R.createH5file: H5.H5Fcreate: ",H5fid > 0); assertTrue("TestH5R.createH5file: H5.H5Screate_simple: ",H5dsid > 0); assertTrue("TestH5R.createH5file: _createDataset: ",H5did > 0); H5.H5Fflush(H5fid, HDF5Constants.H5F_SCOPE_LOCAL); } @After public void deleteH5file() throws HDF5LibraryException { if (H5dsid > 0) try {H5.H5Sclose(H5dsid);} catch (Exception ex) {} if (H5did > 0) try {H5.H5Dclose(H5did);} catch (Exception ex) {} if (H5fid > 0) try {H5.H5Fclose(H5fid);} catch (Exception ex) {} if (H5gid > 0) try {H5.H5Gclose(H5gid);} catch (Exception ex) {} if (H5did2 > 0) try {H5.H5Dclose(H5did2);} catch (Exception ex) {} _deleteFile(H5_FILE); System.out.println(); } @Test public void testH5Rget_name() { long loc_id=H5fid; int ref_type=HDF5Constants.H5R_OBJECT; long ret_val=-1; byte[] ref=null; String[] name= {""}; String objName = "/dset"; try { ref = H5.H5Rcreate(H5fid, objName, ref_type, -1); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Rget_name:H5Rcreate " + err); } try { ret_val = H5.H5Rget_name(loc_id, ref_type, ref, name, 16); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Rget_name: " + err); } assertTrue("testH5Rget_name: H5Rget_name", ret_val>0); assertTrue("The name of the object: ", objName.equals(name[0])); } @Test public void testH5Rget_obj_type2() { int ref_type=HDF5Constants.H5R_OBJECT; byte[] ref=null; String objName = "/dset"; int obj_type = -1;; try { ref = H5.H5Rcreate(H5fid, objName, ref_type, -1); } catch(Throwable err) { err.printStackTrace(); } try { obj_type = H5.H5Rget_obj_type(H5fid, HDF5Constants.H5R_OBJECT, ref); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Rget_obj_type2: " + err); } assertEquals(obj_type, HDF5Constants.H5O_TYPE_DATASET); } @Test public void testH5Rcreate_refobj() { byte[] ref = null; try { ref = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_OBJECT, -1); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Rcreate: " + err); } assertNotNull(ref); } @Test public void testH5Rcreate_regionrefobj() { byte[] ref = null; try { ref = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_DATASET_REGION, H5dsid); } catch (Throwable err) { err.printStackTrace(); fail("H5.H5Rcreate: " + err); } assertNotNull(ref); } @Test public void testH5Rdereference() { byte[] ref1 = null; byte[] ref2 = null; long dataset_id = -1; long group_id = -1; try { //Create reference on dataset ref1 = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_DATASET_REGION, H5dsid); dataset_id= H5.H5Rdereference(H5fid, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5R_DATASET_REGION, ref1); //Create reference on group ref2 = H5.H5Rcreate(H5gid, "/Group1", HDF5Constants.H5R_OBJECT, -1); group_id= H5.H5Rdereference(H5gid, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5R_OBJECT, ref2); assertNotNull(ref1); assertNotNull(ref2); assertTrue(dataset_id>=0); assertTrue(group_id>=0); } catch (Throwable err) { err.printStackTrace(); fail("TestH5Rdereference " + err); } finally { try {H5.H5Dclose(dataset_id);} catch (Exception ex) {} try {H5.H5Gclose(group_id);} catch (Exception ex) {} } } @Test public void testH5Rget_region() { byte[] ref = null; long dsid = -1; try { ref = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_DATASET_REGION, H5dsid); dsid = H5.H5Rget_region(H5fid, HDF5Constants.H5R_DATASET_REGION, ref); assertNotNull(ref); assertTrue(dsid>=0); } catch (Throwable err) { err.printStackTrace(); fail("TestH5Rget_region: " + err); } finally { try {H5.H5Sclose(dsid);} catch (Exception ex) {} } } @Test(expected = IllegalArgumentException.class) public void testH5Rget_name_Invalidreftype() throws Throwable { byte[] ref = null; String[] name= {""}; ref = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_OBJECT, -1); H5.H5Rget_name(H5fid, HDF5Constants.H5R_DATASET_REGION, ref, name, 16); } @Test(expected = NullPointerException.class) public void testH5Rget_name_NULLreference() throws Throwable { byte[] ref = null; String[] name= {""}; H5.H5Rget_name(H5fid, HDF5Constants.H5R_OBJECT, ref, name, 16); } @Test(expected = HDF5LibraryException.class) public void testH5Rget_obj_type2_Invalidreftype() throws Throwable { byte[] ref = null; ref = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_OBJECT, -1); H5.H5Rget_obj_type(H5fid, HDF5Constants.H5R_DATASET_REGION, ref); } @Test(expected = HDF5LibraryException.class) public void testH5Rcreate_InvalidObjectName() throws Throwable { H5.H5Rcreate(H5fid, "/GROUPS", HDF5Constants.H5R_OBJECT, -1); } @Test(expected = HDF5LibraryException.class) public void testH5Rcreate_Invalidspace_id() throws Throwable { H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_DATASET_REGION, -1); } @Test(expected = IllegalArgumentException.class) public void testH5Rcreate_Invalidreftype() throws Throwable { H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_BADTYPE, -1); } @Test(expected = IllegalArgumentException.class) public void testH5Rgetregion_Invalidreftype() throws Throwable { byte[] ref = null; ref = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_OBJECT, H5dsid); H5.H5Rget_region(H5fid, HDF5Constants.H5R_DATASET_REGION, ref); } @Test(expected = IllegalArgumentException.class) public void testH5Rgetregion_Badreferencetype() throws Throwable { byte[] ref = null; ref = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_OBJECT, H5dsid); H5.H5Rget_region(H5fid, HDF5Constants.H5R_OBJECT, ref); } @Test(expected = NullPointerException.class) public void testH5Rgetregion_Nullreference() throws Throwable { byte[] ref = null; H5.H5Rget_region(H5fid, HDF5Constants.H5R_DATASET_REGION, ref); } @Test(expected = NullPointerException.class) public void testH5Rdereference_Nullreference() throws Throwable { byte[] ref = null; H5.H5Rdereference(H5did2, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5R_OBJECT, ref); } @Test(expected = IllegalArgumentException.class) public void testH5Rdereference_Invalidreference() throws Throwable { byte[] ref1 = null; byte[] ref2 = null; ref1 = H5.H5Rcreate(H5fid, "/dset", HDF5Constants.H5R_DATASET_REGION, H5dsid); ref2 = H5.H5Rcreate(H5gid, "/Group1", HDF5Constants.H5R_OBJECT, -1); H5.H5Rdereference(H5gid, HDF5Constants.H5P_DEFAULT, HDF5Constants.H5R_OBJECT, ref1); } }
gpl-3.0
kevin-wayne/algs4
src/main/java/edu/princeton/cs/algs4/Accumulator.java
4963
/****************************************************************************** * Compilation: javac Accumulator.java * Execution: java Accumulator < input.txt * Dependencies: StdOut.java StdIn.java * * Mutable data type that calculates the mean, sample standard * deviation, and sample variance of a stream of real numbers * use a stable, one-pass algorithm. * ******************************************************************************/ package edu.princeton.cs.algs4; /** * The {@code Accumulator} class is a data type for computing the running * mean, sample standard deviation, and sample variance of a stream of real * numbers. It provides an example of a mutable data type and a streaming * algorithm. * <p> * This implementation uses a one-pass algorithm that is less susceptible * to floating-point roundoff error than the more straightforward * implementation based on saving the sum of the squares of the numbers. * This technique is due to * <a href = "https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm">B. P. Welford</a>. * Each operation takes constant time in the worst case. * The amount of memory is constant - the data values are not stored. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/12oop">Section 1.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Accumulator { private int n = 0; // number of data values private double sum = 0.0; // sample variance * (n-1) private double mu = 0.0; // sample mean /** * Initializes an accumulator. */ public Accumulator() { } /** * Adds the specified data value to the accumulator. * @param x the data value */ public void addDataValue(double x) { n++; double delta = x - mu; mu += delta / n; sum += (double) (n - 1) / n * delta * delta; } /** * Returns the mean of the data values. * @return the mean of the data values */ public double mean() { return mu; } /** * Returns the sample variance of the data values. * @return the sample variance of the data values */ public double var() { if (n <= 1) return Double.NaN; return sum / (n - 1); } /** * Returns the sample standard deviation of the data values. * @return the sample standard deviation of the data values */ public double stddev() { return Math.sqrt(this.var()); } /** * Returns the number of data values. * @return the number of data values */ public int count() { return n; } /** * Returns a string representation of this accumulator. * @return a string representation of this accumulator */ public String toString() { return "n = " + n + ", mean = " + mean() + ", stddev = " + stddev(); } /** * Unit tests the {@code Accumulator} data type. * Reads in a stream of real number from standard input; * adds them to the accumulator; and prints the mean, * sample standard deviation, and sample variance to standard * output. * * @param args the command-line arguments */ public static void main(String[] args) { Accumulator stats = new Accumulator(); while (!StdIn.isEmpty()) { double x = StdIn.readDouble(); stats.addDataValue(x); } StdOut.printf("n = %d\n", stats.count()); StdOut.printf("mean = %.5f\n", stats.mean()); StdOut.printf("stddev = %.5f\n", stats.stddev()); StdOut.printf("var = %.5f\n", stats.var()); StdOut.println(stats); } } /****************************************************************************** * Copyright 2002-2020, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
gpl-3.0
yuhang-lin/moa
moa/src/main/java/moa/classifiers/rules/featureranking/MeritFeatureRanking.java
5123
/* * MeritFeatureRanking.java * Copyright (C) 2017 University of Porto, Portugal * @author J. Duarte, J. Gama * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package moa.classifiers.rules.featureranking; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import moa.classifiers.rules.featureranking.messages.ChangeDetectedMessage; import moa.classifiers.rules.featureranking.messages.MeritCheckMessage; import moa.classifiers.rules.featureranking.messages.RuleExpandedMessage; import moa.classifiers.rules.multilabel.core.ObservableMOAObject; import moa.core.DoubleVector; /** * Merit Feature Ranking method * João Duarte, João Gama,Feature ranking in hoeffding algorithms for regression. SAC 2017: 836-841 */ public class MeritFeatureRanking extends AbstractFeatureRanking implements FeatureRanking{ /** * */ private static final long serialVersionUID = 1L; protected DoubleVector attributeImportance; protected HashMap<ObservableMOAObject, RuleInformation> ruleInformation; public MeritFeatureRanking() { super(); this.attributeImportance = new DoubleVector(); this.ruleInformation = new HashMap<ObservableMOAObject, RuleInformation>(); } public void update(ObservableMOAObject o, Object arg) { if (arg instanceof MeritCheckMessage){ RuleInformation ri=ruleInformation.get(o); if(ri==null) { ri=new RuleInformation(); ruleInformation.put(o, ri); } DoubleVector merits=ri.getCurrent(); if(!ri.isFirstAfterExpansion()) this.attributeImportance.subtractValues(merits); MeritCheckMessage msg = (MeritCheckMessage) arg; ri.updateCurrent(msg.getMerits()); merits=ri.getCurrent(); this.attributeImportance.addValues(merits); } else if (arg instanceof RuleExpandedMessage){ RuleInformation ri=ruleInformation.get(o); if(!((RuleExpandedMessage)arg).isSpecialization()) ri.addNumLiterals(); } else if (arg instanceof ChangeDetectedMessage) { RuleInformation ri=ruleInformation.get(o); this.attributeImportance.subtractValues(ri.getAccumulated()); ruleInformation.remove(o); } } @Override public DoubleVector getFeatureRankings() { /*DoubleVector normRankings=null; if(attributeImportance!=null){ double total=0; for (int i=0; i<attributeImportance.numValues();i++) total+=attributeImportance.getValue(i); // normRankings=new DoubleVector(); double[] aux= new double[attributeImportance.numValues()]; for (int i=0; i<attributeImportance.numValues();i++) aux[i]=attributeImportance.getValue(i)/total; normRankings= new DoubleVector(aux); } return normRankings; */ if(attributeImportance==null) return new DoubleVector(); return attributeImportance; } public DoubleVector getAccumulated() { DoubleVector accumulated= new DoubleVector(); Iterator <Entry<ObservableMOAObject, RuleInformation>> it=this.ruleInformation.entrySet().iterator(); while (it.hasNext()) { Map.Entry<ObservableMOAObject, RuleInformation> pair = (Map.Entry<ObservableMOAObject, RuleInformation>)it.next(); accumulated.addValues(pair.getValue().getAccumulated()); } return accumulated; } /* * Rule information class */ public class RuleInformation{ private DoubleVector accumulated; private DoubleVector current; //private HashMap<Integer, Integer> literalAttributes; private boolean isFirstAfterExpansion; private int numLiterals; public RuleInformation() { //literalAttributes=new HashMap<Integer, Integer>(); isFirstAfterExpansion=false; accumulated=new DoubleVector(); current=new DoubleVector(); numLiterals=0; } public DoubleVector getAccumulated() { return accumulated; } public DoubleVector getCurrent() { return current; } public void updateCurrent(DoubleVector merits){ DoubleVector newMerits=new DoubleVector(merits); if(!isFirstAfterExpansion){ accumulated.subtractValues(current); } newMerits.scaleValues(1.0/(1+numLiterals)); accumulated.addValues(newMerits); current=newMerits; isFirstAfterExpansion=false; } public void addNumLiterals() { /*boolean contains=false; Iterator<Integer> it=literalAttributes.iterator(); while (it.hasNext() && !contains){ if(it.next()==attribIndex) contains=true; } if(!contains){ literalAttributes.add(attribIndex); }*/ this.numLiterals++; isFirstAfterExpansion=true; } public boolean isFirstAfterExpansion() { return isFirstAfterExpansion; } } }
gpl-3.0
DanVanAtta/triplea
game-core/src/main/java/games/strategy/engine/lobby/client/ui/action/player/info/PlayerInfoSummaryTextArea.java
1603
package games.strategy.engine.lobby.client.ui.action.player.info; import com.google.common.annotations.VisibleForTesting; import java.sql.Date; import java.text.DateFormat; import java.time.Instant; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JTextPane; import lombok.experimental.UtilityClass; import org.triplea.http.client.lobby.moderator.PlayerSummary; import org.triplea.swing.SwingComponents; @UtilityClass class PlayerInfoSummaryTextArea { /** Returns a text area with the players name, their IP and system ID. */ JComponent buildPlayerInfoSummary(final JDialog dialog, final PlayerSummary playerSummary) { final JTextPane textPane = new JTextPane(); textPane.setEditable(false); textPane.setText(buildPlayerInfoText(playerSummary)); textPane.addKeyListener(SwingComponents.escapeKeyListener(dialog::dispose)); return textPane; } @VisibleForTesting static String buildPlayerInfoText(final PlayerSummary playerSummary) { return (playerSummary.getRegistrationDateEpochMillis() == null ? "Not registered" : "Registered on: " + formatEpochMillis(playerSummary.getRegistrationDateEpochMillis())) + (playerSummary.getIp() == null ? "" : "\nIP: " + playerSummary.getIp()) + (playerSummary.getSystemId() == null ? "" : "\nSystem ID: " + playerSummary.getSystemId()); } private static String formatEpochMillis(final long epochMillis) { return DateFormat.getDateInstance(DateFormat.MEDIUM) // .format(Date.from(Instant.ofEpochMilli(epochMillis))); } }
gpl-3.0
Letractively/micrite
plugins/struts2/src/main/java/org/gaixie/micrite/struts2/json/package-info.java
135
/** * 提供用于将Struts2返回值转化为json对象的类. * <p> * * @since 0.4 */ package org.gaixie.micrite.struts2.json;
gpl-3.0
FAIMS/faims-android
faimsandroidapp/src/main/java/au/org/intersect/faims/android/nutiteq/CustomOgrLayer.java
978
package au.org.intersect.faims.android.nutiteq; import java.io.IOException; import com.nutiteq.layers.vector.OgrLayer; import com.nutiteq.projections.Projection; import com.nutiteq.style.LineStyle; import com.nutiteq.style.PointStyle; import com.nutiteq.style.PolygonStyle; import com.nutiteq.style.StyleSet; public class CustomOgrLayer extends OgrLayer { private String name; private int layerId; public CustomOgrLayer(int layerId, String name, Projection proj, String fileName, String tableName, int maxObjects, StyleSet<PointStyle> pointStyleSet, StyleSet<LineStyle> lineStyleSet, StyleSet<PolygonStyle> polygonStyleSet) throws IOException { super(proj, fileName, tableName, maxObjects, pointStyleSet, lineStyleSet, polygonStyleSet); this.name = name; this.layerId = layerId; } public String getName() { return name; } public void setName(String layerName) { this.name = layerName; } public int getLayerId() { return layerId; } }
gpl-3.0
CosmicDan-Minecraft/AncientWarfare2_CosmicDanFork
src/main/java/net/shadowmage/ancientwarfare/automation/gui/GuiTorqueGeneratorSterling.java
1855
package net.shadowmage.ancientwarfare.automation.gui; import net.minecraft.util.StatCollector; import net.shadowmage.ancientwarfare.automation.container.ContainerTorqueGeneratorSterling; import net.shadowmage.ancientwarfare.core.container.ContainerBase; import net.shadowmage.ancientwarfare.core.gui.GuiContainerBase; import net.shadowmage.ancientwarfare.core.gui.elements.Label; import net.shadowmage.ancientwarfare.core.gui.elements.ProgressBar; public class GuiTorqueGeneratorSterling extends GuiContainerBase<ContainerTorqueGeneratorSterling> { private Label energyLabel; private ProgressBar pg; private ProgressBar pg1; public GuiTorqueGeneratorSterling(ContainerBase par1Container) { super(par1Container, 178, ((ContainerTorqueGeneratorSterling) par1Container).guiHeight); } @Override public void initElements() { pg1 = new ProgressBar(8, 8, 178 - 16, 10); addGuiElement(pg1); energyLabel = new Label(8, 8, StatCollector.translateToLocalFormatted("guistrings.automation.current_energy", String.format("%.2f",getContainer().energy))); addGuiElement(energyLabel); pg = new ProgressBar(8, 8 + 10 + 18 + 4, 178 - 16, 16); addGuiElement(pg); } @Override public void setupElements() { energyLabel.setText(StatCollector.translateToLocalFormatted("guistrings.automation.current_energy", String.format("%.2f",getContainer().energy))); float progress = 0; if (getContainer().burnTimeBase > 0) { progress = (float) getContainer().burnTime / (float) getContainer().burnTimeBase; } pg.setProgress(progress); progress = (float) getContainer().energy / (float) getContainer().tileEntity.getMaxTorque(null); pg1.setProgress(progress); } }
gpl-3.0
Free-Software-for-Android/AdAway
sentrystub/src/main/java/io/sentry/Breadcrumb.java
183
package io.sentry; public class Breadcrumb { public void setMessage(String message) { // Stub } public void setLevel(SentryLevel info) { // Stub } }
gpl-3.0
iheanyi/TextSecure
src/org/thoughtcrime/securesms/PassphraseRequiredSherlockFragmentActivity.java
999
package org.thoughtcrime.securesms; import android.os.Bundle; import org.thoughtcrime.securesms.crypto.MasterSecret; import com.actionbarsherlock.app.SherlockFragmentActivity; public class PassphraseRequiredSherlockFragmentActivity extends SherlockFragmentActivity implements PassphraseRequiredActivity { private final PassphraseRequiredMixin delegate = new PassphraseRequiredMixin(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); delegate.onCreate(this, this); } @Override protected void onResume() { super.onResume(); delegate.onResume(this, this); } @Override protected void onPause() { super.onPause(); delegate.onPause(this, this); } @Override protected void onDestroy() { super.onDestroy(); delegate.onDestroy(this, this); } @Override public void onMasterSecretCleared() { finish(); } @Override public void onNewMasterSecret(MasterSecret masterSecret) {} }
gpl-3.0
Severed-Infinity/technium
build/tmp/recompileMc/sources/net/minecraft/village/MerchantRecipeList.java
5091
package net.minecraft.village; import java.io.IOException; import java.util.ArrayList; import javax.annotation.Nullable; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTUtil; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class MerchantRecipeList extends ArrayList<MerchantRecipe> { public MerchantRecipeList() { } public MerchantRecipeList(NBTTagCompound compound) { this.readRecipiesFromTags(compound); } /** * can par1,par2 be used to in crafting recipe par3 */ @Nullable public MerchantRecipe canRecipeBeUsed(ItemStack stack0, ItemStack stack1, int index) { if (index > 0 && index < this.size()) { MerchantRecipe merchantrecipe1 = (MerchantRecipe)this.get(index); return !this.areItemStacksExactlyEqual(stack0, merchantrecipe1.getItemToBuy()) || (!stack1.isEmpty() || merchantrecipe1.hasSecondItemToBuy()) && (!merchantrecipe1.hasSecondItemToBuy() || !this.areItemStacksExactlyEqual(stack1, merchantrecipe1.getSecondItemToBuy())) || stack0.getCount() < merchantrecipe1.getItemToBuy().getCount() || merchantrecipe1.hasSecondItemToBuy() && stack1.getCount() < merchantrecipe1.getSecondItemToBuy().getCount() ? null : merchantrecipe1; } else { for (int i = 0; i < this.size(); ++i) { MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); if (this.areItemStacksExactlyEqual(stack0, merchantrecipe.getItemToBuy()) && stack0.getCount() >= merchantrecipe.getItemToBuy().getCount() && (!merchantrecipe.hasSecondItemToBuy() && stack1.isEmpty() || merchantrecipe.hasSecondItemToBuy() && this.areItemStacksExactlyEqual(stack1, merchantrecipe.getSecondItemToBuy()) && stack1.getCount() >= merchantrecipe.getSecondItemToBuy().getCount())) { return merchantrecipe; } } return null; } } private boolean areItemStacksExactlyEqual(ItemStack stack1, ItemStack stack2) { return ItemStack.areItemsEqual(stack1, stack2) && (!stack2.hasTagCompound() || stack1.hasTagCompound() && NBTUtil.areNBTEquals(stack2.getTagCompound(), stack1.getTagCompound(), false)); } public void writeToBuf(PacketBuffer buffer) { buffer.writeByte((byte)(this.size() & 255)); for (int i = 0; i < this.size(); ++i) { MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); buffer.writeItemStack(merchantrecipe.getItemToBuy()); buffer.writeItemStack(merchantrecipe.getItemToSell()); ItemStack itemstack = merchantrecipe.getSecondItemToBuy(); buffer.writeBoolean(!itemstack.isEmpty()); if (!itemstack.isEmpty()) { buffer.writeItemStack(itemstack); } buffer.writeBoolean(merchantrecipe.isRecipeDisabled()); buffer.writeInt(merchantrecipe.getToolUses()); buffer.writeInt(merchantrecipe.getMaxTradeUses()); } } public void readRecipiesFromTags(NBTTagCompound compound) { NBTTagList nbttaglist = compound.getTagList("Recipes", 10); for (int i = 0; i < nbttaglist.tagCount(); ++i) { NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); this.add(new MerchantRecipe(nbttagcompound)); } } public NBTTagCompound getRecipiesAsTags() { NBTTagCompound nbttagcompound = new NBTTagCompound(); NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.size(); ++i) { MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); nbttaglist.appendTag(merchantrecipe.writeToTags()); } nbttagcompound.setTag("Recipes", nbttaglist); return nbttagcompound; } @SideOnly(Side.CLIENT) public static MerchantRecipeList readFromBuf(PacketBuffer buffer) throws IOException { MerchantRecipeList merchantrecipelist = new MerchantRecipeList(); int i = buffer.readByte() & 255; for (int j = 0; j < i; ++j) { ItemStack itemstack = buffer.readItemStack(); ItemStack itemstack1 = buffer.readItemStack(); ItemStack itemstack2 = ItemStack.EMPTY; if (buffer.readBoolean()) { itemstack2 = buffer.readItemStack(); } boolean flag = buffer.readBoolean(); int k = buffer.readInt(); int l = buffer.readInt(); MerchantRecipe merchantrecipe = new MerchantRecipe(itemstack, itemstack2, itemstack1, k, l); if (flag) { merchantrecipe.compensateToolUses(); } merchantrecipelist.add(merchantrecipe); } return merchantrecipelist; } }
gpl-3.0
lveci/nest
beam/beam-visat-rcp/src/test/java/org/esa/beam/visat/toolviews/stat/ProfileDataTableModelTest.java
9571
package org.esa.beam.visat.toolviews.stat; import org.esa.beam.framework.datamodel.*; import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.simple.SimpleFeatureImpl; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.filter.identity.FeatureIdImpl; import org.junit.Before; import org.junit.Test; import org.opengis.feature.simple.SimpleFeatureType; import javax.swing.table.TableModel; import java.awt.geom.Path2D; import static org.junit.Assert.assertEquals; /** * @author Norman Fomferra */ public class ProfileDataTableModelTest { private Product product; private Band band; private Path2D path; private ProfilePlotPanel.DataSourceConfig dataSourceConfig; @Before public void setUp() throws Exception { // Draw a "Z" path = new Path2D.Double(); path.moveTo(0, 0); path.lineTo(3, 0); path.lineTo(0, 3); path.lineTo(3, 3); product = new Product("p", "t", 4, 4); band = product.addBand("b", "4 * (Y-0.5) + (X-0.5) + 0.1"); dataSourceConfig = new ProfilePlotPanel.DataSourceConfig(); SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder(); ftb.setName("ft"); ftb.add("lat", Double.class); ftb.add("lon", Double.class); ftb.add("data", Double.class); SimpleFeatureType ft = ftb.buildFeatureType(); DefaultFeatureCollection fc = new DefaultFeatureCollection("id", ft); fc.add(new SimpleFeatureImpl(new Object[]{0, 0, 0.3}, ft, new FeatureIdImpl("id1"), false)); fc.add(new SimpleFeatureImpl(new Object[]{0, 0, 0.5}, ft, new FeatureIdImpl("id2"), false)); fc.add(new SimpleFeatureImpl(new Object[]{0, 0, 0.7}, ft, new FeatureIdImpl("id3"), false)); fc.add(new SimpleFeatureImpl(new Object[]{0, 0, 0.1}, ft, new FeatureIdImpl("id4"), false)); dataSourceConfig.pointDataSource = new VectorDataNode("vd", fc); dataSourceConfig.dataField = ft.getDescriptor("data"); dataSourceConfig.boxSize = 1; dataSourceConfig.computeInBetweenPoints = true; } @Test public void testModelWithCorrData() throws Exception { TransectProfileData profileData = new TransectProfileDataBuilder() .raster(band) .path(path) .boxSize(dataSourceConfig.boxSize) .build(); TableModel tableModel = new ProfileDataTableModel(band.getName(), profileData, dataSourceConfig); assertEquals(10, tableModel.getColumnCount()); assertEquals("pixel_no", tableModel.getColumnName(0)); assertEquals("pixel_x", tableModel.getColumnName(1)); assertEquals("pixel_y", tableModel.getColumnName(2)); assertEquals("latitude", tableModel.getColumnName(3)); assertEquals("longitude", tableModel.getColumnName(4)); assertEquals("b_mean", tableModel.getColumnName(5)); assertEquals("b_sigma", tableModel.getColumnName(6)); assertEquals("data_ref", tableModel.getColumnName(7)); assertEquals("lat_ref", tableModel.getColumnName(8)); assertEquals("lon_ref", tableModel.getColumnName(9)); assertEquals(10, tableModel.getRowCount()); assertEquals(1, tableModel.getValueAt(0, 0)); assertEquals(0.0, tableModel.getValueAt(0, 1)); assertEquals(0.0, tableModel.getValueAt(0, 2)); assertEquals(null, tableModel.getValueAt(0, 3)); assertEquals(null, tableModel.getValueAt(0, 4)); assertEquals(0.1F, tableModel.getValueAt(0, 5)); assertEquals(0.0F, tableModel.getValueAt(0, 6)); assertEquals(0.3, tableModel.getValueAt(0, 7)); assertEquals(0, tableModel.getValueAt(0, 8)); assertEquals(0, tableModel.getValueAt(0, 9)); assertEquals(2, tableModel.getValueAt(1, 0)); assertEquals(1.0, tableModel.getValueAt(1, 1)); assertEquals(0.0, tableModel.getValueAt(1, 2)); assertEquals(null, tableModel.getValueAt(1, 3)); assertEquals(null, tableModel.getValueAt(1, 4)); assertEquals(1.1F, tableModel.getValueAt(1, 5)); assertEquals(0.0F, tableModel.getValueAt(1, 6)); assertEquals(null, tableModel.getValueAt(1, 7)); assertEquals(null, tableModel.getValueAt(1, 8)); assertEquals(null, tableModel.getValueAt(1, 9)); assertEquals(10, tableModel.getValueAt(9, 0)); assertEquals(3.0, tableModel.getValueAt(9, 1)); assertEquals(3.0, tableModel.getValueAt(9, 2)); assertEquals(null, tableModel.getValueAt(9, 3)); assertEquals(null, tableModel.getValueAt(9, 4)); assertEquals(15.1F, tableModel.getValueAt(9, 5)); assertEquals(0.0F, tableModel.getValueAt(9, 6)); assertEquals(0.1, tableModel.getValueAt(9, 7)); assertEquals(0, tableModel.getValueAt(9, 8)); assertEquals(0, tableModel.getValueAt(9, 9)); } @Test public void testModelWithoutCorrData() throws Exception { dataSourceConfig.dataField = null; dataSourceConfig.boxSize = 1; TransectProfileData profileData = new TransectProfileDataBuilder() .raster(band) .path(path) .boxSize(dataSourceConfig.boxSize) .build(); TableModel tableModel = new ProfileDataTableModel(band.getName(), profileData, dataSourceConfig); assertEquals(8, tableModel.getColumnCount()); assertEquals("pixel_no", tableModel.getColumnName(0)); assertEquals("pixel_x", tableModel.getColumnName(1)); assertEquals("pixel_y", tableModel.getColumnName(2)); assertEquals("latitude", tableModel.getColumnName(3)); assertEquals("longitude", tableModel.getColumnName(4)); assertEquals("b_mean", tableModel.getColumnName(5)); assertEquals("b_sigma", tableModel.getColumnName(6)); assertEquals("", tableModel.getColumnName(7)); assertEquals(10, tableModel.getRowCount()); assertEquals(1, tableModel.getValueAt(0, 0)); assertEquals(0.0, tableModel.getValueAt(0, 1)); assertEquals(0.0, tableModel.getValueAt(0, 2)); assertEquals(null, tableModel.getValueAt(0, 3)); assertEquals(null, tableModel.getValueAt(0, 4)); assertEquals(0.1F, tableModel.getValueAt(0, 5)); assertEquals(0.0F, tableModel.getValueAt(0, 6)); assertEquals(null, tableModel.getValueAt(0, 7)); assertEquals(2, tableModel.getValueAt(1, 0)); assertEquals(1.0, tableModel.getValueAt(1, 1)); assertEquals(0.0, tableModel.getValueAt(1, 2)); assertEquals(null, tableModel.getValueAt(1, 3)); assertEquals(null, tableModel.getValueAt(1, 4)); assertEquals(1.1F, tableModel.getValueAt(1, 5)); assertEquals(0.0F, tableModel.getValueAt(1, 6)); assertEquals(null, tableModel.getValueAt(1, 7)); assertEquals(10, tableModel.getValueAt(9, 0)); assertEquals(3.0, tableModel.getValueAt(9, 1)); assertEquals(3.0, tableModel.getValueAt(9, 2)); assertEquals(null, tableModel.getValueAt(9, 3)); assertEquals(null, tableModel.getValueAt(9, 4)); assertEquals(15.1F, tableModel.getValueAt(9, 5)); assertEquals(0.0F, tableModel.getValueAt(9, 6)); assertEquals(null, tableModel.getValueAt(9, 7)); } @Test public void testModelCsv() throws Exception { TransectProfileData profileData = new TransectProfileDataBuilder() .raster(band) .path(path) .boxSize(dataSourceConfig.boxSize) .build(); ProfileDataTableModel tableModel = new ProfileDataTableModel(band.getName(), profileData, dataSourceConfig); String csv = tableModel.toCsv(); assertEquals("pixel_no\tpixel_x\tpixel_y\tlatitude\tlongitude\tb_mean\tb_sigma\tdata_ref\tlat_ref\tlon_ref\n" + "1\t0.0\t0.0\t\t\t0.1\t0.0\t0.3\t0\t0\n" + "2\t1.0\t0.0\t\t\t1.1\t0.0\t\t\t\n" + "3\t2.0\t0.0\t\t\t2.1\t0.0\t\t\t\n" + "4\t3.0\t0.0\t\t\t3.1\t0.0\t0.5\t0\t0\n" + "5\t2.0\t1.0\t\t\t6.1\t0.0\t\t\t\n" + "6\t1.0\t2.0\t\t\t9.1\t0.0\t\t\t\n" + "7\t0.0\t3.0\t\t\t12.1\t0.0\t0.7\t0\t0\n" + "8\t1.0\t3.0\t\t\t13.1\t0.0\t\t\t\n" + "9\t2.0\t3.0\t\t\t14.1\t0.0\t\t\t\n" + "10\t3.0\t3.0\t\t\t15.1\t0.0\t0.1\t0\t0\n", csv); } @Test public void testModelCsvNoInBetweenPoints() throws Exception { dataSourceConfig.computeInBetweenPoints = false; TransectProfileData profileData = new TransectProfileDataBuilder() .raster(band) .path(path) .boxSize(dataSourceConfig.boxSize) .build(); ProfileDataTableModel tableModel = new ProfileDataTableModel(band.getName(), profileData, dataSourceConfig); String csv = tableModel.toCsv(); assertEquals("pixel_no\tpixel_x\tpixel_y\tlatitude\tlongitude\tb_mean\tb_sigma\tdata_ref\tlat_ref\tlon_ref\n" + "1\t0.0\t0.0\t\t\t0.1\t0.0\t0.3\t0\t0\n" + "4\t3.0\t0.0\t\t\t3.1\t0.0\t0.5\t0\t0\n" + "7\t0.0\t3.0\t\t\t12.1\t0.0\t0.7\t0\t0\n" + "10\t3.0\t3.0\t\t\t15.1\t0.0\t0.1\t0\t0\n", csv); } }
gpl-3.0
MadMarty/madsonic-server-5.0
madsonic-main/src/main/java/net/sourceforge/subsonic/filter/RESTFilter.java
3542
/* This file is part of Subsonic. Subsonic is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Subsonic is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Subsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009 (C) Sindre Mehus */ package net.sourceforge.subsonic.filter; import net.sourceforge.subsonic.Logger; import net.sourceforge.subsonic.controller.RESTController; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.util.NestedServletException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.util.NestedServletException; import net.sourceforge.subsonic.Logger; import net.sourceforge.subsonic.controller.RESTController; import static net.sourceforge.subsonic.controller.RESTController.ErrorCode.GENERIC; import static net.sourceforge.subsonic.controller.RESTController.ErrorCode.MISSING_PARAMETER; /** * Intercepts exceptions thrown by RESTController. * * Also adds the CORS response header (http://enable-cors.org) * * @author Sindre Mehus * @version $Revision: 1.1 $ $Date: 2006/03/01 16:58:08 $ */ public class RESTFilter implements Filter { private static final Logger LOG = Logger.getLogger(RESTFilter.class); public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(req, res); HttpServletResponse response = (HttpServletResponse) res; response.addHeader("Access-Control-Allow-Origin", "*"); } catch (Throwable x) { handleException(x, (HttpServletRequest) req, (HttpServletResponse) res); } } private void handleException(Throwable x, HttpServletRequest request, HttpServletResponse response) throws IOException { if (x instanceof NestedServletException && x.getCause() != null) { x = x.getCause(); } RESTController.ErrorCode code = (x instanceof ServletRequestBindingException) ? MISSING_PARAMETER : GENERIC; String msg = getErrorMessage(x); if (msg.contentEquals("EofException")) { LOG.warn("Error in REST API: broken Stream"); } else { LOG.warn("Error in REST API: " + msg, x); RESTController.error(request, response, code, msg); } } private String getErrorMessage(Throwable x) { if (x.getMessage() != null) { return x.getMessage(); } return x.getClass().getSimpleName(); } public void init(FilterConfig filterConfig) { } public void destroy() { } }
gpl-3.0
ifcharming/original2.0
tests/frontend/org/voltdb/planner/PlannerTestAideDeCamp.java
8980
/* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb.planner; import java.io.PrintStream; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import org.hsqldb_voltpatches.HSQLInterface; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.voltdb.VoltType; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.Column; import org.voltdb.catalog.Database; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; import org.voltdb.catalog.StmtParameter; import org.voltdb.compiler.DDLCompiler; import org.voltdb.compiler.DatabaseEstimates; import org.voltdb.compiler.VoltCompiler; import org.voltdb.plannodes.AbstractPlanNode; import org.voltdb.plannodes.PlanNodeList; import org.voltdb.plannodes.SchemaColumn; import org.voltdb.types.QueryType; import org.voltdb.utils.BuildDirectoryUtils; import org.voltdb.utils.Pair; /** * Some utility functions to compile SQL statements for plan generation tests. */ public class PlannerTestAideDeCamp { private final Catalog catalog; private final Procedure proc; private final HSQLInterface hsql; private final Database db; int compileCounter = 0; /** * Loads the schema at ddlurl and setups a voltcompiler / hsql instance. * @param ddlurl URL to the schema/ddl file. * @param basename Unique string, JSON plans [basename]-stmt-#_json.txt on disk * @throws Exception */ public PlannerTestAideDeCamp(URL ddlurl, String basename) throws Exception { catalog = new Catalog(); catalog.execute("add / clusters cluster"); catalog.execute("add /clusters[cluster] databases database"); db = catalog.getClusters().get("cluster").getDatabases().get("database"); proc = db.getProcedures().add(basename); String schemaPath = URLDecoder.decode(ddlurl.getPath(), "UTF-8"); VoltCompiler compiler = new VoltCompiler(); hsql = HSQLInterface.loadHsqldb(); //hsql.runDDLFile(schemaPath); DDLCompiler ddl_compiler = new DDLCompiler(compiler, hsql); ddl_compiler.loadSchema(schemaPath); ddl_compiler.compileToCatalog(catalog, db); } /** * Cleans up HSQL. Mandatory - call this when done! */ public void tearDown() { hsql.close(); } public Catalog getCatalog() { return catalog; } public List<AbstractPlanNode> compile(String sql, int paramCount) { return compile(sql, paramCount, false); } public List<AbstractPlanNode> compile(String sql, int paramCount, boolean singlePartition) { return compile(sql, paramCount, singlePartition, null); } /** * Compile a statement and return the final plan graph. * @param sql * @param paramCount */ public List<AbstractPlanNode> compile(String sql, int paramCount, boolean singlePartition, String joinOrder) { Statement catalogStmt = proc.getStatements().add("stmt-" + String.valueOf(compileCounter++)); catalogStmt.setSqltext(sql); catalogStmt.setSinglepartition(singlePartition); catalogStmt.setBatched(false); catalogStmt.setParamnum(paramCount); // determine the type of the query QueryType qtype = QueryType.SELECT; catalogStmt.setReadonly(true); if (sql.toLowerCase().startsWith("insert")) { qtype = QueryType.INSERT; catalogStmt.setReadonly(false); } if (sql.toLowerCase().startsWith("update")) { qtype = QueryType.UPDATE; catalogStmt.setReadonly(false); } if (sql.toLowerCase().startsWith("delete")) { qtype = QueryType.DELETE; catalogStmt.setReadonly(false); } catalogStmt.setQuerytype(qtype.getValue()); // name will look like "basename-stmt-#" String name = catalogStmt.getParent().getTypeName() + "-" + catalogStmt.getTypeName(); DatabaseEstimates estimates = new DatabaseEstimates(); TrivialCostModel costModel = new TrivialCostModel(); QueryPlanner planner = new QueryPlanner(catalog.getClusters().get("cluster"), db, hsql, estimates, true, false); CompiledPlan plan = null; plan = planner.compilePlan(costModel, catalogStmt.getSqltext(), joinOrder, catalogStmt.getTypeName(), catalogStmt.getParent().getTypeName(), catalogStmt.getSinglepartition(), null); if (plan == null) { String msg = "planner.compilePlan returned null plan"; String plannerMsg = planner.getErrorMessage(); if (plannerMsg != null) { msg += " with error: \"" + plannerMsg + "\""; } throw new NullPointerException(msg); } // Input Parameters // We will need to update the system catalogs with this new information // If this is an adhoc query then there won't be any parameters for (ParameterInfo param : plan.parameters) { StmtParameter catalogParam = catalogStmt.getParameters().add(String.valueOf(param.index)); catalogParam.setJavatype(param.type.getValue()); catalogParam.setIndex(param.index); } // Output Columns int index = 0; for (SchemaColumn col : plan.columns.getColumns()) { Column catColumn = catalogStmt.getOutput_columns().add(String.valueOf(index)); catColumn.setNullable(false); catColumn.setIndex(index); catColumn.setName(col.getColumnName()); catColumn.setType(col.getType().getValue()); catColumn.setSize(col.getSize()); index++; } List<PlanNodeList> nodeLists = new ArrayList<PlanNodeList>(); for (CompiledPlan.Fragment fragment : plan.fragments) { PlanNodeList nodeList = new PlanNodeList(fragment.planGraph); nodeLists.add(nodeList); } //Store the list of parameters types and indexes in the plan node list. List<Pair<Integer, VoltType>> parameters = nodeLists.get(0).getParameters(); for (ParameterInfo param : plan.parameters) { Pair<Integer, VoltType> parameter = new Pair<Integer, VoltType>(param.index, param.type); parameters.add(parameter); } // Now update our catalog information // HACK: We're using the node_tree's hashCode() as it's name. It would be really // nice if the Catalog code give us an guid without needing a name first... String json = null; try { JSONObject jobj = new JSONObject(nodeLists.get(0).toJSONString()); json = jobj.toString(4); } catch (JSONException e2) { // TODO Auto-generated catch block e2.printStackTrace(); System.exit(-1); } // // We then stick a serialized version of PlanNodeTree into a PlanFragment // try { PrintStream plansJSONOut = BuildDirectoryUtils.getDebugOutputPrintStream( "statement-plans", name + "_json.txt"); plansJSONOut.print(json); plansJSONOut.close(); PrintStream plansDOTOut = BuildDirectoryUtils.getDebugOutputPrintStream( "statement-plans", name + ".dot"); plansDOTOut.print(nodeLists.get(0).toDOTString("name")); plansDOTOut.close(); } catch (Exception e) { e.printStackTrace(); } List<AbstractPlanNode> plannodes = new ArrayList<AbstractPlanNode>(); for (PlanNodeList nodeList : nodeLists) { plannodes.add(nodeList.getRootPlanNode()); } return plannodes; } }
gpl-3.0
timgrube/GTNA
src/gtna/transformation/sampling/walkercontroller/UniformSamplingWalkerController.java
2793
/* =========================================================== * GTNA : Graph-Theoretic Network Analyzer * =========================================================== * * (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt) * and Contributors * * Project Info: http://www.p2p.tu-darmstadt.de/research/gtna/ * * GTNA is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GTNA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * --------------------------------------- * UniformSamplingWalkerController.java * --------------------------------------- * (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt) * and Contributors * * Original Author: Tim; * Contributors: -; * * Changes since 2011-05-17 * --------------------------------------- * */ package gtna.transformation.sampling.walkercontroller; import gtna.graph.Node; import gtna.transformation.sampling.AWalker; import gtna.transformation.sampling.AWalkerController; import gtna.transformation.sampling.CandidateFilter; import java.util.Collection; /** * @author Tim * */ public class UniformSamplingWalkerController extends AWalkerController { CandidateFilter cf; Collection<AWalker> walkers; /** * @param key * @param value * @param w * @param cf */ public UniformSamplingWalkerController(Collection<AWalker> w, CandidateFilter cf) { super(w.size() + "x_" + w.toArray(new AWalker[0])[0].getValue(), w, cf); if (w.size() != 1) { throw new IllegalArgumentException( "This Walker Controller is defined for single dimensional usage only."); } this.walkers = w; this.cf = cf; } /* * (non-Javadoc) * * @see * gtna.transformation.sampling.AWalkerController#initialize(gtna.graph. * Graph, gtna.graph.Node[]) */ @Override public void initialize(Node[] startNodes) { AWalker[] wa = walkers.toArray(new AWalker[0]); for (int i = 0; i < walkers.size(); i++) { // if #walkers > #startNodes assign startnodes with wraparound int snid = i % startNodes.length; wa[i].setStartNode(startNodes[snid]); } } /* * (non-Javadoc) * * @see gtna.transformation.sampling.AWalkerController#getActiveWalkers() */ @Override protected Collection<AWalker> getActiveWalkers() { return walkers; } }
gpl-3.0
R41G4/ERP-Constructora
ERPMuestra/src/java/com/model/ValeDevolucion.java
2427
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.model; import java.util.HashSet; import java.util.Set; /** * * @author Mickey */ public class ValeDevolucion { private Integer idValeDevolucion; private ValeConsumo valeConsumo; private String fechaElaboracion; private Integer noValeConsumo; private Integer noValeDevolucion; private Set insumoValeDevolucions = new HashSet(0); public ValeDevolucion() { } public Integer getIdValeDevolucion() { return idValeDevolucion; } /** * @param idValeDevolucion the idValeDevolucion to set */ public void setIdValeDevolucion(Integer idValeDevolucion) { this.idValeDevolucion = idValeDevolucion; } /** * @return the valeConsumo */ public ValeConsumo getValeConsumo() { return valeConsumo; } /** * @param valeConsumo the valeConsumo to set */ public void setValeConsumo(ValeConsumo valeConsumo) { this.valeConsumo = valeConsumo; } /** * @return the fechaElaboracion */ public String getFechaElaboracion() { return fechaElaboracion; } /** * @param fechaElaboracion the fechaElaboracion to set */ public void setFechaElaboracion(String fechaElaboracion) { this.fechaElaboracion = fechaElaboracion; } /** * @return the noValeConsumo */ public Integer getNoValeConsumo() { return noValeConsumo; } /** * @param noValeConsumo the noValeConsumo to set */ public void setNoValeConsumo(Integer noValeConsumo) { this.noValeConsumo = noValeConsumo; } /** * @return the noValeDevolucion */ public Integer getNoValeDevolucion() { return noValeDevolucion; } /** * @param noValeDevolucion the noValeDevolucion to set */ public void setNoValeDevolucion(Integer noValeDevolucion) { this.noValeDevolucion = noValeDevolucion; } /** * @return the insumoValeDevolucions */ public Set getInsumoValeDevolucions() { return insumoValeDevolucions; } /** * @param insumoValeDevolucions the insumoValeDevolucions to set */ public void setInsumoValeDevolucions(Set insumoValeDevolucions) { this.insumoValeDevolucions = insumoValeDevolucions; } }
gpl-3.0
jeberst/MobiSimBase
Common/src/edu/sharif/ce/dml/common/parameters/logic/primitives/StringParameter.java
2662
/* * Copyright (c) 2005-2008 by Masoud Moshref Javadi <moshref@ce.sharif.edu>, http://ce.sharif.edu/~moshref * The license.txt file describes the conditions under which this software may be distributed. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package edu.sharif.ce.dml.common.parameters.logic.primitives; import edu.sharif.ce.dml.common.parameters.data.GeneralDataParameter; import edu.sharif.ce.dml.common.parameters.data.StringDataParameter; import edu.sharif.ce.dml.common.parameters.logic.Parameter; import edu.sharif.ce.dml.common.parameters.logic.exception.InvalidParameterInputException; import edu.sharif.ce.dml.common.parameters.ui.NewUIParameter; import edu.sharif.ce.dml.common.parameters.ui.primitives.StringUIParameter; /** * Created by IntelliJ IDEA. * User: Masoud * Date: Nov 11, 2007 * Time: 5:45:32 PM<br> * string parameter.<br/> * Assumes input dataparameters structure as:<br/> * <ul><li>{@link edu.sharif.ce.dml.common.parameters.data.StringDataParameter}</il></ul> */ public class StringParameter extends Parameter { private String value; public StringParameter(String name, String value) { super(name); this.value = value; } public String getValue() { return value; } public void setValue(Object v) throws InvalidParameterInputException { value = (String) v; } public void setInitData(GeneralDataParameter dataParameter) throws InvalidParameterInputException { super.setInitData(dataParameter); value = ((StringDataParameter) dataParameter).getValue(); } public void updateUIParameter(NewUIParameter uiParameter) throws InvalidParameterInputException { ((StringUIParameter) uiParameter).setValue(getValue()); } public NewUIParameter getUIParameter(boolean showInternalParameterables) { return new StringUIParameter(getName(), value); } public void setUIParameterValue(NewUIParameter uiParameter) throws InvalidParameterInputException { setValue(uiParameter.toString()); } }
gpl-3.0
YcheLanguageStudio/JavaRelatedStudy
SoftwareAnalysis/Assignments/Assign2Subject/src/test/java/janala/ThreeSumCloseTestCase6.java
631
package janala; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by cheyulin on 11/29/16. */ public class ThreeSumCloseTestCase6 { private static util.IntArrayUtil jarUtil = new util.IntArrayUtil(); private static tests.homework.IntArrayUtil srcUtil = new tests.homework.IntArrayUtil(); @Test public void testThreeSumClose() throws Exception { int[] arr0 = {-1, 0, 0, 0, 0}; int[] arr1 = {-1, 0, 0, 0, 0}; int targetVal = -2147483647; assertEquals(jarUtil.threeSumClosest(arr0, targetVal), srcUtil.threeSumClosest(arr1, targetVal)); } }
gpl-3.0
yoann-dufresne/Smiles2Monomers
src/algorithms/isomorphism/indepth/ImpossibleToReplace.java
125
package algorithms.isomorphism.indepth; @SuppressWarnings("serial") public class ImpossibleToReplace extends Exception { }
agpl-3.0
mbenguig/scheduling
scheduler/scheduler-server/src/test/java/functionaltests/runasme/TestRunAsMeLinuxPwd.java
5918
/* * ProActive Parallel Suite(TM): * The Open Source library for parallel and distributed * Workflows & Scheduling, Orchestration, Cloud Automation * and Big Data Analysis on Enterprise Grids & Clouds. * * Copyright (c) 2007 - 2017 ActiveEon * Contact: contact@activeeon.com * * This library is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation: version 3 of * the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. */ package functionaltests.runasme; import static org.junit.Assume.assumeTrue; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.proactive.utils.OperatingSystem; import org.ow2.proactive.resourcemanager.RMFactory; import org.ow2.proactive.scheduler.common.Scheduler; import org.ow2.proactive.scheduler.common.job.Job; import org.ow2.proactive.scheduler.common.job.JobId; import org.ow2.proactive.scheduler.common.job.factories.JobFactory; import org.ow2.proactive.scheduler.common.task.TaskResult; import org.ow2.proactive.scheduler.task.utils.ForkerUtils; import functionaltests.dataspaces.TestCacheSpaceCleaning; import functionaltests.utils.RMTHelper; import functionaltests.utils.SchedulerTHelper; /** * Tests RunAsMe feature on linux configured with su impersonation * * @author ActiveEon Team * @since 05/01/2017 */ public class TestRunAsMeLinuxPwd extends TestRunAsMe { static URL jobDescriptor = TestCacheSpaceCleaning.class.getResource("/functionaltests/descriptors/Job_RunAsMe_Linux.xml"); @BeforeClass public static void startDedicatedScheduler() throws Exception { assumeTrue(OperatingSystem.getOperatingSystem() == OperatingSystem.unix); setupUser(); RMFactory.setOsJavaProperty(); // start an empty scheduler and add a node source with modified properties schedulerHelper = new SchedulerTHelper(true, true); List<String> arguments = new ArrayList<>(); arguments.addAll(RMTHelper.setup.getJvmParametersAsList()); arguments.add("-D" + ForkerUtils.FORK_METHOD_KEY + "=" + ForkerUtils.ForkMethod.PWD.toString()); schedulerHelper.createNodeSource("RunAsMeNSPwd", 5, arguments); } @Test public void testRunAsMe() throws Exception { // connect to the scheduler using the runasme account Scheduler scheduler = schedulerHelper.getSchedulerInterface(username, password, null); JobId jobid = schedulerHelper.testJobSubmission(scheduler, JobFactory.getFactory() .createJob(new File(jobDescriptor.toURI()).getAbsolutePath()), false, true); for (Map.Entry<String, TaskResult> entry : scheduler.getJobResult(jobid).getAllResults().entrySet()) { if (entry.getKey().contains("RunAsMeTask")) { Assert.assertTrue("RunAsMe task should display in the logs the correct system user", entry.getValue().getOutput().getStdoutLogs().contains(username)); } } } @Test public void testRunAsUser() throws Exception { // connect to the scheduler using the runasme account Scheduler scheduler = schedulerHelper.getSchedulerInterface(username, password, null); Job job = JobFactory.getFactory().createJob(new File(jobDescriptor.toURI()).getAbsolutePath()); job.addGenericInformation(ForkerUtils.RUNAS_USER_GENERIC_INFO, username); job.addGenericInformation(ForkerUtils.RUNAS_PWD_GENERIC_INFO, password); JobId jobid = schedulerHelper.testJobSubmission(scheduler, job, false, true); for (Map.Entry<String, TaskResult> entry : scheduler.getJobResult(jobid).getAllResults().entrySet()) { if (entry.getKey().contains("RunAsMeTask")) { Assert.assertTrue("RunAsMe task should display in the logs the correct system user", entry.getValue().getOutput().getStdoutLogs().contains(username)); } } } @Test public void testRunAsUserCreds() throws Exception { // connect to the scheduler using the runasme account Scheduler scheduler = schedulerHelper.getSchedulerInterface(username, password, null); Job job = JobFactory.getFactory().createJob(new File(jobDescriptor.toURI()).getAbsolutePath()); job.addGenericInformation(ForkerUtils.RUNAS_USER_GENERIC_INFO, username); job.addGenericInformation(ForkerUtils.RUNAS_PWD_CRED_GENERIC_INFO, username); scheduler.putThirdPartyCredential(username, password); JobId jobid = schedulerHelper.testJobSubmission(scheduler, job, false, true); for (Map.Entry<String, TaskResult> entry : scheduler.getJobResult(jobid).getAllResults().entrySet()) { if (entry.getKey().contains("RunAsMeTask")) { Assert.assertTrue("RunAsMe task should display in the logs the correct system user", entry.getValue().getOutput().getStdoutLogs().contains(username)); } } } }
agpl-3.0
klebergraciasoares/ireport-fork
ireport-designer/src/com/jaspersoft/ireport/designer/welcome/RecentReportsPanel.java
7258
/* * iReport - Visual Designer for JasperReports. * Copyright (C) 2002 - 2009 Jaspersoft Corporation. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of iReport. * * iReport is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * iReport is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with iReport. If not, see <http://www.gnu.org/licenses/>. */ package com.jaspersoft.ireport.designer.welcome; import com.jaspersoft.ireport.designer.IReportManager; import com.jaspersoft.ireport.locale.I18n; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.beans.BeanInfo; import java.net.MalformedURLException; import java.net.URL; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import org.openide.cookies.OpenCookie; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileStateInvalidException; import org.openide.filesystems.URLMapper; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.util.Exceptions; /** * * @author gtoffoli */ public class RecentReportsPanel extends javax.swing.JPanel { /** Creates new form RecentReportsPanel */ public RecentReportsPanel() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { setOpaque(false); setLayout(new java.awt.BorderLayout()); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables private static final int MAX_REPORTS = 10; private PreferenceChangeListener changeListener; @Override public void addNotify() { super.addNotify(); removeAll(); add( rebuildContent(), BorderLayout.CENTER ); IReportManager.getPreferences().addPreferenceChangeListener( getPreferenceChangeListener() ); } @Override public void removeNotify() { super.removeNotify(); IReportManager.getPreferences().removePreferenceChangeListener( getPreferenceChangeListener() ); } private PreferenceChangeListener getPreferenceChangeListener() { if( null == changeListener ) { changeListener = new PreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent evt) { removeAll(); add( rebuildContent(), BorderLayout.CENTER ); invalidate(); revalidate(); repaint(); } }; } return changeListener; } private JPanel rebuildContent() { JPanel panel = new JPanel( new GridBagLayout() ); panel.setOpaque( false ); int row = 0; String s = IReportManager.getPreferences().get("RecentFiles",null); // NOI18N if (s != null) { String[] files = s.split("\n"); for (int i=0; i<files.length; ++i) { if (files[i].trim().length() == 0) continue; if (row > MAX_REPORTS) break; String item = files[i]; FileObject fo = null; try { fo = convertURL2File(new URL(item)); } catch (MalformedURLException ex) { Exceptions.printStackTrace(ex); } if (fo == null || !fo.isValid()) continue; addProject( panel, row, fo ); row++; } } if( 0 == row ) { panel.add( new JLabel(I18n.getString( "RecentReportsPanel.noRecentFiles" )), //NOI18N new GridBagConstraints( 0,row,1,1,1.0,1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(10,10,10,10), 0, 0 ) ); } else { panel.add( new JLabel(), new GridBagConstraints( 0,row,1,1,0.0,1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0 ) ); } return panel; } private void addProject( JPanel panel, int row, final FileObject fileObject ) { try { OpenFileObjectAction action = new OpenFileObjectAction(fileObject); ActionButton b = new ActionButton(action, true, fileObject.getURL().toString()); b.setFont(LinkButton.BUTTON_FONT); panel.add(b, new GridBagConstraints(0, row, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); } catch (FileStateInvalidException ex) { //Exceptions.printStackTrace(ex); } } private static class OpenFileObjectAction extends AbstractAction { private FileObject fileObject; public OpenFileObjectAction( FileObject fileObject ) { super(); this.fileObject = fileObject; Image icon = null; try { DataObject dObj = DataObject.find(fileObject); icon = dObj.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16); this.putValue(AbstractAction.SMALL_ICON,new ImageIcon(icon)); } catch (DataObjectNotFoundException ex) { ex.printStackTrace(); } this.putValue(AbstractAction.NAME, fileObject.getName()); } public void actionPerformed(ActionEvent e) { if (fileObject != null) { try { DataObject.find(fileObject).getCookie(OpenCookie.class).open(); } catch (Exception ex) { // do nothing... } } } } static URL convertFile2URL (FileObject fo) { URL url = URLMapper.findURL(fo, URLMapper.EXTERNAL); return url; } static FileObject convertURL2File (URL url) { FileObject fo = URLMapper.findFileObject(url); return fo; } }
agpl-3.0
maduhu/jBilling
src/java/com/sapienter/jbilling/server/pluggableTask/TaskException.java
1307
/* jBilling - The Enterprise Open Source Billing System Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde This file is part of jbilling. jbilling is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jbilling is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with jbilling. If not, see <http://www.gnu.org/licenses/>. */ package com.sapienter.jbilling.server.pluggableTask; /** * @author emilc * */ public class TaskException extends Exception { /** * Constructor for TaskException. */ public TaskException() { super(); } public TaskException(Exception e) { super(e); } /** * Constructor for TaskException. * @param message */ public TaskException(String message) { super(message); } }
agpl-3.0
Chris--A/Arduino
arduino-core/src/cc/arduino/contributions/libraries/ContributedLibrary.java
5136
/* * This file is part of Arduino. * * Copyright 2014 Arduino LLC (http://www.arduino.cc/) * * Arduino is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. */ package cc.arduino.contributions.libraries; import cc.arduino.contributions.DownloadableContribution; import processing.app.I18n; import java.util.Comparator; import java.util.List; import static processing.app.I18n.tr; public abstract class ContributedLibrary extends DownloadableContribution { public abstract String getName(); public abstract String getMaintainer(); public abstract String getAuthor(); public abstract String getWebsite(); public abstract String getCategory(); public abstract void setCategory(String category); public abstract String getLicense(); public abstract String getParagraph(); public abstract String getSentence(); public abstract List<String> getArchitectures(); public abstract List<String> getTypes(); public abstract List<ContributedLibraryReference> getRequires(); public static final Comparator<ContributedLibrary> CASE_INSENSITIVE_ORDER = (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()); /** * Returns <b>true</b> if the library declares to support the specified * architecture (through the "architectures" property field). * * @param reqArch * @return */ public boolean supportsArchitecture(String reqArch) { return getArchitectures().contains(reqArch) || getArchitectures().contains("*"); } /** * Returns <b>true</b> if the library declares to support at least one of the * specified architectures. * * @param reqArchs A List of architectures to check * @return */ public boolean supportsArchitecture(List<String> reqArchs) { if (reqArchs.contains("*")) return true; for (String reqArch : reqArchs) if (supportsArchitecture(reqArch)) return true; return false; } @Override public String toString() { return I18n.format(tr("Version {0}"), getParsedVersion()); } public String info() { String res = ""; res += " ContributedLibrary : " + getName() + "\n"; res += " author : " + getAuthor() + "\n"; res += " maintainer : " + getMaintainer() + "\n"; res += " version : " + getParsedVersion() + "\n"; res += " website : " + getUrl() + "\n"; res += " category : " + getCategory() + "\n"; res += " license : " + getLicense() + "\n"; res += " descrip : " + getSentence() + "\n"; if (getParagraph() != null && !getParagraph().isEmpty()) res += " " + getParagraph() + "\n"; res += " architectures : "; if (getArchitectures() != null) for (String a : getArchitectures()) { res += a + ","; } res += "\n"; res += " requires :\n"; if (getRequires() != null) for (ContributedLibraryReference r : getRequires()) { res += " " + r; } res += "\n"; // DownloadableContribution res += super.toString(); return res; } @Override public boolean equals(Object obj) { if (!(obj instanceof ContributedLibrary)) { return false; } String thisVersion = getParsedVersion(); String otherVersion = ((ContributedLibrary) obj).getParsedVersion(); boolean versionEquals = (thisVersion != null && otherVersion != null && thisVersion.equals(otherVersion)); // Important: for legacy libs, versions are null. Two legacy libs must // always pass this test. if (thisVersion == null && otherVersion == null) versionEquals = true; String thisName = getName(); String otherName = ((ContributedLibrary) obj).getName(); boolean nameEquals = thisName == null || otherName == null || thisName.equals(otherName); return versionEquals && nameEquals; } }
lgpl-2.1
deadcyclo/nuxeo-features
nuxeo-automation/nuxeo-automation-core/src/main/java/org/nuxeo/ecm/automation/core/impl/adapters/StringToList.java
1057
/* * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) 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: * bstefanescu */ package org.nuxeo.ecm.automation.core.impl.adapters; import org.nuxeo.common.utils.StringUtils; import org.nuxeo.ecm.automation.OperationContext; import org.nuxeo.ecm.automation.TypeAdaptException; import org.nuxeo.ecm.automation.TypeAdapter; import org.nuxeo.ecm.automation.core.util.StringList; /** * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> */ public class StringToList implements TypeAdapter { public Object getAdaptedValue(OperationContext ctx, Object objectToAdapt) throws TypeAdaptException { String content = (String) objectToAdapt; String[] ar = StringUtils.split(content, ',', true); return new StringList(ar); } }
lgpl-2.1
ggiudetti/opencms-core
src/org/opencms/importexport/CmsImportParameters.java
4132
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * 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 * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH & Co. KG, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.importexport; /** * Import parameters.<p> * * @since 7.0.4 */ public class CmsImportParameters { /** The path in the OpenCms VFS to import into.*/ private String m_destinationPath; /** If set, the permissions set on existing resources will not be modified.*/ private boolean m_keepPermissions; /** The file path, could be a folder or a zip file. */ private String m_path; /** If set, the manifest.xml file will be validated during the import. */ private boolean m_xmlValidation; /** * Constructor.<p> * * @param path the file path, could be a folder or a zip file * @param destination path in the OpenCms VFS to import into * @param keepPermissions if set, the permissions set on existing resources will not be modified */ public CmsImportParameters(String path, String destination, boolean keepPermissions) { setPath(path); setDestinationPath(destination); setKeepPermissions(keepPermissions); } /** * Returns the path in the OpenCms VFS to import into.<p> * * @return the path in the OpenCms VFS to import into */ public String getDestinationPath() { return m_destinationPath; } /** * Returns the file path, could be a folder or a zip file.<p> * * @return the file path */ public String getPath() { return m_path; } /** * Returns the keep permissions flags. * if set, the permissions set on existing resources will not be modified.<p> * * @return the keep permissions flag */ public boolean isKeepPermissions() { return m_keepPermissions; } /** * Checks if the manifest.xml file will be validated during the import.<p> * * @return the xml validation flag */ public boolean isXmlValidation() { return m_xmlValidation; } /** * Sets the path in the OpenCms VFS to import into.<p> * * @param importPath the import path to set */ public void setDestinationPath(String importPath) { m_destinationPath = importPath; } /** * Sets the keep permissions flag. * If set, the permissions set on existing resources will not be modified.<p> * * @param keepPermissions the keep permissions flag to set */ public void setKeepPermissions(boolean keepPermissions) { m_keepPermissions = keepPermissions; } /** * Sets the file path, could be a folder or a zip file.<p> * * @param path the file path, could be a folder or a zip file */ public void setPath(String path) { m_path = path; } /** * Sets the xml validation flag. If set, the manifest.xml file will be validated during the import.<p> * * @param xmlValidation the xml validation flag to set */ public void setXmlValidation(boolean xmlValidation) { m_xmlValidation = xmlValidation; } }
lgpl-2.1
marc4j/marc4j
test/src/org/marc4j/test/MarcStreamReaderTest.java
2311
package org.marc4j.test; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Test; import org.marc4j.MarcException; import org.marc4j.MarcStreamReader; /** * Tests of {@link MarcStreamReader}. * * @author <a href="mailto:ksclarke@gmail.com">Kevin S. Clarke</a> */ public class MarcStreamReaderTest { /** * Tests private {@link MarcStreamReader#getDataAsString()} when an explicit non-(UTF-8, Ansel, or ISO-8859-1) * character set is used. */ @Test public void testGetDataAsStringWithExplicitCharset() { final InputStream input = getClass().getResourceAsStream("/cyrillic_capital_e.mrc"); final MarcStreamReader reader = new MarcStreamReader(input, "iso-8859-5"); if (reader.hasNext()) { final String ctrlField = reader.next().getControlNumberField().getData(); if (!ctrlField.equals("u6015439")) { fail("Failed to get control number field data with explicit character set requested [Found: " + ctrlField + "]"); } } } @Test public void testParseRecordOnUnorderDirectoryEntries() { final InputStream input = getClass().getResourceAsStream("/unordered-directory-entries.mrc"); try { final MarcStreamReader reader = new MarcStreamReader(input); while (reader.hasNext()) { reader.next(); } } catch (final MarcException e) { fail("Failed to parse record having unordered directory entries"); } } @Test public void testByteStreamRead() throws IOException { final Path path = Paths.get("test/resources/chabon.mrc"); final byte[] data = Files.readAllBytes(path); final ByteArrayInputStream byteStream = new ByteArrayInputStream(data); try { final MarcStreamReader reader = new MarcStreamReader(byteStream); while (reader.hasNext()) { reader.next(); } } catch (final MarcException details) { fail("Failed to parse record read from byte stream"); } } }
lgpl-2.1
fionakim/biojava
biojava-ontology/src/main/java/org/biojava/nbio/ontology/AlreadyExistsException.java
1056
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.nbio.ontology; /** * Thrown to indicate that a term or triple can't be added to an ontology * because it is already present. * * @author Thomas Down */ public class AlreadyExistsException extends OntologyException { private static final long serialVersionUID = 1L; public AlreadyExistsException() { super(); } public AlreadyExistsException(String description) { super(description); } }
lgpl-2.1
roidelapluie/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/common/packet/ResultPacketFactory.java
3496
/* MariaDB Client for Java Copyright (c) 2012 Monty Program Ab. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to Monty Program Ab info@montyprogram.com. This particular MariaDB Client for Java file is work derived from a Drizzle-JDBC. Drizzle-JDBC file which is covered by subject to the following copyright and notice provisions: Copyright (c) 2009-2011, Marcus Eriksson Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the driver nor the names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.mariadb.jdbc.internal.common.packet; import java.io.IOException; /** * Creates result packets only handles error, ok, eof and result set packets since field and row packets require a * previous result set packet */ public class ResultPacketFactory { private final static byte ERROR = (byte) 0xff; private final static byte OK = (byte) 0x00; private final static byte EOF = (byte) 0xfe; private final static byte LOCALINFILE = (byte) 0xfb; private ResultPacketFactory() { } // private static EOFPacket eof = new EOFPacket(); public static ResultPacket createResultPacket(final RawPacket rawPacket) throws IOException { byte b = rawPacket.getByteBuffer().get(0); switch (b) { case ERROR: return new ErrorPacket(rawPacket); case OK: return new OKPacket(rawPacket); case EOF: return new EOFPacket(rawPacket); case LOCALINFILE: return new LocalInfilePacket(rawPacket); default: return new ResultSetPacket(rawPacket); } } }
lgpl-2.1
nuxeo-archives/nuxeo-features
nuxeo-automation/nuxeo-automation-server/src/main/java/org/nuxeo/ecm/automation/server/MarshallerDescriptor.java
1516
/* * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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 * Lesser General Public License for more details. * * Contributors: * dmetzler */ package org.nuxeo.ecm.automation.server; import java.util.ArrayList; import java.util.List; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import org.nuxeo.common.xmap.annotation.XNodeList; import org.nuxeo.common.xmap.annotation.XObject; /** * * * @since 5.8 */ @XObject("marshaller") public class MarshallerDescriptor { @XNodeList(value = "writer", componentType = Class.class, type = ArrayList.class) private List<Class<? extends MessageBodyWriter<?>>> writers; @XNodeList(value = "reader", componentType = Class.class, type = ArrayList.class) private List<Class<? extends MessageBodyReader<?>>> readers; public List<Class<? extends MessageBodyWriter<?>>> getWriters() { return writers; } public List<Class<? extends MessageBodyReader<?>>> getReaders() { return readers; } }
lgpl-2.1
DionKoolhaas/molgenis
molgenis-data-import/src/main/java/org/molgenis/data/importer/ImporterConfiguration.java
1328
package org.molgenis.data.importer; import org.molgenis.data.DataService; import org.molgenis.data.mysql.EmxImportServiceRegistrator; import org.molgenis.data.semantic.LabeledResource; import org.molgenis.data.semanticsearch.service.TagService; import org.molgenis.security.permission.PermissionSystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ImporterConfiguration { @Autowired private DataService dataService; @Autowired private PermissionSystemService permissionSystemService; @Autowired private TagService<LabeledResource, LabeledResource> tagService; @Autowired private ImportServiceFactory importServiceFactory; @Bean public ImportService emxImportService() { return new EmxImportService(emxMetaDataParser(), importWriter(), dataService); } @Bean public ImportWriter importWriter() { return new ImportWriter(dataService, permissionSystemService, tagService); } @Bean public MetaDataParser emxMetaDataParser() { return new EmxMetaDataParser(dataService); } @Bean public EmxImportServiceRegistrator mysqlRepositoryRegistrator() { return new EmxImportServiceRegistrator(importServiceFactory, emxImportService()); } }
lgpl-3.0
johnpfield/apache-fortress-demo
src/main/java/com/mycompany/LoginPage.java
622
/* * This is free and unencumbered software released into the public domain. */ package com.mycompany; /** * Since the Java EE container performs authentication, this wicket page simply sets the response page to wicket * application home page. If Java EE security session has timed out, the container will direct request to its configured login form: /login/login.html. * See web.xml for container security configuration settings. * * @author Shawn McKinney * @version $Rev$ */ public final class LoginPage extends MyBasePage { public LoginPage() { setResponsePage( LaunchPage.class ); } }
unlicense
chrisdennis/terracotta-platform
dynamic-config/api/src/main/java/org/terracotta/dynamic_config/api/model/nomad/NodeAdditionNomadChange.java
2916
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.dynamic_config.api.model.nomad; import org.terracotta.dynamic_config.api.model.Cluster; import org.terracotta.dynamic_config.api.model.Node; import org.terracotta.dynamic_config.api.model.NodeContext; import org.terracotta.dynamic_config.api.model.Stripe; import org.terracotta.dynamic_config.api.model.UID; import static java.util.Objects.requireNonNull; /** * @author Mathieu Carbou */ public class NodeAdditionNomadChange extends NodeNomadChange { public NodeAdditionNomadChange(Cluster cluster, UID stripeUID, Node node) { super(cluster, stripeUID, node); Stripe stripe = cluster.getStripe(stripeUID) .orElseThrow(() -> new IllegalArgumentException("Invalid stripe UID: " + stripeUID + " in cluster " + cluster.toShapeString())); if (stripe.getNodes().stream().noneMatch(node::equals)) { throw new IllegalArgumentException("Node " + node.getName() + " is not part of stripe: " + stripe.getName() + " in cluster " + cluster.toShapeString()); } } @Override public Cluster apply(Cluster original) { requireNonNull(original); original.getStripe(getStripeUID()) .orElseThrow(() -> new IllegalArgumentException("Stripe UID: " + getStripeUID() + " does not exist in cluster: " + original.toShapeString())); if (original.containsNode(getNode().getName())) { throw new IllegalArgumentException("Node name: " + getNode().getName() + " already exists in cluster: " + original.toShapeString()); } if (original.containsNode(getNode().getUID())) { throw new IllegalArgumentException("Node: " + getNode().getUID() + " already exists in cluster: " + original); } Cluster updated = original.clone(); updated.getStripe(getStripeUID()).get().addNode(getNode().clone()); return updated; } @Override public boolean canUpdateRuntimeTopology(NodeContext currentNode) { return true; } @Override public String getSummary() { return "Attaching node: " + getNode().toShapeString() + " to stripe: " + getCluster().getStripe(getStripeUID()).get().getName(); } @Override public String toString() { return "NodeAdditionNomadChange{" + "stripeUID=" + getStripeUID() + ", node=" + getNode().getName() + ", cluster=" + getCluster().toShapeString() + '}'; } }
apache-2.0
karolaug/log4j-extras
src/main/java/org/apache/log4j/receivers/db/JNDIConnectionSource.java
4905
/* * 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.log4j.receivers.db; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; // PortableRemoteObject was introduced in JDK 1.3. We won't use it. // import javax.rmi.PortableRemoteObject; /** * The <id>JNDIConnectionSource</id> is an implementation of * {@link ConnectionSource} that obtains a {@link javax.sql.DataSource} from a * JNDI provider and uses it to obtain a {@link java.sql.Connection}. It is * primarily designed to be used inside of J2EE application servers or * application server clients, assuming the application server supports remote * access of {@link javax.sql.DataSource}s. In this way one can take * advantage of connection pooling and whatever other goodies the application * server provides. * <p> * Sample configuration:<br> * <pre> * &lt;connectionSource class="org.apache.log4j.jdbc.JNDIConnectionSource"&gt; * &lt;param name="jndiLocation" value="jdbc/MySQLDS" /&gt; * &lt;/connectionSource&gt; * </pre> * <p> * Sample configuration (with username and password):<br> * <pre> * &lt;connectionSource class="org.apache.log4j.jdbc.JNDIConnectionSource"&gt; * &lt;param name="jndiLocation" value="jdbc/MySQLDS" /&gt; * &lt;param name="username" value="myUser" /&gt; * &lt;param name="password" value="myPassword" /&gt; * &lt;/connectionSource&gt; * </pre> * <p> * Note that this class will obtain an {@link javax.naming.InitialContext} * using the no-argument constructor. This will usually work when executing * within a J2EE environment. When outside the J2EE environment, make sure * that you provide a jndi.properties file as described by your JNDI * provider's documentation. * * @author <a href="mailto:rdecampo@twcny.rr.com">Ray DeCampo</a> */ public class JNDIConnectionSource extends ConnectionSourceSkeleton { private String jndiLocation = null; private DataSource dataSource = null; /** * @see org.apache.log4j.spi.OptionHandler#activateOptions() */ public void activateOptions() { if (jndiLocation == null) { getLogger().error("No JNDI location specified for JNDIConnectionSource."); } discoverConnnectionProperties(); } /** * @see org.apache.log4j.receivers.db.ConnectionSource#getConnection() */ public Connection getConnection() throws SQLException { Connection conn = null; try { if(dataSource == null) { dataSource = lookupDataSource(); } if (getUser() == null) { conn = dataSource.getConnection(); } else { conn = dataSource.getConnection(getUser(), getPassword()); } } catch (final NamingException ne) { getLogger().error("Error while getting data source", ne); throw new SQLException("NamingException while looking up DataSource: " + ne.getMessage()); } catch (final ClassCastException cce) { getLogger().error("ClassCastException while looking up DataSource.", cce); throw new SQLException("ClassCastException while looking up DataSource: " + cce.getMessage()); } return conn; } /** * Returns the jndiLocation. * @return String */ public String getJndiLocation() { return jndiLocation; } /** * Sets the jndiLocation. * @param jndiLocation The jndiLocation to set */ public void setJndiLocation(String jndiLocation) { this.jndiLocation = jndiLocation; } private DataSource lookupDataSource() throws NamingException, SQLException { DataSource ds; Context ctx = new InitialContext(); Object obj = ctx.lookup(jndiLocation); // PortableRemoteObject was introduced in JDK 1.3. We won't use it. //ds = (DataSource)PortableRemoteObject.narrow(obj, DataSource.class); ds = (DataSource) obj; if (ds == null) { throw new SQLException("Failed to obtain data source from JNDI location " + jndiLocation); } else { return ds; } } }
apache-2.0
zstackorg/zstack
header/src/main/java/org/zstack/header/storage/primary/APICleanUpTrashOnPrimaryStorageEvent.java
1166
package org.zstack.header.storage.primary; import org.zstack.header.core.trash.CleanTrashResult; import org.zstack.header.message.APIEvent; import org.zstack.header.rest.RestResponse; import java.util.Collections; /** * Created by mingjian.deng on 2018/12/10. */ @RestResponse(allTo = "result") public class APICleanUpTrashOnPrimaryStorageEvent extends APIEvent { private CleanTrashResult result; public CleanTrashResult getResult() { return result; } public void setResult(CleanTrashResult result) { this.result = result; } public APICleanUpTrashOnPrimaryStorageEvent(String apiId) { super(apiId); } public APICleanUpTrashOnPrimaryStorageEvent() { super(null); } public static APICleanUpTrashOnPrimaryStorageEvent __example__() { APICleanUpTrashOnPrimaryStorageEvent event = new APICleanUpTrashOnPrimaryStorageEvent(); CleanTrashResult cleaned = new CleanTrashResult(); String uuid = uuid(); cleaned.setResourceUuids(Collections.singletonList(uuid)); cleaned.setSize(1024000L); event.setResult(cleaned); return event; } }
apache-2.0
papicella/snappy-store
gemfire-core/src/main/java/com/gemstone/gemfire/cache/query/internal/Support.java
2551
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. See accompanying * LICENSE file. */ package com.gemstone.gemfire.cache.query.internal; import com.gemstone.gemfire.internal.i18n.LocalizedStrings; import com.gemstone.gemfire.InternalGemFireError; public class Support { public static final boolean ASSERTIONS_ENABLED = true; private static final int OTHER = 0; private static final int STATE = 1; private static final int ARG = 2; public static void assertArg(boolean b, String message) { if (!ASSERTIONS_ENABLED) return; Assert(b, message, ARG); } public static void assertState(boolean b, String message) { if (!ASSERTIONS_ENABLED) return; Assert(b, message, STATE); } public static void Assert(boolean b) { if (!ASSERTIONS_ENABLED) return; Assert(b, "", OTHER); } public static void Assert(boolean b, String message) { if (!ASSERTIONS_ENABLED) return; Assert(b, message, OTHER); } public static void assertionFailed(String message) { assertionFailed(message, OTHER); } public static void assertionFailed() { assertionFailed("", OTHER); } private static void Assert(boolean b, String message, int type) { if (!b) assertionFailed(message, type); } private static void assertionFailed(String message, int type) { switch (type) { case ARG: throw new IllegalArgumentException(message); case STATE: throw new IllegalStateException(message); default: throw new InternalGemFireError(LocalizedStrings.Support_ERROR_ASSERTION_FAILED_0.toLocalizedString(message)); } // com.gemstone.persistence.jdo.GsRuntime.notifyCDebugger(null); } }
apache-2.0
cloudbearings/SMART-GH
core/src/main/java/com/graphhopper/routing/util/Bike2WeightFlagEncoder.java
8495
/* * Licensed to Peter Karich under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * Peter Karich 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 com.graphhopper.routing.util; import com.graphhopper.reader.OSMWay; import com.graphhopper.util.BitUtil; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.PointList; import static com.graphhopper.util.Helper.*; /** * Stores two speed values into an edge to support avoiding too much incline * <p> * @author Peter Karich */ public class Bike2WeightFlagEncoder extends BikeFlagEncoder { private EncodedDoubleValue reverseSpeed; @Override public int defineWayBits( int index, int shift ) { shift = super.defineWayBits(index, shift); reverseSpeed = new EncodedDoubleValue("Speed", shift, speedBits, speedFactor, getHighwaySpeed("cycleway"), 30); shift += reverseSpeed.getBits(); return shift; } @Override public double getReverseSpeed( long flags ) { return reverseSpeed.getDoubleValue(flags); } @Override public long setReverseSpeed( long flags, double speed ) { if (speed < 0) throw new IllegalArgumentException("Speed cannot be negative: " + speed + ", flags:" + BitUtil.LITTLE.toBitString(flags)); if (speed > getMaxSpeed()) speed = getMaxSpeed(); return reverseSpeed.setDoubleValue(flags, speed); } @Override public long handleSpeed( OSMWay way, double speed, long encoded ) { // handle oneways if ((way.hasTag("oneway", oneways) || way.hasTag("junction", "roundabout")) && !way.hasTag("oneway:bicycle", "no") && !way.hasTag("cycleway", oppositeLanes)) { if (way.hasTag("oneway", "-1")) { encoded |= backwardBit; encoded = setReverseSpeed(encoded, speed); } else { encoded |= forwardBit; encoded = setSpeed(encoded, speed); } } else { encoded |= directionBitMask; encoded = setSpeed(encoded, speed); encoded = setReverseSpeed(encoded, speed); } return encoded; } @Override public long flagsDefault( boolean forward, boolean backward ) { long flags = super.flagsDefault(forward, backward); if (backward) return reverseSpeed.setDefaultValue(flags); return flags; } @Override public long setProperties( double speed, boolean forward, boolean backward ) { long flags = super.setProperties(speed, forward, backward); if (backward) return setReverseSpeed(flags, speed); return flags; } @Override public long reverseFlags( long flags ) { // swap access flags = super.reverseFlags(flags); // swap speeds double otherValue = reverseSpeed.getDoubleValue(flags); flags = setReverseSpeed(flags, speedEncoder.getDoubleValue(flags)); return setSpeed(flags, otherValue); } @Override public void applyWayTags( OSMWay way, EdgeIteratorState edge ) { PointList pl = edge.fetchWayGeometry(3); if (!pl.is3D()) throw new IllegalStateException("To support speed calculation based on elevation data it is necessary to enable import of it."); long flags = edge.getFlags(); if (way.hasTag("tunnel", "yes") || way.hasTag("bridge", "yes") || way.hasTag("highway", "steps")) { // do not change speed // note: although tunnel can have a difference in elevation it is very unlikely that the elevation data is correct for a tunnel } else { // Decrease the speed for ele increase (incline), and decrease the speed for ele decrease (decline). The speed-decrease // has to be bigger (compared to the speed-increase) for the same elevation difference to simulate loosing energy and avoiding hills. // For the reverse speed this has to be the opposite but again keeping in mind that up+down difference. double incEleSum = 0, incDist2DSum = 0; double decEleSum = 0, decDist2DSum = 0; // double prevLat = pl.getLatitude(0), prevLon = pl.getLongitude(0); double prevEle = pl.getElevation(0); double fullDist2D = 0; fullDist2D = edge.getDistance(); double eleDelta = pl.getElevation(pl.size() - 1) - prevEle; if (eleDelta > 0.1) { incEleSum = eleDelta; incDist2DSum = fullDist2D; } else if (eleDelta < -0.1) { decEleSum = -eleDelta; decDist2DSum = fullDist2D; } // // get a more detailed elevation information, but due to bad SRTM data this does not make sense now. // for (int i = 1; i < pl.size(); i++) // { // double lat = pl.getLatitude(i); // double lon = pl.getLongitude(i); // double ele = pl.getElevation(i); // double eleDelta = ele - prevEle; // double dist2D = distCalc.calcDist(prevLat, prevLon, lat, lon); // if (eleDelta > 0.1) // { // incEleSum += eleDelta; // incDist2DSum += dist2D; // } else if (eleDelta < -0.1) // { // decEleSum += -eleDelta; // decDist2DSum += dist2D; // } // fullDist2D += dist2D; // prevLat = lat; // prevLon = lon; // prevEle = ele; // } // Calculate slop via tan(asin(height/distance)) but for rather smallish angles where we can assume tan a=a and sin a=a. // Then calculate a factor which decreases or increases the speed. // Do this via a simple quadratic equation where y(0)=1 and y(0.3)=1/4 for incline and y(0.3)=2 for decline double fwdIncline = incDist2DSum > 1 ? incEleSum / incDist2DSum : 0; double fwdDecline = decDist2DSum > 1 ? decEleSum / decDist2DSum : 0; double restDist2D = fullDist2D - incDist2DSum - decDist2DSum; double maxSpeed = getHighwaySpeed("cycleway"); if (isBool(flags, K_FORWARD)) { // use weighted mean so that longer incline infuences speed more than shorter double speed = getSpeed(flags); double fwdFaster = 1 + 2 * keepIn(fwdDecline, 0, 0.2); fwdFaster = fwdFaster * fwdFaster; double fwdSlower = 1 - 5 * keepIn(fwdIncline, 0, 0.2); fwdSlower = fwdSlower * fwdSlower; speed = speed * (fwdSlower * incDist2DSum + fwdFaster * decDist2DSum + 1 * restDist2D) / fullDist2D; flags = this.setSpeed(flags, keepIn(speed, PUSHING_SECTION_SPEED / 2, maxSpeed)); } if (isBool(flags, K_BACKWARD)) { double speedReverse = getReverseSpeed(flags); double bwFaster = 1 + 2 * keepIn(fwdIncline, 0, 0.2); bwFaster = bwFaster * bwFaster; double bwSlower = 1 - 5 * keepIn(fwdDecline, 0, 0.2); bwSlower = bwSlower * bwSlower; speedReverse = speedReverse * (bwFaster * incDist2DSum + bwSlower * decDist2DSum + 1 * restDist2D) / fullDist2D; flags = this.setReverseSpeed(flags, keepIn(speedReverse, PUSHING_SECTION_SPEED / 2, maxSpeed)); } } edge.setFlags(flags); } @Override public String toString() { return "bike2"; } }
apache-2.0
ThiagoGarciaAlves/intellij-community
java/execution/impl/src/com/intellij/execution/applet/AppletConfiguration.java
10339
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.execution.applet; import com.intellij.execution.*; import com.intellij.execution.configurations.*; import com.intellij.execution.junit.RefactoringListeners; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.util.JavaParametersUtil; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JdkUtil; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.refactoring.listeners.RefactoringElementListener; import com.intellij.util.xmlb.annotations.Transient; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; public class AppletConfiguration extends ModuleBasedConfiguration<JavaRunConfigurationModule> implements SingleClassConfiguration, RefactoringListenerProvider, PersistentStateComponent<Element> { public AppletConfiguration(@NotNull Project project, @NotNull ConfigurationFactory factory) { super(new JavaRunConfigurationModule(project, false), factory); } @Override public AppletConfigurationOptions getOptions() { return (AppletConfigurationOptions)super.getOptions(); } @Override protected Class<AppletConfigurationOptions> getOptionsClass() { return AppletConfigurationOptions.class; } @Override public void setMainClass(final PsiClass psiClass) { final Module originalModule = getConfigurationModule().getModule(); setMainClassName(JavaExecutionUtil.getRuntimeQualifiedName(psiClass)); setModule(JavaExecutionUtil.findModule(psiClass)); restoreOriginalModule(originalModule); } @Override public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException { return new JavaCommandLineState(env) { private AppletHtmlFile myHtmlURL = null; @Override protected JavaParameters createJavaParameters() throws ExecutionException { final JavaParameters params = new JavaParameters(); myHtmlURL = getHtmlURL(); final int classPathType = myHtmlURL.isHttp() ? JavaParameters.JDK_ONLY : JavaParameters.JDK_AND_CLASSES; final RunConfigurationModule runConfigurationModule = getConfigurationModule(); JavaParametersUtil.configureModule(runConfigurationModule, params, classPathType, getOptions().isAlternativeJrePathEnabled() ? getOptions().getAlternativeJrePath() : null); final String policyFileParameter = getPolicyFileParameter(); if (policyFileParameter != null) { params.getVMParametersList().add(policyFileParameter); } params.getVMParametersList().addParametersString(getOptions().getVmParameters()); params.setMainClass("sun.applet.AppletViewer"); params.getProgramParametersList().add(myHtmlURL.getUrl()); return params; } @Override @NotNull protected OSProcessHandler startProcess() throws ExecutionException { final OSProcessHandler handler = super.startProcess(); final AppletHtmlFile htmlUrl = myHtmlURL; if (htmlUrl != null) { handler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(@NotNull ProcessEvent event) { htmlUrl.deleteFile(); } }); } return handler; } }; } @Override @NotNull public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() { return new AppletConfigurable(getProject()); } private String getPolicyFileParameter() { if (!StringUtil.isEmpty(getOptions().getPolicyFile())) { //noinspection SpellCheckingInspection return "-Djava.security.policy=" + getPolicyFile(); } return null; } @Transient public String getPolicyFile() { return ExternalizablePath.localPathValue(getOptions().getPolicyFile()); } public void setPolicyFile(final String localPath) { getOptions().setPolicyFile(ExternalizablePath.urlValue(localPath)); } @Override public Collection<Module> getValidModules() { return JavaRunConfigurationModule.getModulesForClass(getProject(), getOptions().getMainClassName()); } @Override public Element getState() { Element element = new Element("state"); super.writeExternal(element); return element; } @Override public RefactoringElementListener getRefactoringElementListener(final PsiElement element) { if (getOptions().getHtmlUsed()) { return null; } return RefactoringListeners.getClassOrPackageListener(element, new RefactoringListeners.SingleClassConfigurationAccessor(this)); } @Override @Transient public PsiClass getMainClass() { return getConfigurationModule().findClass(getOptions().getMainClassName()); } @Override public String suggestedName() { if (getOptions().getMainClassName() == null) { return null; } return ProgramRunnerUtil.shortenName(JavaExecutionUtil.getShortClassName(getOptions().getMainClassName()), 0); } @Override public void setMainClassName(@Nullable String qualifiedName) { getOptions().setMainClassName(qualifiedName); } @Override public void checkConfiguration() throws RuntimeConfigurationException { if (getOptions().isAlternativeJrePathEnabled() && (StringUtil.isEmptyOrSpaces(getOptions().getAlternativeJrePath()) || !JdkUtil.checkForJre(getOptions().getAlternativeJrePath()))) { throw new RuntimeConfigurationWarning(ExecutionBundle.message("jre.not.valid.error.message", getOptions().getAlternativeJrePath())); } getConfigurationModule().checkForWarning(); if (getOptions().getHtmlUsed()) { if (getOptions().getHtmlFileName() == null) { throw new RuntimeConfigurationWarning(ExecutionBundle.message("html.file.not.specified.error.message")); } try { new URL(getHtmlURL().getUrl()); } catch (CantRunException | MalformedURLException ex) { checkUrlIsValid(ex); } } else { getConfigurationModule().checkClassName(getOptions().getMainClassName(), ExecutionBundle.message("no.applet.class.specified.error.message")); } } private void checkUrlIsValid(Exception ex) throws RuntimeConfigurationWarning { throw new RuntimeConfigurationWarning("URL " + getOptions().getHtmlFileName() + " is not valid: " + ex.getLocalizedMessage()); } private AppletHtmlFile getHtmlURL() throws CantRunException { if (getOptions().getHtmlUsed()) { if (getOptions().getHtmlFileName() == null) { throw new CantRunException(ExecutionBundle.message("html.file.not.specified.error.message")); } return new AppletHtmlFile(getOptions().getHtmlFileName(), null); } else { if (getOptions().getMainClassName() == null) { throw new CantRunException(ExecutionBundle.message("class.not.specified.error.message")); } // generate html try { return generateAppletTempPage(); } catch (IOException ignored) { throw new CantRunException(ExecutionBundle.message("failed.to.generate.wrapper.error.message")); } } } @NotNull private AppletHtmlFile generateAppletTempPage() throws IOException { final File tempFile = FileUtil.createTempFile("AppletPage", ".html"); @NonNls final FileWriter writer = new FileWriter(tempFile); try { writer.write("<html>\n" + "<head>\n" + "<title>" + getOptions().getMainClassName() + "</title>\n" + "</head>\n" + "<applet codebase=\".\"\n" + "code=\"" + getOptions().getMainClassName() + "\"\n" + "name=\"" + getOptions().getMainClassName() + "\"\n" + "width=" + getOptions().getWidth() + "\n" + "height=" + getOptions().getHeight() + "\n" + "align=top>\n"); for (AppletParameter parameter : getOptions().getAppletParameters()) { writer.write("<param name=\"" + parameter.getName() + "\" value=\"" + parameter.getValue() + "\">\n"); } writer.write("</applet>\n</body>\n</html>\n"); } finally { writer.close(); } return new AppletHtmlFile(tempFile.getAbsolutePath(), tempFile); } private static class AppletHtmlFile { private final String myHtmlFile; private final File myFileToDelete; @NonNls protected static final String FILE_PREFIX = "file:/"; @NonNls protected static final String HTTP_PREFIX = "http:/"; @NonNls protected static final String HTTPS_PREFIX = "https:/"; protected AppletHtmlFile(final String htmlFile, final File fileToDelete) { myHtmlFile = htmlFile; myFileToDelete = fileToDelete; } public String getUrl() { if (!StringUtil.startsWithIgnoreCase(myHtmlFile, FILE_PREFIX) && !isHttp()) { try { //noinspection deprecation return new File(myHtmlFile).toURL().toString(); } catch (MalformedURLException ignored) { } } return myHtmlFile; } public boolean isHttp() { return StringUtil.startsWithIgnoreCase(myHtmlFile, HTTP_PREFIX) || StringUtil.startsWithIgnoreCase(myHtmlFile, HTTPS_PREFIX); } public void deleteFile() { if (myFileToDelete != null) { //noinspection ResultOfMethodCallIgnored myFileToDelete.delete(); } } } }
apache-2.0
fogbeam/cas_mirror
support/cas-server-support-webauthn-rest/src/main/java/org/apereo/cas/config/RestfulWebAuthnConfiguration.java
1534
package org.apereo.cas.config; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.util.crypto.CipherExecutor; import org.apereo.cas.webauthn.RestfulWebAuthnCredentialRepository; import org.apereo.cas.webauthn.storage.WebAuthnCredentialRepository; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * This is {@link RestfulWebAuthnConfiguration}. * * @author Misagh Moayyed * @since 6.4.0 */ @Configuration(value = "RestfulWebAuthnConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public class RestfulWebAuthnConfiguration { @Autowired private CasConfigurationProperties casProperties; @Autowired @Qualifier("webAuthnCredentialRegistrationCipherExecutor") private ObjectProvider<CipherExecutor<String, String>> webAuthnCredentialRegistrationCipherExecutor; @RefreshScope @Bean public WebAuthnCredentialRepository webAuthnCredentialRepository() { return new RestfulWebAuthnCredentialRepository( casProperties, webAuthnCredentialRegistrationCipherExecutor.getObject()); } }
apache-2.0
robinverduijn/gradle
subprojects/docs/src/samples/java/withIntegrationTests/src/test/java/org/gradle/PersonTestFixture.java
205
package org.gradle; import static org.junit.Assert.*; public class PersonTestFixture { public static Person create(String name) { assertNotNull(name); return new Person(name); } }
apache-2.0
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/fsm/StateDescriptorGraph.java
20360
/** * * Copyright 2018-2021 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack.fsm; import java.io.PrintWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.jivesoftware.smack.c2s.ModularXmppClientToServerConnection.DisconnectedStateDescriptor; import org.jivesoftware.smack.c2s.internal.ModularXmppClientToServerConnectionInternal; import org.jivesoftware.smack.util.Consumer; import org.jivesoftware.smack.util.MultiMap; /** * Smack's utility API for Finite State Machines (FSM). * * <p> * Thanks to Andreas Fried for the fun and successful bug hunting session. * </p> * * @author Florian Schmaus * */ public class StateDescriptorGraph { private static GraphVertex<StateDescriptor> addNewStateDescriptorGraphVertex( Class<? extends StateDescriptor> stateDescriptorClass, Map<Class<? extends StateDescriptor>, GraphVertex<StateDescriptor>> graphVertexes) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Constructor<? extends StateDescriptor> stateDescriptorConstructor = stateDescriptorClass.getDeclaredConstructor(); stateDescriptorConstructor.setAccessible(true); StateDescriptor stateDescriptor = stateDescriptorConstructor.newInstance(); GraphVertex<StateDescriptor> graphVertexStateDescriptor = new GraphVertex<>(stateDescriptor); GraphVertex<StateDescriptor> previous = graphVertexes.put(stateDescriptorClass, graphVertexStateDescriptor); assert previous == null; return graphVertexStateDescriptor; } private static final class HandleStateDescriptorGraphVertexContext { private final Set<Class<? extends StateDescriptor>> handledStateDescriptors = new HashSet<>(); Map<Class<? extends StateDescriptor>, GraphVertex<StateDescriptor>> graphVertexes; MultiMap<Class<? extends StateDescriptor>, Class<? extends StateDescriptor>> inferredForwardEdges; private HandleStateDescriptorGraphVertexContext( Map<Class<? extends StateDescriptor>, GraphVertex<StateDescriptor>> graphVertexes, MultiMap<Class<? extends StateDescriptor>, Class<? extends StateDescriptor>> inferredForwardEdges) { this.graphVertexes = graphVertexes; this.inferredForwardEdges = inferredForwardEdges; } private boolean recurseInto(Class<? extends StateDescriptor> stateDescriptorClass) { boolean wasAdded = handledStateDescriptors.add(stateDescriptorClass); boolean alreadyHandled = !wasAdded; return alreadyHandled; } private GraphVertex<StateDescriptor> getOrConstruct(Class<? extends StateDescriptor> stateDescriptorClass) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { GraphVertex<StateDescriptor> graphVertexStateDescriptor = graphVertexes.get(stateDescriptorClass); if (graphVertexStateDescriptor == null) { graphVertexStateDescriptor = addNewStateDescriptorGraphVertex(stateDescriptorClass, graphVertexes); for (Class<? extends StateDescriptor> inferredSuccessor : inferredForwardEdges.getAll( stateDescriptorClass)) { graphVertexStateDescriptor.getElement().addSuccessor(inferredSuccessor); } } return graphVertexStateDescriptor; } } private static void handleStateDescriptorGraphVertex(GraphVertex<StateDescriptor> node, HandleStateDescriptorGraphVertexContext context, boolean failOnUnknownStates) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Class<? extends StateDescriptor> stateDescriptorClass = node.element.getClass(); boolean alreadyHandled = context.recurseInto(stateDescriptorClass); if (alreadyHandled) { return; } Set<Class<? extends StateDescriptor>> successorClasses = node.element.getSuccessors(); int numSuccessors = successorClasses.size(); Map<Class<? extends StateDescriptor>, GraphVertex<StateDescriptor>> successorStateDescriptors = new HashMap<>( numSuccessors); for (Class<? extends StateDescriptor> successorClass : successorClasses) { GraphVertex<StateDescriptor> successorGraphNode = context.getOrConstruct(successorClass); successorStateDescriptors.put(successorClass, successorGraphNode); } switch (numSuccessors) { case 0: throw new IllegalStateException("State " + stateDescriptorClass + " has no successor"); case 1: GraphVertex<StateDescriptor> soleSuccessorNode = successorStateDescriptors.values().iterator().next(); node.addOutgoingEdge(soleSuccessorNode); handleStateDescriptorGraphVertex(soleSuccessorNode, context, failOnUnknownStates); return; } // We hit a state with multiple successors, perform a topological sort on the successors first. // Process the information regarding subordinates and superiors states. // The preference graph is the graph where the precedence information of all successors is stored, which we will // topologically sort to find out which successor we should try first. It is a further new graph we use solely in // this step for every node. The graph is represented as map. There is no special marker for the initial node // as it is not required for the topological sort performed later. Map<Class<? extends StateDescriptor>, GraphVertex<Class<? extends StateDescriptor>>> preferenceGraph = new HashMap<>(numSuccessors); // Iterate over all successor states of the current state. for (GraphVertex<StateDescriptor> successorStateDescriptorGraphNode : successorStateDescriptors.values()) { StateDescriptor successorStateDescriptor = successorStateDescriptorGraphNode.element; Class<? extends StateDescriptor> successorStateDescriptorClass = successorStateDescriptor.getClass(); for (Class<? extends StateDescriptor> subordinateClass : successorStateDescriptor.getSubordinates()) { if (failOnUnknownStates && !successorClasses.contains(subordinateClass)) { throw new IllegalStateException(successorStateDescriptor + " points to a subordinate '" + subordinateClass + "' which is not part of the successor set"); } GraphVertex<Class<? extends StateDescriptor>> superiorClassNode = lookupAndCreateIfRequired( preferenceGraph, successorStateDescriptorClass); GraphVertex<Class<? extends StateDescriptor>> subordinateClassNode = lookupAndCreateIfRequired( preferenceGraph, subordinateClass); superiorClassNode.addOutgoingEdge(subordinateClassNode); } for (Class<? extends StateDescriptor> superiorClass : successorStateDescriptor.getSuperiors()) { if (failOnUnknownStates && !successorClasses.contains(superiorClass)) { throw new IllegalStateException(successorStateDescriptor + " points to a superior '" + superiorClass + "' which is not part of the successor set"); } GraphVertex<Class<? extends StateDescriptor>> subordinateClassNode = lookupAndCreateIfRequired( preferenceGraph, successorStateDescriptorClass); GraphVertex<Class<? extends StateDescriptor>> superiorClassNode = lookupAndCreateIfRequired( preferenceGraph, superiorClass); superiorClassNode.addOutgoingEdge(subordinateClassNode); } } // Perform a topological sort which returns the state descriptor classes sorted by their priority. Highest // priority state descriptors first. List<GraphVertex<Class<? extends StateDescriptor>>> sortedSuccessors = topologicalSort(preferenceGraph.values()); // Handle the successor nodes which have not preference information available. Simply append them to the end of // the sorted successor list. outerloop: for (Class<? extends StateDescriptor> successorStateDescriptor : successorClasses) { for (GraphVertex<Class<? extends StateDescriptor>> sortedSuccessor : sortedSuccessors) { if (sortedSuccessor.getElement() == successorStateDescriptor) { continue outerloop; } } sortedSuccessors.add(new GraphVertex<>(successorStateDescriptor)); } for (GraphVertex<Class<? extends StateDescriptor>> successor : sortedSuccessors) { GraphVertex<StateDescriptor> successorVertex = successorStateDescriptors.get(successor.element); if (successorVertex == null) { // The successor does not exist, probably because its module was not enabled. continue; } node.addOutgoingEdge(successorVertex); // Recurse further. handleStateDescriptorGraphVertex(successorVertex, context, failOnUnknownStates); } } public static GraphVertex<StateDescriptor> constructStateDescriptorGraph( Set<Class<? extends StateDescriptor>> backwardEdgeStateDescriptors, boolean failOnUnknownStates) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Map<Class<? extends StateDescriptor>, GraphVertex<StateDescriptor>> graphVertexes = new HashMap<>(); final Class<? extends StateDescriptor> initialStatedescriptorClass = DisconnectedStateDescriptor.class; GraphVertex<StateDescriptor> initialNode = addNewStateDescriptorGraphVertex(initialStatedescriptorClass, graphVertexes); MultiMap<Class<? extends StateDescriptor>, Class<? extends StateDescriptor>> inferredForwardEdges = new MultiMap<>(); for (Class<? extends StateDescriptor> backwardsEdge : backwardEdgeStateDescriptors) { GraphVertex<StateDescriptor> graphVertexStateDescriptor = addNewStateDescriptorGraphVertex(backwardsEdge, graphVertexes); for (Class<? extends StateDescriptor> predecessor : graphVertexStateDescriptor.getElement().getPredeccessors()) { inferredForwardEdges.put(predecessor, backwardsEdge); } } // Ensure that the intial node has their successors inferred. for (Class<? extends StateDescriptor> inferredSuccessorOfInitialStateDescriptor : inferredForwardEdges.getAll(initialStatedescriptorClass)) { initialNode.getElement().addSuccessor(inferredSuccessorOfInitialStateDescriptor); } HandleStateDescriptorGraphVertexContext context = new HandleStateDescriptorGraphVertexContext(graphVertexes, inferredForwardEdges); handleStateDescriptorGraphVertex(initialNode, context, failOnUnknownStates); return initialNode; } private static GraphVertex<State> convertToStateGraph(GraphVertex<StateDescriptor> stateDescriptorVertex, ModularXmppClientToServerConnectionInternal connectionInternal, Map<StateDescriptor, GraphVertex<State>> handledStateDescriptors) { StateDescriptor stateDescriptor = stateDescriptorVertex.getElement(); GraphVertex<State> stateVertex = handledStateDescriptors.get(stateDescriptor); if (stateVertex != null) { return stateVertex; } State state = stateDescriptor.constructState(connectionInternal); stateVertex = new GraphVertex<>(state); handledStateDescriptors.put(stateDescriptor, stateVertex); for (GraphVertex<StateDescriptor> successorStateDescriptorVertex : stateDescriptorVertex.getOutgoingEdges()) { GraphVertex<State> successorStateVertex = convertToStateGraph(successorStateDescriptorVertex, connectionInternal, handledStateDescriptors); // It is important that we keep the order of the edges. This should do it. stateVertex.addOutgoingEdge(successorStateVertex); } return stateVertex; } public static GraphVertex<State> convertToStateGraph(GraphVertex<StateDescriptor> initialStateDescriptor, ModularXmppClientToServerConnectionInternal connectionInternal) { Map<StateDescriptor, GraphVertex<State>> handledStateDescriptors = new HashMap<>(); GraphVertex<State> initialState = convertToStateGraph(initialStateDescriptor, connectionInternal, handledStateDescriptors); return initialState; } // Graph API after here. // This API could possibly factored out into an extra package/class, but then we will probably need a builder for // the graph vertex in order to keep it immutable. public static final class GraphVertex<E> { private final E element; private final List<GraphVertex<E>> outgoingEdges = new ArrayList<>(); private VertexColor color = VertexColor.white; private GraphVertex(E element) { this.element = element; } private void addOutgoingEdge(GraphVertex<E> vertex) { assert vertex != null; if (outgoingEdges.contains(vertex)) { throw new IllegalArgumentException("This " + this + " already has an outgoing edge to " + vertex); } outgoingEdges.add(vertex); } public E getElement() { return element; } public List<GraphVertex<E>> getOutgoingEdges() { return Collections.unmodifiableList(outgoingEdges); } private enum VertexColor { white, grey, black, } @Override public String toString() { return toString(true); } public String toString(boolean includeOutgoingEdges) { StringBuilder sb = new StringBuilder(); sb.append("GraphVertex " + element + " [color=" + color + ", identityHashCode=" + System.identityHashCode(this) + ", outgoingEdgeCount=" + outgoingEdges.size()); if (includeOutgoingEdges) { sb.append(", outgoingEdges={"); for (Iterator<GraphVertex<E>> it = outgoingEdges.iterator(); it.hasNext();) { GraphVertex<E> outgoingEdgeVertex = it.next(); sb.append(outgoingEdgeVertex.toString(false)); if (it.hasNext()) { sb.append(", "); } } sb.append('}'); } sb.append(']'); return sb.toString(); } } private static GraphVertex<Class<? extends StateDescriptor>> lookupAndCreateIfRequired( Map<Class<? extends StateDescriptor>, GraphVertex<Class<? extends StateDescriptor>>> map, Class<? extends StateDescriptor> clazz) { GraphVertex<Class<? extends StateDescriptor>> vertex = map.get(clazz); if (vertex == null) { vertex = new GraphVertex<>(clazz); map.put(clazz, vertex); } return vertex; } private static <E> List<GraphVertex<E>> topologicalSort(Collection<GraphVertex<E>> vertexes) { List<GraphVertex<E>> res = new ArrayList<>(); dfs(vertexes, vertex -> res.add(0, vertex), null); return res; } private static <E> void dfsVisit(GraphVertex<E> vertex, Consumer<GraphVertex<E>> dfsFinishedVertex, DfsEdgeFound<E> dfsEdgeFound) { vertex.color = GraphVertex.VertexColor.grey; final int totalEdgeCount = vertex.getOutgoingEdges().size(); int edgeCount = 0; for (GraphVertex<E> successorVertex : vertex.getOutgoingEdges()) { edgeCount++; if (dfsEdgeFound != null) { dfsEdgeFound.onEdgeFound(vertex, successorVertex, edgeCount, totalEdgeCount); } if (successorVertex.color == GraphVertex.VertexColor.white) { dfsVisit(successorVertex, dfsFinishedVertex, dfsEdgeFound); } } vertex.color = GraphVertex.VertexColor.black; if (dfsFinishedVertex != null) { dfsFinishedVertex.accept(vertex); } } private static <E> void dfs(Collection<GraphVertex<E>> vertexes, Consumer<GraphVertex<E>> dfsFinishedVertex, DfsEdgeFound<E> dfsEdgeFound) { for (GraphVertex<E> vertex : vertexes) { if (vertex.color == GraphVertex.VertexColor.white) { dfsVisit(vertex, dfsFinishedVertex, dfsEdgeFound); } } } public static <E> void stateDescriptorGraphToDot(Collection<GraphVertex<StateDescriptor>> vertexes, PrintWriter dotOut, boolean breakStateName) { dotOut.append("digraph {\n"); dfs(vertexes, finishedVertex -> { boolean isMultiVisitState = finishedVertex.element.isMultiVisitState(); boolean isFinalState = finishedVertex.element.isFinalState(); boolean isNotImplemented = finishedVertex.element.isNotImplemented(); String style = null; if (isMultiVisitState) { style = "bold"; } else if (isFinalState) { style = "filled"; } else if (isNotImplemented) { style = "dashed"; } if (style == null) { return; } dotOut.append('"') .append(finishedVertex.element.getFullStateName(breakStateName)) .append("\" [ ") .append("style=") .append(style) .append(" ]\n"); }, (from, to, edgeId, totalEdgeCount) -> { dotOut.append(" \"") .append(from.element.getFullStateName(breakStateName)) .append("\" -> \"") .append(to.element.getFullStateName(breakStateName)) .append('"'); if (totalEdgeCount > 1) { // Note that 'dot' requires *double* quotes to enclose the value. dotOut.append(" [xlabel=\"") .append(Integer.toString(edgeId)) .append("\"]"); } dotOut.append(";\n"); }); dotOut.append("}\n"); } private interface DfsEdgeFound<E> { void onEdgeFound(GraphVertex<E> from, GraphVertex<E> to, int edgeId, int totalEdgeCount); } }
apache-2.0
ChosenGlobal/bbs
src/main/java/cn/jfinalbbs/utils/Result.java
823
package cn.jfinalbbs.utils; /** * Created by liuyang on 15/4/4. */ public class Result { private String code; private String description; private Object detail; public Result() { } public Result(String code, String description, Object detail) { this.code = code; this.description = description; this.detail = detail; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Object getDetail() { return detail; } public void setDetail(Object detail) { this.detail = detail; } }
apache-2.0
raviperi/storm
storm-client/test/jvm/org/apache/storm/windowing/WindowManagerTest.java
25112
/** * 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.storm.windowing; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.apache.storm.topology.base.BaseWindowedBolt.Count; import static org.apache.storm.topology.base.BaseWindowedBolt.Duration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Unit tests for {@link WindowManager} */ public class WindowManagerTest { private WindowManager<Integer> windowManager; private Listener listener; private static class Listener implements WindowLifecycleListener<Integer> { List<Integer> onExpiryEvents = Collections.emptyList(); List<Integer> onActivationEvents = Collections.emptyList(); List<Integer> onActivationNewEvents = Collections.emptyList(); List<Integer> onActivationExpiredEvents = Collections.emptyList(); // all events since last clear List<List<Integer>> allOnExpiryEvents = new ArrayList<>(); List<List<Integer>> allOnActivationEvents = new ArrayList<>(); List<List<Integer>> allOnActivationNewEvents = new ArrayList<>(); List<List<Integer>> allOnActivationExpiredEvents = new ArrayList<>(); @Override public void onExpiry(List<Integer> events) { onExpiryEvents = events; allOnExpiryEvents.add(events); } @Override public void onActivation(List<Integer> events, List<Integer> newEvents, List<Integer> expired, Long timestamp) { onActivationEvents = events; allOnActivationEvents.add(events); onActivationNewEvents = newEvents; allOnActivationNewEvents.add(newEvents); onActivationExpiredEvents = expired; allOnActivationExpiredEvents.add(expired); } void clear() { onExpiryEvents = Collections.emptyList(); onActivationEvents = Collections.emptyList(); onActivationNewEvents = Collections.emptyList(); onActivationExpiredEvents = Collections.emptyList(); allOnExpiryEvents.clear(); allOnActivationEvents.clear(); allOnActivationNewEvents.clear(); allOnActivationExpiredEvents.clear(); } } @Before public void setUp() { listener = new Listener(); windowManager = new WindowManager<>(listener); } @After public void tearDown() { windowManager.shutdown(); } @Test public void testCountBasedWindow() throws Exception { EvictionPolicy<Integer> evictionPolicy = new CountEvictionPolicy<Integer>(5); TriggerPolicy<Integer> triggerPolicy = new CountTriggerPolicy<Integer>(2, windowManager, evictionPolicy); triggerPolicy.start(); windowManager.setEvictionPolicy(evictionPolicy); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1); windowManager.add(2); // nothing expired yet assertTrue(listener.onExpiryEvents.isEmpty()); assertEquals(seq(1, 2), listener.onActivationEvents); assertEquals(seq(1, 2), listener.onActivationNewEvents); assertTrue(listener.onActivationExpiredEvents.isEmpty()); windowManager.add(3); windowManager.add(4); // nothing expired yet assertTrue(listener.onExpiryEvents.isEmpty()); assertEquals(seq(1, 4), listener.onActivationEvents); assertEquals(seq(3, 4), listener.onActivationNewEvents); assertTrue(listener.onActivationExpiredEvents.isEmpty()); windowManager.add(5); windowManager.add(6); // 1 expired assertEquals(seq(1), listener.onExpiryEvents); assertEquals(seq(2, 6), listener.onActivationEvents); assertEquals(seq(5, 6), listener.onActivationNewEvents); assertEquals(seq(1), listener.onActivationExpiredEvents); listener.clear(); windowManager.add(7); // nothing expires until threshold is hit assertTrue(listener.onExpiryEvents.isEmpty()); windowManager.add(8); // 1 expired assertEquals(seq(2, 3), listener.onExpiryEvents); assertEquals(seq(4, 8), listener.onActivationEvents); assertEquals(seq(7, 8), listener.onActivationNewEvents); assertEquals(seq(2, 3), listener.onActivationExpiredEvents); } @Test public void testExpireThreshold() throws Exception { int threshold = WindowManager.EXPIRE_EVENTS_THRESHOLD; int windowLength = 5; windowManager.setEvictionPolicy(new CountEvictionPolicy<Integer>(5)); TriggerPolicy<Integer> triggerPolicy = new TimeTriggerPolicy<Integer>(new Duration(1, TimeUnit.HOURS).value, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); for (int i : seq(1, 5)) { windowManager.add(i); } // nothing expired yet assertTrue(listener.onExpiryEvents.isEmpty()); for (int i : seq(6, 10)) { windowManager.add(i); } for (int i : seq(11, threshold)) { windowManager.add(i); } // window should be compacted and events should be expired. assertEquals(seq(1, threshold - windowLength), listener.onExpiryEvents); } @Test public void testTimeBasedWindow() throws Exception { EvictionPolicy<Integer> evictionPolicy = new TimeEvictionPolicy<Integer>(new Duration(1, TimeUnit.SECONDS).value); windowManager.setEvictionPolicy(evictionPolicy); /* * Don't wait for Timetrigger to fire since this could lead to timing issues in unit tests. * Set it to a large value and trigger manually. */ TriggerPolicy<Integer> triggerPolicy = new TimeTriggerPolicy<Integer>(new Duration(1, TimeUnit.DAYS).value, windowManager, evictionPolicy); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); long now = System.currentTimeMillis(); // add with past ts for (int i : seq(1, 50)) { windowManager.add(i, now - 1000); } // add with current ts for (int i : seq(51, WindowManager.EXPIRE_EVENTS_THRESHOLD)) { windowManager.add(i, now); } // first 50 should have expired due to expire events threshold assertEquals(50, listener.onExpiryEvents.size()); // add more events with past ts for (int i : seq(WindowManager.EXPIRE_EVENTS_THRESHOLD + 1, WindowManager.EXPIRE_EVENTS_THRESHOLD + 100)) { windowManager.add(i, now - 1000); } // simulate the time trigger by setting the reference time and invoking onTrigger() manually evictionPolicy.setContext(new DefaultEvictionContext(now + 100)); windowManager.onTrigger(); // 100 events with past ts should expire assertEquals(100, listener.onExpiryEvents.size()); assertEquals(seq(WindowManager.EXPIRE_EVENTS_THRESHOLD + 1, WindowManager.EXPIRE_EVENTS_THRESHOLD + 100), listener.onExpiryEvents); List<Integer> activationsEvents = seq(51, WindowManager.EXPIRE_EVENTS_THRESHOLD); assertEquals(seq(51, WindowManager.EXPIRE_EVENTS_THRESHOLD), listener.onActivationEvents); assertEquals(seq(51, WindowManager.EXPIRE_EVENTS_THRESHOLD), listener.onActivationNewEvents); // activation expired list should contain even the ones expired due to EXPIRE_EVENTS_THRESHOLD List<Integer> expiredList = seq(1, 50); expiredList.addAll(seq(WindowManager.EXPIRE_EVENTS_THRESHOLD + 1, WindowManager.EXPIRE_EVENTS_THRESHOLD + 100)); assertEquals(expiredList, listener.onActivationExpiredEvents); listener.clear(); // add more events with current ts List<Integer> newEvents = seq(WindowManager.EXPIRE_EVENTS_THRESHOLD + 101, WindowManager.EXPIRE_EVENTS_THRESHOLD + 200); for (int i : newEvents) { windowManager.add(i, now); } activationsEvents.addAll(newEvents); // simulate the time trigger by setting the reference time and invoking onTrigger() manually evictionPolicy.setContext(new DefaultEvictionContext(now + 200)); windowManager.onTrigger(); assertTrue(listener.onExpiryEvents.isEmpty()); assertEquals(activationsEvents, listener.onActivationEvents); assertEquals(newEvents, listener.onActivationNewEvents); } @Test public void testTimeBasedWindowExpiry() throws Exception { EvictionPolicy<Integer> evictionPolicy = new TimeEvictionPolicy<Integer>(new Duration(100, TimeUnit.MILLISECONDS).value); windowManager.setEvictionPolicy(evictionPolicy); /* * Don't wait for Timetrigger to fire since this could lead to timing issues in unit tests. * Set it to a large value and trigger manually. */ TriggerPolicy<Integer> triggerPolicy = new TimeTriggerPolicy<Integer>(new Duration(1, TimeUnit.DAYS).value, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); long now = System.currentTimeMillis(); // add 10 events for (int i : seq(1, 10)) { windowManager.add(i); } // simulate the time trigger by setting the reference time and invoking onTrigger() manually evictionPolicy.setContext(new DefaultEvictionContext(now + 60)); windowManager.onTrigger(); assertEquals(seq(1, 10), listener.onActivationEvents); assertTrue(listener.onActivationExpiredEvents.isEmpty()); listener.clear(); // wait so all events expire evictionPolicy.setContext(new DefaultEvictionContext(now + 120)); windowManager.onTrigger(); assertEquals(seq(1, 10), listener.onExpiryEvents); assertTrue(listener.onActivationEvents.isEmpty()); listener.clear(); evictionPolicy.setContext(new DefaultEvictionContext(now + 180)); windowManager.onTrigger(); assertTrue(listener.onActivationExpiredEvents.isEmpty()); assertTrue(listener.onActivationEvents.isEmpty()); } @Test public void testTumblingWindow() throws Exception { EvictionPolicy<Integer> evictionPolicy = new CountEvictionPolicy<Integer>(3); windowManager.setEvictionPolicy(evictionPolicy); TriggerPolicy<Integer> triggerPolicy = new CountTriggerPolicy<Integer>(3, windowManager, evictionPolicy); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1); windowManager.add(2); // nothing expired yet assertTrue(listener.onExpiryEvents.isEmpty()); windowManager.add(3); assertTrue(listener.onExpiryEvents.isEmpty()); assertEquals(seq(1, 3), listener.onActivationEvents); assertTrue(listener.onActivationExpiredEvents.isEmpty()); assertEquals(seq(1, 3), listener.onActivationNewEvents); listener.clear(); windowManager.add(4); windowManager.add(5); windowManager.add(6); assertEquals(seq(1, 3), listener.onExpiryEvents); assertEquals(seq(4, 6), listener.onActivationEvents); assertEquals(seq(1, 3), listener.onActivationExpiredEvents); assertEquals(seq(4, 6), listener.onActivationNewEvents); } @Test public void testEventTimeBasedWindow() throws Exception { EvictionPolicy<Integer> evictionPolicy = new WatermarkTimeEvictionPolicy<>(20); windowManager.setEvictionPolicy(evictionPolicy); TriggerPolicy<Integer> triggerPolicy = new WatermarkTimeTriggerPolicy<Integer>(10, windowManager, evictionPolicy, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1, 603); windowManager.add(2, 605); windowManager.add(3, 607); // This should trigger the scan to find // the next aligned window end ts, but not produce any activations windowManager.add(new WaterMarkEvent<Integer>(609)); assertEquals(Collections.emptyList(), listener.allOnActivationEvents); windowManager.add(4, 618); windowManager.add(5, 626); windowManager.add(6, 636); // send a watermark event, which should trigger three windows. windowManager.add(new WaterMarkEvent<Integer>(631)); // System.out.println(listener.allOnActivationEvents); assertEquals(3, listener.allOnActivationEvents.size()); assertEquals(seq(1,3), listener.allOnActivationEvents.get(0)); assertEquals(seq(1, 4), listener.allOnActivationEvents.get(1)); assertEquals(seq(4, 5), listener.allOnActivationEvents.get(2)); assertEquals(Collections.emptyList(), listener.allOnActivationExpiredEvents.get(0)); assertEquals(Collections.emptyList(), listener.allOnActivationExpiredEvents.get(1)); assertEquals(seq(1, 3), listener.allOnActivationExpiredEvents.get(2)); assertEquals(seq(1, 3), listener.allOnActivationNewEvents.get(0)); assertEquals(seq(4, 4), listener.allOnActivationNewEvents.get(1)); assertEquals(seq(5, 5), listener.allOnActivationNewEvents.get(2)); assertEquals(seq(1, 3), listener.allOnExpiryEvents.get(0)); // add more events with a gap in ts windowManager.add(7, 825); windowManager.add(8, 826); windowManager.add(9, 827); windowManager.add(10, 839); listener.clear(); windowManager.add(new WaterMarkEvent<Integer>(834)); assertEquals(3, listener.allOnActivationEvents.size()); assertEquals(seq(5, 6), listener.allOnActivationEvents.get(0)); assertEquals(seq(6, 6), listener.allOnActivationEvents.get(1)); assertEquals(seq(7, 9), listener.allOnActivationEvents.get(2)); assertEquals(seq(4, 4), listener.allOnActivationExpiredEvents.get(0)); assertEquals(seq(5, 5), listener.allOnActivationExpiredEvents.get(1)); assertEquals(Collections.emptyList(), listener.allOnActivationExpiredEvents.get(2)); assertEquals(seq(6,6), listener.allOnActivationNewEvents.get(0)); assertEquals(Collections.emptyList(), listener.allOnActivationNewEvents.get(1)); assertEquals(seq(7, 9), listener.allOnActivationNewEvents.get(2)); assertEquals(seq(4, 4), listener.allOnExpiryEvents.get(0)); assertEquals(seq(5, 5), listener.allOnExpiryEvents.get(1)); assertEquals(seq(6, 6), listener.allOnExpiryEvents.get(2)); } @Test public void testCountBasedWindowWithEventTs() throws Exception { EvictionPolicy<Integer> evictionPolicy = new WatermarkCountEvictionPolicy<>(3); windowManager.setEvictionPolicy(evictionPolicy); TriggerPolicy<Integer> triggerPolicy = new WatermarkTimeTriggerPolicy<Integer>(10, windowManager, evictionPolicy, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1, 603); windowManager.add(2, 605); windowManager.add(3, 607); windowManager.add(4, 618); windowManager.add(5, 626); windowManager.add(6, 636); // send a watermark event, which should trigger three windows. windowManager.add(new WaterMarkEvent<Integer>(631)); assertEquals(3, listener.allOnActivationEvents.size()); assertEquals(seq(1, 3), listener.allOnActivationEvents.get(0)); assertEquals(seq(2, 4), listener.allOnActivationEvents.get(1)); assertEquals(seq(3, 5), listener.allOnActivationEvents.get(2)); // add more events with a gap in ts windowManager.add(7, 665); windowManager.add(8, 666); windowManager.add(9, 667); windowManager.add(10, 679); listener.clear(); windowManager.add(new WaterMarkEvent<Integer>(674)); // System.out.println(listener.allOnActivationEvents); assertEquals(4, listener.allOnActivationEvents.size()); // same set of events part of three windows assertEquals(seq(4, 6), listener.allOnActivationEvents.get(0)); assertEquals(seq(4, 6), listener.allOnActivationEvents.get(1)); assertEquals(seq(4, 6), listener.allOnActivationEvents.get(2)); assertEquals(seq(7, 9), listener.allOnActivationEvents.get(3)); } @Test public void testCountBasedTriggerWithEventTs() throws Exception { EvictionPolicy<Integer> evictionPolicy = new WatermarkTimeEvictionPolicy<Integer>(20); windowManager.setEvictionPolicy(evictionPolicy); TriggerPolicy<Integer> triggerPolicy = new WatermarkCountTriggerPolicy<Integer>(3, windowManager, evictionPolicy, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1, 603); windowManager.add(2, 605); windowManager.add(3, 607); windowManager.add(4, 618); windowManager.add(5, 625); windowManager.add(6, 626); windowManager.add(7, 629); windowManager.add(8, 636); // send a watermark event, which should trigger three windows. windowManager.add(new WaterMarkEvent<Integer>(631)); // System.out.println(listener.allOnActivationEvents); assertEquals(2, listener.allOnActivationEvents.size()); assertEquals(seq(1, 3), listener.allOnActivationEvents.get(0)); assertEquals(seq(3, 6), listener.allOnActivationEvents.get(1)); // add more events with a gap in ts windowManager.add(9, 665); windowManager.add(10, 666); windowManager.add(11, 667); windowManager.add(12, 669); windowManager.add(12, 679); listener.clear(); windowManager.add(new WaterMarkEvent<Integer>(674)); // System.out.println(listener.allOnActivationEvents); assertEquals(2, listener.allOnActivationEvents.size()); // same set of events part of three windows assertEquals(seq(9), listener.allOnActivationEvents.get(0)); assertEquals(seq(9, 12), listener.allOnActivationEvents.get(1)); } @Test public void testCountBasedTumblingWithSameEventTs() throws Exception { EvictionPolicy<Integer> evictionPolicy = new WatermarkCountEvictionPolicy<>(2); windowManager.setEvictionPolicy(evictionPolicy); TriggerPolicy<Integer> triggerPolicy = new WatermarkCountTriggerPolicy<Integer>(2, windowManager, evictionPolicy, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1, 10); windowManager.add(2, 10); windowManager.add(3, 11); windowManager.add(4, 12); windowManager.add(5, 12); windowManager.add(6, 12); windowManager.add(7, 12); windowManager.add(8, 13); windowManager.add(9, 14); windowManager.add(10, 15); windowManager.add(new WaterMarkEvent<Integer>(20)); assertEquals(5, listener.allOnActivationEvents.size()); assertEquals(seq(1, 2), listener.allOnActivationEvents.get(0)); assertEquals(seq(3, 4), listener.allOnActivationEvents.get(1)); assertEquals(seq(5, 6), listener.allOnActivationEvents.get(2)); assertEquals(seq(7, 8), listener.allOnActivationEvents.get(3)); assertEquals(seq(9, 10), listener.allOnActivationEvents.get(4)); } @Test public void testCountBasedSlidingWithSameEventTs() throws Exception { EvictionPolicy<Integer> evictionPolicy = new WatermarkCountEvictionPolicy<>(5); windowManager.setEvictionPolicy(evictionPolicy); TriggerPolicy<Integer> triggerPolicy = new WatermarkCountTriggerPolicy<Integer>(2, windowManager, evictionPolicy, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1, 10); windowManager.add(2, 10); windowManager.add(3, 11); windowManager.add(4, 12); windowManager.add(5, 12); windowManager.add(6, 12); windowManager.add(7, 12); windowManager.add(8, 13); windowManager.add(9, 14); windowManager.add(10, 15); windowManager.add(new WaterMarkEvent<Integer>(20)); assertEquals(5, listener.allOnActivationEvents.size()); assertEquals(seq(1, 2), listener.allOnActivationEvents.get(0)); assertEquals(seq(1, 4), listener.allOnActivationEvents.get(1)); assertEquals(seq(2, 6), listener.allOnActivationEvents.get(2)); assertEquals(seq(4, 8), listener.allOnActivationEvents.get(3)); assertEquals(seq(6, 10), listener.allOnActivationEvents.get(4)); } @Test public void testEventTimeLag() throws Exception { EvictionPolicy<Integer> evictionPolicy = new WatermarkTimeEvictionPolicy<>(20, 5); windowManager.setEvictionPolicy(evictionPolicy); TriggerPolicy<Integer> triggerPolicy = new WatermarkTimeTriggerPolicy<Integer>(10, windowManager, evictionPolicy, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1, 603); windowManager.add(2, 605); windowManager.add(3, 607); windowManager.add(4, 618); windowManager.add(5, 626); windowManager.add(6, 632); windowManager.add(7, 629); windowManager.add(8, 636); // send a watermark event, which should trigger three windows. windowManager.add(new WaterMarkEvent<Integer>(631)); // System.out.println(listener.allOnActivationEvents); assertEquals(3, listener.allOnActivationEvents.size()); assertEquals(seq(1, 3), listener.allOnActivationEvents.get(0)); assertEquals(seq(1, 4), listener.allOnActivationEvents.get(1)); // out of order events should be processed upto the lag assertEquals(Arrays.asList(4, 5, 7), listener.allOnActivationEvents.get(2)); } @Test public void testScanStop() throws Exception { final Set<Integer> eventsScanned = new HashSet<>(); EvictionPolicy<Integer> evictionPolicy = new WatermarkTimeEvictionPolicy<Integer>(20, 5) { @Override public Action evict(Event<Integer> event) { eventsScanned.add(event.get()); return super.evict(event); } }; windowManager.setEvictionPolicy(evictionPolicy); TriggerPolicy<Integer> triggerPolicy = new WatermarkTimeTriggerPolicy<Integer>(10, windowManager, evictionPolicy, windowManager); triggerPolicy.start(); windowManager.setTriggerPolicy(triggerPolicy); windowManager.add(1, 603); windowManager.add(2, 605); windowManager.add(3, 607); windowManager.add(4, 618); windowManager.add(5, 626); windowManager.add(6, 629); windowManager.add(7, 636); windowManager.add(8, 637); windowManager.add(9, 638); windowManager.add(10, 639); // send a watermark event, which should trigger three windows. windowManager.add(new WaterMarkEvent<Integer>(631)); assertEquals(3, listener.allOnActivationEvents.size()); assertEquals(seq(1, 3), listener.allOnActivationEvents.get(0)); assertEquals(seq(1, 4), listener.allOnActivationEvents.get(1)); // out of order events should be processed upto the lag assertEquals(Arrays.asList(4, 5, 6), listener.allOnActivationEvents.get(2)); // events 8, 9, 10 should not be scanned at all since TimeEvictionPolicy lag 5s should break // the WindowManager scan loop early. assertEquals(new HashSet<>(seq(1, 7)), eventsScanned); } private List<Integer> seq(int start) { return seq(start, start); } private List<Integer> seq(int start, int stop) { List<Integer> ints = new ArrayList<>(); for (int i = start; i <= stop; i++) { ints.add(i); } return ints; } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-compute/v1/1.31.0/com/google/api/services/compute/model/Backend.java
17306
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Message containing information of one individual backend. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Backend extends com.google.api.client.json.GenericJson { /** * Specifies how to determine whether the backend of a load balancer can handle additional traffic * or is fully loaded. For usage guidelines, see Connection balancing mode. Backends must use * compatible balancing modes. For more information, see Supported balancing modes and target * capacity settings and Restrictions and guidance for instance groups. Note: Currently, if you * use the API to configure incompatible balancing modes, the configuration might be accepted even * though it has no impact and is ignored. Specifically, Backend.maxUtilization is ignored when * Backend.balancingMode is RATE. In the future, this incompatible combination will be rejected. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String balancingMode; /** * A multiplier applied to the backend's target capacity of its balancing mode. The default value * is 1, which means the group serves up to 100% of its configured capacity (depending on * balancingMode). A setting of 0 means the group is completely drained, offering 0% of its * available capacity. The valid ranges are 0.0 and [0.1,1.0]. You cannot configure a setting * larger than 0 and smaller than 0.1. You cannot configure a setting of 0 when there is only one * backend attached to the backend service. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float capacityScaler; /** * An optional description of this resource. Provide this property when you create the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * This field designates whether this is a failover backend. More than one failover backend can be * configured for a given BackendService. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean failover; /** * The fully-qualified URL of an instance group or network endpoint group (NEG) resource. To * determine what types of backends a load balancer supports, see the [Backend services * overview](https://cloud.google.com/load-balancing/docs/backend-service#backends). You must use * the *fully-qualified* URL (starting with https://www.googleapis.com/) to specify the instance * group or NEG. Partial URLs are not supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String group; /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer maxConnections; /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer maxConnectionsPerEndpoint; /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer maxConnectionsPerInstance; /** * Defines a maximum number of HTTP requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer maxRate; /** * Defines a maximum target for requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float maxRatePerEndpoint; /** * Defines a maximum target for requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float maxRatePerInstance; /** * Optional parameter to define a target capacity for the UTILIZATIONbalancing mode. The valid * range is [0.0, 1.0]. For usage guidelines, see Utilization balancing mode. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Float maxUtilization; /** * Specifies how to determine whether the backend of a load balancer can handle additional traffic * or is fully loaded. For usage guidelines, see Connection balancing mode. Backends must use * compatible balancing modes. For more information, see Supported balancing modes and target * capacity settings and Restrictions and guidance for instance groups. Note: Currently, if you * use the API to configure incompatible balancing modes, the configuration might be accepted even * though it has no impact and is ignored. Specifically, Backend.maxUtilization is ignored when * Backend.balancingMode is RATE. In the future, this incompatible combination will be rejected. * @return value or {@code null} for none */ public java.lang.String getBalancingMode() { return balancingMode; } /** * Specifies how to determine whether the backend of a load balancer can handle additional traffic * or is fully loaded. For usage guidelines, see Connection balancing mode. Backends must use * compatible balancing modes. For more information, see Supported balancing modes and target * capacity settings and Restrictions and guidance for instance groups. Note: Currently, if you * use the API to configure incompatible balancing modes, the configuration might be accepted even * though it has no impact and is ignored. Specifically, Backend.maxUtilization is ignored when * Backend.balancingMode is RATE. In the future, this incompatible combination will be rejected. * @param balancingMode balancingMode or {@code null} for none */ public Backend setBalancingMode(java.lang.String balancingMode) { this.balancingMode = balancingMode; return this; } /** * A multiplier applied to the backend's target capacity of its balancing mode. The default value * is 1, which means the group serves up to 100% of its configured capacity (depending on * balancingMode). A setting of 0 means the group is completely drained, offering 0% of its * available capacity. The valid ranges are 0.0 and [0.1,1.0]. You cannot configure a setting * larger than 0 and smaller than 0.1. You cannot configure a setting of 0 when there is only one * backend attached to the backend service. * @return value or {@code null} for none */ public java.lang.Float getCapacityScaler() { return capacityScaler; } /** * A multiplier applied to the backend's target capacity of its balancing mode. The default value * is 1, which means the group serves up to 100% of its configured capacity (depending on * balancingMode). A setting of 0 means the group is completely drained, offering 0% of its * available capacity. The valid ranges are 0.0 and [0.1,1.0]. You cannot configure a setting * larger than 0 and smaller than 0.1. You cannot configure a setting of 0 when there is only one * backend attached to the backend service. * @param capacityScaler capacityScaler or {@code null} for none */ public Backend setCapacityScaler(java.lang.Float capacityScaler) { this.capacityScaler = capacityScaler; return this; } /** * An optional description of this resource. Provide this property when you create the resource. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * An optional description of this resource. Provide this property when you create the resource. * @param description description or {@code null} for none */ public Backend setDescription(java.lang.String description) { this.description = description; return this; } /** * This field designates whether this is a failover backend. More than one failover backend can be * configured for a given BackendService. * @return value or {@code null} for none */ public java.lang.Boolean getFailover() { return failover; } /** * This field designates whether this is a failover backend. More than one failover backend can be * configured for a given BackendService. * @param failover failover or {@code null} for none */ public Backend setFailover(java.lang.Boolean failover) { this.failover = failover; return this; } /** * The fully-qualified URL of an instance group or network endpoint group (NEG) resource. To * determine what types of backends a load balancer supports, see the [Backend services * overview](https://cloud.google.com/load-balancing/docs/backend-service#backends). You must use * the *fully-qualified* URL (starting with https://www.googleapis.com/) to specify the instance * group or NEG. Partial URLs are not supported. * @return value or {@code null} for none */ public java.lang.String getGroup() { return group; } /** * The fully-qualified URL of an instance group or network endpoint group (NEG) resource. To * determine what types of backends a load balancer supports, see the [Backend services * overview](https://cloud.google.com/load-balancing/docs/backend-service#backends). You must use * the *fully-qualified* URL (starting with https://www.googleapis.com/) to specify the instance * group or NEG. Partial URLs are not supported. * @param group group or {@code null} for none */ public Backend setGroup(java.lang.String group) { this.group = group; return this; } /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * @return value or {@code null} for none */ public java.lang.Integer getMaxConnections() { return maxConnections; } /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * @param maxConnections maxConnections or {@code null} for none */ public Backend setMaxConnections(java.lang.Integer maxConnections) { this.maxConnections = maxConnections; return this; } /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * @return value or {@code null} for none */ public java.lang.Integer getMaxConnectionsPerEndpoint() { return maxConnectionsPerEndpoint; } /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * @param maxConnectionsPerEndpoint maxConnectionsPerEndpoint or {@code null} for none */ public Backend setMaxConnectionsPerEndpoint(java.lang.Integer maxConnectionsPerEndpoint) { this.maxConnectionsPerEndpoint = maxConnectionsPerEndpoint; return this; } /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * @return value or {@code null} for none */ public java.lang.Integer getMaxConnectionsPerInstance() { return maxConnectionsPerInstance; } /** * Defines a target maximum number of simultaneous connections. For usage guidelines, see * Connection balancing mode and Utilization balancing mode. Not available if the backend's * balancingMode is RATE. * @param maxConnectionsPerInstance maxConnectionsPerInstance or {@code null} for none */ public Backend setMaxConnectionsPerInstance(java.lang.Integer maxConnectionsPerInstance) { this.maxConnectionsPerInstance = maxConnectionsPerInstance; return this; } /** * Defines a maximum number of HTTP requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * @return value or {@code null} for none */ public java.lang.Integer getMaxRate() { return maxRate; } /** * Defines a maximum number of HTTP requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * @param maxRate maxRate or {@code null} for none */ public Backend setMaxRate(java.lang.Integer maxRate) { this.maxRate = maxRate; return this; } /** * Defines a maximum target for requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * @return value or {@code null} for none */ public java.lang.Float getMaxRatePerEndpoint() { return maxRatePerEndpoint; } /** * Defines a maximum target for requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * @param maxRatePerEndpoint maxRatePerEndpoint or {@code null} for none */ public Backend setMaxRatePerEndpoint(java.lang.Float maxRatePerEndpoint) { this.maxRatePerEndpoint = maxRatePerEndpoint; return this; } /** * Defines a maximum target for requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * @return value or {@code null} for none */ public java.lang.Float getMaxRatePerInstance() { return maxRatePerInstance; } /** * Defines a maximum target for requests per second (RPS). For usage guidelines, see Rate * balancing mode and Utilization balancing mode. Not available if the backend's balancingMode is * CONNECTION. * @param maxRatePerInstance maxRatePerInstance or {@code null} for none */ public Backend setMaxRatePerInstance(java.lang.Float maxRatePerInstance) { this.maxRatePerInstance = maxRatePerInstance; return this; } /** * Optional parameter to define a target capacity for the UTILIZATIONbalancing mode. The valid * range is [0.0, 1.0]. For usage guidelines, see Utilization balancing mode. * @return value or {@code null} for none */ public java.lang.Float getMaxUtilization() { return maxUtilization; } /** * Optional parameter to define a target capacity for the UTILIZATIONbalancing mode. The valid * range is [0.0, 1.0]. For usage guidelines, see Utilization balancing mode. * @param maxUtilization maxUtilization or {@code null} for none */ public Backend setMaxUtilization(java.lang.Float maxUtilization) { this.maxUtilization = maxUtilization; return this; } @Override public Backend set(String fieldName, Object value) { return (Backend) super.set(fieldName, value); } @Override public Backend clone() { return (Backend) super.clone(); } }
apache-2.0
freeVM/freeVM
enhanced/java/classlib/modules/security/src/main/java/common/javax/security/cert/X509Certificate.java
13459
/* * 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 javax.security.cert; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Constructor; import java.math.BigInteger; import java.security.AccessController; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Principal; import java.security.PublicKey; import java.security.Security; import java.security.SignatureException; import java.security.cert.CertificateFactory; import java.util.Date; import javax.security.cert.Certificate; import javax.security.cert.CertificateEncodingException; import javax.security.cert.CertificateException; import javax.security.cert.CertificateExpiredException; import javax.security.cert.CertificateNotYetValidException; import org.apache.harmony.security.internal.nls.Messages; /** * Abstract base class for X.509 certificates. * <p> * This represents a standard way for accessing the attributes of X.509 v1 * certificates. * <p> * Note: This package is provided only for compatibility reasons. * It contains a simplified version of the java.security.cert package that was * previously used by JSSE (Java SSL package). All applications that do not have * to be compatible with older versions of JSSE (that is before Java SDK 1.5) * should only use java.security.cert. */ public abstract class X509Certificate extends Certificate { private static Constructor constructor; static { try { String classname = (String) AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { return Security.getProperty("cert.provider.x509v1"); //$NON-NLS-1$ } } ); Class cl = Class.forName(classname); constructor = cl.getConstructor(new Class[] {InputStream.class}); } catch (Throwable e) { } } /** * Creates a new {@code X509Certificate}. */ public X509Certificate() { super(); } /** * Creates a new {@code X509Certificate} and initializes it from the * specified input stream. * * @param inStream * input stream containing data to initialize the certificate. * @return the certificate initialized from the specified input stream * @throws CertificateException * if the certificate cannot be created or initialized. */ public static final X509Certificate getInstance(InputStream inStream) throws CertificateException { if (inStream == null) { throw new CertificateException(Messages.getString("security.87")); //$NON-NLS-1$ } if (constructor != null) { try { return (X509Certificate) constructor.newInstance(new Object[] {inStream}); } catch (Throwable e) { throw new CertificateException(e.getMessage()); } } final java.security.cert.X509Certificate cert; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$ cert = (java.security.cert.X509Certificate) cf.generateCertificate(inStream); } catch (java.security.cert.CertificateException e) { throw new CertificateException(e.getMessage()); } return new X509Certificate() { public byte[] getEncoded() throws CertificateEncodingException { try { return cert.getEncoded(); } catch (java.security.cert.CertificateEncodingException e) { throw new CertificateEncodingException(e.getMessage()); } } public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { try { cert.verify(key); } catch (java.security.cert.CertificateException e) { throw new CertificateException(e.getMessage()); } } public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { try { cert.verify(key, sigProvider); } catch (java.security.cert.CertificateException e) { throw new CertificateException(e.getMessage()); } } public String toString() { return cert.toString(); } public PublicKey getPublicKey() { return cert.getPublicKey(); } public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException { try { cert.checkValidity(); } catch (java.security.cert.CertificateNotYetValidException e) { throw new CertificateNotYetValidException(e.getMessage()); } catch (java.security.cert.CertificateExpiredException e) { throw new CertificateExpiredException(e.getMessage()); } } public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException { try { cert.checkValidity(date); } catch (java.security.cert.CertificateNotYetValidException e) { throw new CertificateNotYetValidException(e.getMessage()); } catch (java.security.cert.CertificateExpiredException e) { throw new CertificateExpiredException(e.getMessage()); } } public int getVersion() { return 2; } public BigInteger getSerialNumber() { return cert.getSerialNumber(); } public Principal getIssuerDN() { return cert.getIssuerDN(); } public Principal getSubjectDN() { return cert.getSubjectDN(); } public Date getNotBefore() { return cert.getNotBefore(); } public Date getNotAfter() { return cert.getNotAfter(); } public String getSigAlgName() { return cert.getSigAlgName(); } public String getSigAlgOID() { return cert.getSigAlgOID(); } public byte[] getSigAlgParams() { return cert.getSigAlgParams(); } }; } /** * Creates a new {@code X509Certificate} and initializes it from the * specified byte array. * * @param certData * byte array containing data to initialize the certificate. * @return the certificate initialized from the specified byte array * @throws CertificateException * if the certificate cannot be created or initialized. */ public static final X509Certificate getInstance(byte[] certData) throws CertificateException { if (certData == null) { throw new CertificateException(Messages.getString("security.88")); //$NON-NLS-1$ } ByteArrayInputStream bais = new ByteArrayInputStream(certData); return getInstance(bais); } /** * Checks whether the certificate is currently valid. * <p> * The validity defined in ASN.1: * * <pre> * validity Validity * * Validity ::= SEQUENCE { * notBefore CertificateValidityDate, * notAfter CertificateValidityDate } * * CertificateValidityDate ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } * </pre> * * @throws CertificateExpiredException * if the certificate has expired. * @throws CertificateNotYetValidException * if the certificate is not yet valid. */ public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException; /** * Checks whether the certificate is valid at the specified date. * * @param date * the date to check the validity against. * @throws CertificateExpiredException * if the certificate has expired. * @throws CertificateNotYetValidException * if the certificate is not yet valid. * @see #checkValidity() */ public abstract void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException; /** * Returns the certificates {@code version} (version number). * <p> * The version defined is ASN.1: * * <pre> * Version ::= INTEGER { v1(0), v2(1), v3(2) } * </pre> * * @return the version number. */ public abstract int getVersion(); /** * Returns the {@code serialNumber} of the certificate. * <p> * The ASN.1 definition of {@code serialNumber}: * * <pre> * CertificateSerialNumber ::= INTEGER * </pre> * * @return the serial number. */ public abstract BigInteger getSerialNumber(); /** * Returns the {@code issuer} (issuer distinguished name) as an * implementation specific {@code Principal} object. * <p> * The ASN.1 definition of {@code issuer}: * * <pre> * issuer Name * * Name ::= CHOICE { * RDNSequence } * * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue } * * AttributeType ::= OBJECT IDENTIFIER * * AttributeValue ::= ANY DEFINED BY AttributeType * </pre> * * @return the {@code issuer} as an implementation specific {@code * Principal}. */ public abstract Principal getIssuerDN(); /** * Returns the {@code subject} (subject distinguished name) as an * implementation specific {@code Principal} object. * <p> * The ASN.1 definition of {@code subject}: * * <pre> * subject Name * * Name ::= CHOICE { * RDNSequence } * * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type AttributeType, * value AttributeValue } * * AttributeType ::= OBJECT IDENTIFIER * * AttributeValue ::= ANY DEFINED BY AttributeType * </pre> * * @return the {@code subject} (subject distinguished name). */ public abstract Principal getSubjectDN(); /** * Returns the {@code notBefore} date from the validity period of the * certificate. * * @return the start of the validity period. */ public abstract Date getNotBefore(); /** * Returns the {@code notAfter} date of the validity period of the * certificate. * * @return the end of the validity period. */ public abstract Date getNotAfter(); /** * Returns the name of the algorithm for the certificate signature. * * @return the signature algorithm name. */ public abstract String getSigAlgName(); /** * Returns the OID of the signature algorithm from the certificate. * * @return the OID of the signature algorithm. */ public abstract String getSigAlgOID(); /** * Returns the parameters of the signature algorithm in DER-encoded format. * * @return the parameters of the signature algorithm, or null if none are * used. */ public abstract byte[] getSigAlgParams(); }
apache-2.0
ecarm002/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-control/hyracks-control-cc/src/main/java/org/apache/hyracks/control/cc/work/GetJobInfoWork.java
1952
/* * 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.hyracks.control.cc.work; import org.apache.hyracks.api.job.JobId; import org.apache.hyracks.api.job.JobInfo; import org.apache.hyracks.control.cc.job.IJobManager; import org.apache.hyracks.control.cc.job.JobRun; import org.apache.hyracks.control.common.work.IResultCallback; import org.apache.hyracks.control.common.work.SynchronizableWork; public class GetJobInfoWork extends SynchronizableWork { private final IJobManager jobManager; private final JobId jobId; private final IResultCallback<JobInfo> callback; public GetJobInfoWork(IJobManager jobManager, JobId jobId, IResultCallback<JobInfo> callback) { this.jobManager = jobManager; this.jobId = jobId; this.callback = callback; } @Override protected void doRun() throws Exception { try { JobRun run = jobManager.get(jobId); JobInfo info = (run != null) ? new JobInfo(run.getJobId(), run.getStatus(), run.getOperatorLocations()) : null; callback.setValue(info); } catch (Exception e) { callback.setException(e); } } }
apache-2.0
radicalbit/ambari
ambari-server/src/test/java/org/apache/ambari/server/stack/ComponentModuleTest.java
26448
/* * 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.ambari.server.stack; import static org.easymock.EasyMock.createNiceMock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.ambari.server.state.AutoDeployInfo; import org.apache.ambari.server.state.BulkCommandDefinition; import org.apache.ambari.server.state.ClientConfigFileDefinition; import org.apache.ambari.server.state.CommandScriptDefinition; import org.apache.ambari.server.state.ComponentInfo; import org.apache.ambari.server.state.CustomCommandDefinition; import org.apache.ambari.server.state.DependencyInfo; import org.apache.ambari.server.state.UnlimitedKeyJCERequirement; import org.junit.Test; /** * ComponentModule unit test case. */ public class ComponentModuleTest { @Test public void testResolve_CommandScript() { CommandScriptDefinition commandScript = new CommandScriptDefinition(); ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setCommandScript(commandScript); assertSame(commandScript, resolveComponent(info, parentInfo).getModuleInfo().getCommandScript()); // child has value set, parent value is null info.setCommandScript(commandScript); parentInfo.setCommandScript(null); assertSame(commandScript, resolveComponent(info, parentInfo).getModuleInfo().getCommandScript()); // value set in both parent and child; child overwrites CommandScriptDefinition commandScript2 = createNiceMock(CommandScriptDefinition.class); info.setCommandScript(commandScript); parentInfo.setCommandScript(commandScript2); assertSame(commandScript, resolveComponent(info, parentInfo).getModuleInfo().getCommandScript()); } @Test public void testResolve_DisplayName() { String displayName = "foo"; ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setDisplayName(displayName); assertEquals(displayName, resolveComponent(info, parentInfo).getModuleInfo().getDisplayName()); // child has value set, parent value is null info.setDisplayName(displayName); parentInfo.setDisplayName(null); assertEquals(displayName, resolveComponent(info, parentInfo).getModuleInfo().getDisplayName()); // value set in both parent and child; child overwrites String displayName2 = "foo2"; info.setDisplayName(displayName2); parentInfo.setDisplayName(displayName); assertEquals(displayName2, resolveComponent(info, parentInfo).getModuleInfo().getDisplayName()); } @Test public void testResolve_ClientConfigFiles() { List<ClientConfigFileDefinition> clientConfigs = new ArrayList<>(); ClientConfigFileDefinition clientConfig1 = new ClientConfigFileDefinition(); clientConfig1.setType("type1"); clientConfig1.setDictionaryName("dictName1"); clientConfig1.setFileName("filename1"); ClientConfigFileDefinition clientConfig2 = new ClientConfigFileDefinition(); clientConfig1.setType("type1"); clientConfig1.setDictionaryName("dictName1"); clientConfig1.setFileName("filename1"); clientConfigs.add(clientConfig1); clientConfigs.add(clientConfig2); ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setClientConfigFiles(clientConfigs); assertEquals(clientConfigs, resolveComponent(info, parentInfo).getModuleInfo().getClientConfigFiles()); // child has value set, parent value is null info.setClientConfigFiles(clientConfigs); parentInfo.setClientConfigFiles(null); assertEquals(clientConfigs, resolveComponent(info, parentInfo).getModuleInfo().getClientConfigFiles()); // value set in both parent and child; child overwrites with no merge List<ClientConfigFileDefinition> clientConfigs2 = new ArrayList<>(); ClientConfigFileDefinition clientConfig3 = new ClientConfigFileDefinition(); clientConfig3.setType("type1"); clientConfig3.setDictionaryName("dictName1"); clientConfig3.setFileName("DIFFERENT filename"); clientConfigs2.add(clientConfig3); info.setClientConfigFiles(clientConfigs2); parentInfo.setClientConfigFiles(clientConfigs); assertEquals(clientConfigs2, resolveComponent(info, parentInfo).getModuleInfo().getClientConfigFiles()); } @Test public void testResolve_Category() { String category = "foo"; ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setCategory(category); assertEquals(category, resolveComponent(info, parentInfo).getModuleInfo().getCategory()); // child has value set, parent value is null info.setCategory(category); parentInfo.setCategory(null); assertEquals(category, resolveComponent(info, parentInfo).getModuleInfo().getCategory()); // value set in both parent and child; child overwrites String category2 = "foo2"; info.setCategory(category2); parentInfo.setCategory(category); assertEquals(category2, resolveComponent(info, parentInfo).getModuleInfo().getCategory()); } @Test public void testResolve_Cardinality() { String cardinality = "foo"; ComponentInfo info = new ComponentInfo(); // parent is null, child cardinality is null assertEquals("0+", resolveComponent(info, null).getModuleInfo().getCardinality()); ComponentInfo parentInfo = new ComponentInfo(); info = new ComponentInfo(); // parent has value set, child value is null parentInfo.setCardinality(cardinality); assertEquals("foo", resolveComponent(info, parentInfo).getModuleInfo().getCardinality()); // child has value set, parent value is null info.setCardinality(cardinality); parentInfo.setCardinality(null); assertEquals(cardinality, resolveComponent(info, parentInfo).getModuleInfo().getCardinality()); // value set in both parent and child; child overwrites String cardinality2 = "foo2"; info.setCardinality(cardinality2); parentInfo.setCardinality(cardinality); assertEquals(cardinality2, resolveComponent(info, parentInfo).getModuleInfo().getCardinality()); } @Test public void testResolve_TimelineAppId() { String timelineAppId = "app"; ComponentInfo info = new ComponentInfo(); assertEquals(null, resolveComponent(info, null).getModuleInfo().getTimelineAppid()); ComponentInfo parentInfo = new ComponentInfo(); info = new ComponentInfo(); // parent has value set, child value is null parentInfo.setTimelineAppid(timelineAppId); assertEquals(timelineAppId, resolveComponent(info, parentInfo).getModuleInfo().getTimelineAppid()); // child has value set, parent value is null info.setTimelineAppid(timelineAppId); parentInfo.setTimelineAppid(null); assertEquals(timelineAppId, resolveComponent(info, parentInfo).getModuleInfo().getTimelineAppid()); // value set in both parent and child; child overwrites String timelineAppId2 = "app2"; info.setTimelineAppid(timelineAppId2); parentInfo.setTimelineAppid(timelineAppId); assertEquals(timelineAppId2, resolveComponent(info, parentInfo).getModuleInfo().getTimelineAppid()); } @Test public void testResolve_AutoDeploy() { AutoDeployInfo autoDeployInfo = new AutoDeployInfo(); autoDeployInfo.setEnabled(true); autoDeployInfo.setCoLocate("foo/bar"); ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setAutoDeploy(autoDeployInfo); assertEquals(autoDeployInfo, resolveComponent(info, parentInfo).getModuleInfo().getAutoDeploy()); // child has value set, parent value is null info.setAutoDeploy(autoDeployInfo); parentInfo.setAutoDeploy(null); assertEquals(autoDeployInfo, resolveComponent(info, parentInfo).getModuleInfo().getAutoDeploy()); // value set in both parent and child; child overwrites AutoDeployInfo autoDeployInfo2 = new AutoDeployInfo(); info.setAutoDeploy(autoDeployInfo); parentInfo.setAutoDeploy(autoDeployInfo2); assertEquals(autoDeployInfo, resolveComponent(info, parentInfo).getModuleInfo().getAutoDeploy()); } @Test public void testResolve_Dependencies() { List<DependencyInfo> dependencies = new ArrayList<>(); DependencyInfo dependency1 = new DependencyInfo(); dependency1.setName("service/one"); DependencyInfo dependency2 = new DependencyInfo(); dependency2.setName("service/two"); dependencies.add(dependency1); dependencies.add(dependency2); ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setDependencies(dependencies); assertEquals(dependencies, resolveComponent(info, parentInfo).getModuleInfo().getDependencies()); // child has value set, parent value is null info.setDependencies(dependencies); parentInfo.setDependencies(null); assertEquals(dependencies, resolveComponent(info, parentInfo).getModuleInfo().getDependencies()); // value set in both parent and child; merge parent and child //todo: currently there is no way to remove an inherited dependency List<DependencyInfo> dependencies2 = new ArrayList<>(); DependencyInfo dependency3 = new DependencyInfo(); dependency3.setName("service/two"); DependencyInfo dependency4 = new DependencyInfo(); dependency4.setName("service/four"); dependencies2.add(dependency3); dependencies2.add(dependency4); info.setDependencies(dependencies2); parentInfo.setDependencies(dependencies); List<DependencyInfo> resolvedDependencies = resolveComponent(info, parentInfo).getModuleInfo().getDependencies(); assertEquals(3, resolvedDependencies.size()); assertTrue(resolvedDependencies.contains(dependency1)); assertTrue(resolvedDependencies.contains(dependency3)); assertTrue(resolvedDependencies.contains(dependency4)); } @Test public void testResolve_CustomCommands() throws Exception { List<CustomCommandDefinition> commands = new ArrayList<>(); CustomCommandDefinition command1 = new CustomCommandDefinition(); setPrivateField(command1, "name", "one"); CustomCommandDefinition command2 = new CustomCommandDefinition(); setPrivateField(command2, "name", "two"); commands.add(command1); commands.add(command2); ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setCustomCommands(commands); assertEquals(commands, resolveComponent(info, parentInfo).getModuleInfo().getCustomCommands()); // child has value set, parent value is null info.setCustomCommands(commands); parentInfo.setCustomCommands(null); assertEquals(commands, resolveComponent(info, parentInfo).getModuleInfo().getCustomCommands()); // value set in both parent and child; merge parent and child //todo: currently there is no way to remove an inherited command List<CustomCommandDefinition> commands2 = new ArrayList<>(); CustomCommandDefinition command3 = new CustomCommandDefinition(); // override command 2 setPrivateField(command3, "name", "two"); CustomCommandDefinition command4 = new CustomCommandDefinition(); setPrivateField(command4, "name", "four"); commands2.add(command3); commands2.add(command4); info.setCustomCommands(commands2); parentInfo.setCustomCommands(commands); List<CustomCommandDefinition> resolvedCommands = resolveComponent(info, parentInfo).getModuleInfo().getCustomCommands(); assertEquals(3, resolvedCommands.size()); assertTrue(resolvedCommands.contains(command1)); assertTrue(resolvedCommands.contains(command3)); assertTrue(resolvedCommands.contains(command4)); } @Test // merging of config dependencies is different than other non-module merges in that the collections aren't // merged if any config dependency is specified in the child. So, the merged result is either the child // dependencies or if null, the parent dependencies. public void testResolve_ConfigDependencies() { List<String> dependencies = new ArrayList<>(); String dependency1 = "one"; String dependency2 = "two"; dependencies.add(dependency1); dependencies.add(dependency2); ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setConfigDependencies(dependencies); assertEquals(dependencies, resolveComponent(info, parentInfo).getModuleInfo().getConfigDependencies()); // child has value set, parent value is null info.setConfigDependencies(dependencies); parentInfo.setConfigDependencies(null); assertEquals(dependencies, resolveComponent(info, parentInfo).getModuleInfo().getConfigDependencies()); // value set in both parent and child; merge parent and child List<String> dependencies2 = new ArrayList<>(); String dependency3 = "two"; String dependency4 = "four"; dependencies2.add(dependency3); dependencies2.add(dependency4); info.setConfigDependencies(dependencies2); parentInfo.setConfigDependencies(dependencies); List<String> resolvedDependencies = resolveComponent(info, parentInfo).getModuleInfo().getConfigDependencies(); assertEquals(2, resolvedDependencies.size()); assertTrue(resolvedDependencies.contains(dependency3)); assertTrue(resolvedDependencies.contains(dependency4)); } @Test // merging of "client to update configs", whatever that means, is different than most other non-module merges // in that the collections aren't merged if any "client to update configs" is specified in the child. // So, the merged result is either the child collection or if null, the parent collection. public void testResolve_ClientToUpdateConfigs() { List<String> clientsToUpdate = new ArrayList<>(); String client1 = "one"; String client2 = "two"; clientsToUpdate.add(client1); clientsToUpdate.add(client2); ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setClientsToUpdateConfigs(clientsToUpdate); assertEquals(clientsToUpdate, resolveComponent(info, parentInfo).getModuleInfo().getClientsToUpdateConfigs()); // child has value set, parent value is null info.setClientsToUpdateConfigs(clientsToUpdate); parentInfo.setClientsToUpdateConfigs(null); assertEquals(clientsToUpdate, resolveComponent(info, parentInfo).getModuleInfo().getClientsToUpdateConfigs()); // value set in both parent and child; merge parent and child List<String> clientsToUpdate2 = new ArrayList<>(); String client3 = "two"; String client4 = "four"; clientsToUpdate2.add(client3); clientsToUpdate2.add(client4); info.setClientsToUpdateConfigs(clientsToUpdate2); parentInfo.setClientsToUpdateConfigs(clientsToUpdate); List<String> resolvedClientsToUpdate = resolveComponent(info, parentInfo).getModuleInfo().getClientsToUpdateConfigs(); assertEquals(2, resolvedClientsToUpdate.size()); assertTrue(resolvedClientsToUpdate.contains(client3)); assertTrue(resolvedClientsToUpdate.contains(client4)); } @Test public void testGetId() { ComponentInfo info = new ComponentInfo(); info.setName("foo"); ComponentModule component = new ComponentModule(info); assertEquals("foo", component.getId()); } @Test public void testIsDeleted() { // default value ComponentInfo info = new ComponentInfo(); info.setName("foo"); ComponentModule component = new ComponentModule(info); assertFalse(component.isDeleted()); // explicit value info = new ComponentInfo(); info.setName("foo"); info.setDeleted(true); component = new ComponentModule(info); assertTrue(component.isDeleted()); } @Test public void testResolve_BulkCommandsDefinition(){ BulkCommandDefinition bulkCommandsDefinition = new BulkCommandDefinition(); ComponentInfo info = new ComponentInfo(); ComponentInfo parentInfo = new ComponentInfo(); // parent has value set, child value is null parentInfo.setBulkCommands(bulkCommandsDefinition); assertSame(bulkCommandsDefinition, resolveComponent(info, parentInfo).getModuleInfo().getBulkCommandDefinition()); // child has value set, parent value is null info.setBulkCommands(bulkCommandsDefinition); parentInfo.setBulkCommands(null); assertSame(bulkCommandsDefinition, resolveComponent(info, parentInfo).getModuleInfo().getBulkCommandDefinition()); // value set in both parent and child; child overwrites BulkCommandDefinition bulkCommandsDefinition2 = createNiceMock(BulkCommandDefinition.class); info.setBulkCommands(bulkCommandsDefinition); parentInfo.setBulkCommands(bulkCommandsDefinition2); assertSame(bulkCommandsDefinition, resolveComponent(info, parentInfo).getModuleInfo().getBulkCommandDefinition()); } @Test public void testResolve_DecommissionAllowedInheritance(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent has it, child doesn't parentInfo.setDecommissionAllowed("true"); assertSame("true", resolveComponent(info, parentInfo).getModuleInfo().getDecommissionAllowed()); } @Test public void testResolve_DecommissionAllowed(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent doesn't have it, child has it info.setDecommissionAllowed("false"); assertSame("false", resolveComponent(info, parentInfo).getModuleInfo().getDecommissionAllowed()); } @Test public void testResolve_DecommissionAllowedOverwrite(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent has it, child overwrites it parentInfo.setDecommissionAllowed("false"); info.setDecommissionAllowed("true"); assertSame("true", resolveComponent(info, parentInfo).getModuleInfo().getDecommissionAllowed()); } @Test public void testResolve_UnlimitedKeyJCERequiredInheritance(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent has it, child doesn't parentInfo.setUnlimitedKeyJCERequired(UnlimitedKeyJCERequirement.ALWAYS); assertSame(UnlimitedKeyJCERequirement.ALWAYS, resolveComponent(info, parentInfo).getModuleInfo().getUnlimitedKeyJCERequired()); } @Test public void testResolve_UnlimitedKeyJCERequired(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent doesn't have it, child has it info.setUnlimitedKeyJCERequired(UnlimitedKeyJCERequirement.NEVER); assertSame(UnlimitedKeyJCERequirement.NEVER, resolveComponent(info, parentInfo).getModuleInfo().getUnlimitedKeyJCERequired()); } @Test public void testResolve_UnlimitedKeyJCERequiredOverwrite(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent has it, child overwrites it parentInfo.setUnlimitedKeyJCERequired(UnlimitedKeyJCERequirement.KERBEROS_ENABLED); info.setUnlimitedKeyJCERequired(UnlimitedKeyJCERequirement.ALWAYS); assertSame(UnlimitedKeyJCERequirement.ALWAYS, resolveComponent(info, parentInfo).getModuleInfo().getUnlimitedKeyJCERequired()); } @Test public void testResolve_Reassignable(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent doesn't have it, child has it info.setReassignAllowed("false"); assertSame("false", resolveComponent(info, parentInfo).getModuleInfo().getReassignAllowed()); } @Test public void testResolve_ReassignableInheritance(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent has it, child doesn't parentInfo.setReassignAllowed("true"); assertSame("true", resolveComponent(info, parentInfo).getModuleInfo().getReassignAllowed()); } @Test public void testResolve_ReassignableOverwrite(){ List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); //parent has it, child overwrites it parentInfo.setReassignAllowed("false"); info.setReassignAllowed("true"); assertSame("true", resolveComponent(info, parentInfo).getModuleInfo().getReassignAllowed()); } /** * Test that versionAdvertised is resolved correctly. */ @Test public void testResolve_VersionAdvertised() { List<ComponentInfo> components = createComponentInfo(2); ComponentInfo info = components.get(0); ComponentInfo parentInfo = components.get(1); // Test cases where the current Component Info explicitly sets the value. // 1. Chain of versionAdvertised is: true (parent) -> true (current) => true parentInfo.setVersionAdvertisedField(new Boolean(true)); parentInfo.setVersionAdvertised(true); info.setVersionAdvertisedField(new Boolean(true)); assertEquals(true, resolveComponent(info, parentInfo).getModuleInfo().isVersionAdvertised()); // 2. Chain of versionAdvertised is: true (parent) -> false (current) => false parentInfo.setVersionAdvertisedField(new Boolean(true)); parentInfo.setVersionAdvertised(true); info.setVersionAdvertisedField(new Boolean(false)); assertEquals(false, resolveComponent(info, parentInfo).getModuleInfo().isVersionAdvertised()); // 3. Chain of versionAdvertised is: false (parent) -> true (current) => true parentInfo.setVersionAdvertisedField(new Boolean(false)); parentInfo.setVersionAdvertised(false); info.setVersionAdvertisedField(new Boolean(true)); assertEquals(true, resolveComponent(info, parentInfo).getModuleInfo().isVersionAdvertised()); // 4. Chain of versionAdvertised is: null (parent) -> true (current) => true parentInfo.setVersionAdvertisedField(null); parentInfo.setVersionAdvertised(false); info.setVersionAdvertisedField(new Boolean(true)); assertEquals(true, resolveComponent(info, parentInfo).getModuleInfo().isVersionAdvertised()); // Test cases where current Component Info is null so it should inherit from parent. // 5. Chain of versionAdvertised is: true (parent) -> null (current) => true parentInfo.setVersionAdvertisedField(new Boolean(true)); parentInfo.setVersionAdvertised(true); info.setVersionAdvertisedField(null); assertEquals(true, resolveComponent(info, parentInfo).getModuleInfo().isVersionAdvertised()); // 6. Chain of versionAdvertised is: true (parent) -> inherit (current) => true parentInfo.setVersionAdvertisedField(new Boolean(true)); parentInfo.setVersionAdvertised(true); info.setVersionAdvertisedField(null); assertEquals(true, resolveComponent(info, parentInfo).getModuleInfo().isVersionAdvertised()); // 7. Chain of versionAdvertised is: false (parent) -> null (current) => false parentInfo.setVersionAdvertisedField(new Boolean(false)); parentInfo.setVersionAdvertised(false); info.setVersionAdvertisedField(null); assertEquals(false, resolveComponent(info, parentInfo).getModuleInfo().isVersionAdvertised()); // 8. Chain of versionAdvertised is: false (parent) -> inherit (current) => false parentInfo.setVersionAdvertisedField(new Boolean(false)); parentInfo.setVersionAdvertised(false); info.setVersionAdvertisedField(null); assertEquals(false, resolveComponent(info, parentInfo).getModuleInfo().isVersionAdvertised()); } private List<ComponentInfo> createComponentInfo(int count){ List<ComponentInfo> result = new ArrayList<>(); if(count > 0) { for(int i = 0; i < count; i++){ result.add(new ComponentInfo()); } } return result; } private ComponentModule resolveComponent(ComponentInfo info, ComponentInfo parentInfo) { info.setName("FOO"); ComponentModule component = new ComponentModule(info); ComponentModule parentComponent = null; if (parentInfo != null) { parentInfo.setName("FOO"); parentComponent = new ComponentModule(parentInfo); } component.resolve(parentComponent, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap()); return component; } private void setPrivateField(Object o, String field, Object value) throws Exception{ Class<?> c = o.getClass(); Field f = c.getDeclaredField(field); f.setAccessible(true); f.set(o, value); } }
apache-2.0
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/mam/element/MamV1ElementFactory.java
2383
/** * * Copyright © 2016-2021 Florian Schmaus and Frank Matheron * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smackx.mam.element; import java.util.List; import javax.xml.namespace.QName; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smackx.forward.packet.Forwarded; import org.jivesoftware.smackx.rsm.packet.RSMSet; import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jxmpp.jid.Jid; class MamV1ElementFactory implements MamElementFactory { @Override public MamElements.MamResultExtension newResultExtension(String queryId, String id, Forwarded<Message> forwarded) { return new MamV1ResultExtension(queryId, id, forwarded); } @Override public MamFinIQ newFinIQ(String queryId, RSMSet rsmSet, boolean complete, boolean stable) { return new MamFinIQ(MamVersion.MAM1, queryId, rsmSet, complete, stable); } @Override public MamPrefsIQ newPrefsIQ(List<Jid> alwaysJids, List<Jid> neverJids, MamPrefsIQ.DefaultBehavior defaultBehavior) { return new MamPrefsIQ(MamVersion.MAM1, alwaysJids, neverJids, defaultBehavior); } @Override public MamPrefsIQ newPrefsIQ() { return new MamPrefsIQ(MamVersion.MAM1); } @Override public MamQueryIQ newQueryIQ(String queryId, String node, DataForm dataForm) { return new MamQueryIQ(MamVersion.MAM1, queryId, node, dataForm); } public static class MamV1ResultExtension extends MamElements.MamResultExtension { /** * The qualified name of the MAM result extension element. */ public static final QName QNAME = new QName(MamVersion.MAM1.getNamespace(), ELEMENT); MamV1ResultExtension(String queryId, String id, Forwarded<Message> forwarded) { super(MamVersion.MAM1, queryId, id, forwarded); } } }
apache-2.0
salyh/javamailspec
geronimo-j2ee-management_1.1_spec/src/main/java/javax/management/j2ee/statistics/BoundedRangeStatistic.java
1163
/* * 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 source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.management.j2ee.statistics; /** * @version $Rev$ */ public interface BoundedRangeStatistic extends BoundaryStatistic, RangeStatistic { }
apache-2.0
ultratendency/hbase
hbase-mapreduce/src/test/java/org/apache/hadoop/hbase/mapreduce/TestHRegionPartitioner.java
2887
/** * 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.hadoop.hbase.mapreduce; import static org.junit.Assert.assertEquals; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.testclassification.MapReduceTests; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.util.Bytes; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; @Category({MapReduceTests.class, MediumTests.class}) public class TestHRegionPartitioner { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestHRegionPartitioner.class); private static final HBaseTestingUtility UTIL = new HBaseTestingUtility(); @Rule public TestName name = new TestName(); @BeforeClass public static void beforeClass() throws Exception { UTIL.startMiniCluster(); } @AfterClass public static void afterClass() throws Exception { UTIL.shutdownMiniCluster(); } /** * Test HRegionPartitioner */ @Test public void testHRegionPartitioner() throws Exception { byte[][] families = { Bytes.toBytes("familyA"), Bytes.toBytes("familyB") }; UTIL.createTable(TableName.valueOf(name.getMethodName()), families, 1, Bytes.toBytes("aa"), Bytes.toBytes("cc"), 3); HRegionPartitioner<Long, Long> partitioner = new HRegionPartitioner<>(); Configuration configuration = UTIL.getConfiguration(); configuration.set(TableOutputFormat.OUTPUT_TABLE, name.getMethodName()); partitioner.setConf(configuration); ImmutableBytesWritable writable = new ImmutableBytesWritable(Bytes.toBytes("bb")); assertEquals(1, partitioner.getPartition(writable, 10L, 3)); assertEquals(0, partitioner.getPartition(writable, 10L, 1)); } }
apache-2.0
ErinJoan/mostly_empty_directory
appengine/datastore/src/main/java/com/example/time/Clock.java
1278
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.time; import org.joda.time.Instant; /** * Provides the current value of "now." To preserve testability, avoid all other libraries that * access the system clock (whether {@linkplain System#currentTimeMillis directly} or {@linkplain * org.joda.time.DateTime#DateTime() indirectly}). * * <p>In production, use the {@link SystemClock} implementation to return the "real" system time. In * tests, either use {@link com.example.time.testing.FakeClock}, or get an instance from a mocking * framework such as Mockito. */ public interface Clock { /** * Returns the current, absolute time according to this clock. */ Instant now(); }
apache-2.0
shuliangtao/apache-camel-2.13.0-src
camel-core/src/test/java/org/apache/camel/processor/DelayerTest.java
4027
/** * 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.camel.processor; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import static org.apache.camel.processor.ExchangeAwareDelayCalcBean.BEAN_DELAYER_HEADER; /** * @version */ public class DelayerTest extends ContextTestSupport { private MyDelayCalcBean bean = new MyDelayCalcBean(); private ExchangeAwareDelayCalcBean exchangeAwareBean = new ExchangeAwareDelayCalcBean(); public void testSendingMessageGetsDelayed() throws Exception { MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); // do not wait for the first message resultEndpoint.expectedMessageCount(0); resultEndpoint.setResultWaitTime(500); template.sendBodyAndHeader("seda:a", "<hello>world!</hello>", "MyDelay", 1000); // we should not receive it as we wait at most 0.5 sec and it take 1 sec to send resultEndpoint.assertIsSatisfied(); // now if we wait a bit longer we should receive the message! resultEndpoint.reset(); resultEndpoint.expectedMessageCount(1); resultEndpoint.assertIsSatisfied(); } public void testDelayConstant() throws Exception { MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); resultEndpoint.expectedMessageCount(1); // should at least take 1 sec to complete resultEndpoint.setMinimumResultWaitTime(900); template.sendBody("seda:b", "<hello>world!</hello>"); resultEndpoint.assertIsSatisfied(); } public void testDelayBean() throws Exception { MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); resultEndpoint.expectedMessageCount(1); // should at least take 1 sec to complete resultEndpoint.setMinimumResultWaitTime(900); template.sendBody("seda:c", "<hello>world!</hello>"); resultEndpoint.assertIsSatisfied(); } public void testExchangeAwareDelayBean() throws Exception { MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); resultEndpoint.expectedMessageCount(1); // should at least take 1 sec to complete resultEndpoint.setMinimumResultWaitTime(900); template.sendBodyAndHeader("seda:d", "<hello>world!</hello>", BEAN_DELAYER_HEADER, 1000); resultEndpoint.assertIsSatisfied(); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: ex from("seda:a").delay().header("MyDelay").to("mock:result"); // END SNIPPET: ex // START SNIPPET: ex2 from("seda:b").delay(1000).to("mock:result"); // END SNIPPET: ex2 // START SNIPPET: ex3 from("seda:c").delay().method(bean, "delayMe").to("mock:result"); // END SNIPPET: ex3 from("seda:d").delay().method(exchangeAwareBean, "delayMe").to("mock:result"); } }; } }
apache-2.0
DavesMan/guava
guava/src/com/google/common/util/concurrent/AtomicDouble.java
7813
/* * Written by Doug Lea and Martin Buchholz with assistance from * members of JCP JSR-166 Expert Group and released to the public * domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ /* * Source: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/extra/AtomicDouble.java?revision=1.13 * (Modified to adapt to guava coding conventions and * to use AtomicLongFieldUpdater instead of sun.misc.Unsafe) */ package com.google.common.util.concurrent; import static java.lang.Double.doubleToRawLongBits; import static java.lang.Double.longBitsToDouble; import com.google.common.annotations.GwtIncompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.concurrent.atomic.AtomicLongFieldUpdater; /** * A {@code double} value that may be updated atomically. See the {@link * java.util.concurrent.atomic} package specification for description of the properties of atomic * variables. An {@code AtomicDouble} is used in applications such as atomic accumulation, and * cannot be used as a replacement for a {@link Double}. However, this class does extend {@code * Number} to allow uniform access by tools and utilities that deal with numerically-based classes. * * <p><a name="bitEquals"></a>This class compares primitive {@code double} values in methods such as * {@link #compareAndSet} by comparing their bitwise representation using {@link * Double#doubleToRawLongBits}, which differs from both the primitive double {@code ==} operator and * from {@link Double#equals}, as if implemented by: * * <pre>{@code * static boolean bitEquals(double x, double y) { * long xBits = Double.doubleToRawLongBits(x); * long yBits = Double.doubleToRawLongBits(y); * return xBits == yBits; * } * }</pre> * * <p>It is possible to write a more scalable updater, at the cost of giving up strict atomicity. * See for example <a * href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleAdder.html"> * DoubleAdder</a> and <a * href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleMaxUpdater.html"> * DoubleMaxUpdater</a>. * * @author Doug Lea * @author Martin Buchholz * @since 11.0 */ @GwtIncompatible public class AtomicDouble extends Number implements java.io.Serializable { private static final long serialVersionUID = 0L; private transient volatile long value; private static final AtomicLongFieldUpdater<AtomicDouble> updater = AtomicLongFieldUpdater.newUpdater(AtomicDouble.class, "value"); /** * Creates a new {@code AtomicDouble} with the given initial value. * * @param initialValue the initial value */ public AtomicDouble(double initialValue) { value = doubleToRawLongBits(initialValue); } /** * Creates a new {@code AtomicDouble} with initial value {@code 0.0}. */ public AtomicDouble() { // assert doubleToRawLongBits(0.0) == 0L; } /** * Gets the current value. * * @return the current value */ public final double get() { return longBitsToDouble(value); } /** * Sets to the given value. * * @param newValue the new value */ public final void set(double newValue) { long next = doubleToRawLongBits(newValue); value = next; } /** * Eventually sets to the given value. * * @param newValue the new value */ public final void lazySet(double newValue) { set(newValue); // TODO(user): replace with code below when jdk5 support is dropped. // long next = doubleToRawLongBits(newValue); // updater.lazySet(this, next); } /** * Atomically sets to the given value and returns the old value. * * @param newValue the new value * @return the previous value */ public final double getAndSet(double newValue) { long next = doubleToRawLongBits(newValue); return longBitsToDouble(updater.getAndSet(this, next)); } /** * Atomically sets the value to the given updated value * if the current value is <a href="#bitEquals">bitwise equal</a> * to the expected value. * * @param expect the expected value * @param update the new value * @return {@code true} if successful. False return indicates that * the actual value was not bitwise equal to the expected value. */ public final boolean compareAndSet(double expect, double update) { return updater.compareAndSet(this, doubleToRawLongBits(expect), doubleToRawLongBits(update)); } /** * Atomically sets the value to the given updated value * if the current value is <a href="#bitEquals">bitwise equal</a> * to the expected value. * * <p>May <a * href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious"> * fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * * @param expect the expected value * @param update the new value * @return {@code true} if successful */ public final boolean weakCompareAndSet(double expect, double update) { return updater.weakCompareAndSet(this, doubleToRawLongBits(expect), doubleToRawLongBits(update)); } /** * Atomically adds the given value to the current value. * * @param delta the value to add * @return the previous value */ @CanIgnoreReturnValue public final double getAndAdd(double delta) { while (true) { long current = value; double currentVal = longBitsToDouble(current); double nextVal = currentVal + delta; long next = doubleToRawLongBits(nextVal); if (updater.compareAndSet(this, current, next)) { return currentVal; } } } /** * Atomically adds the given value to the current value. * * @param delta the value to add * @return the updated value */ @CanIgnoreReturnValue public final double addAndGet(double delta) { while (true) { long current = value; double currentVal = longBitsToDouble(current); double nextVal = currentVal + delta; long next = doubleToRawLongBits(nextVal); if (updater.compareAndSet(this, current, next)) { return nextVal; } } } /** * Returns the String representation of the current value. * @return the String representation of the current value */ public String toString() { return Double.toString(get()); } /** * Returns the value of this {@code AtomicDouble} as an {@code int} * after a narrowing primitive conversion. */ public int intValue() { return (int) get(); } /** * Returns the value of this {@code AtomicDouble} as a {@code long} * after a narrowing primitive conversion. */ public long longValue() { return (long) get(); } /** * Returns the value of this {@code AtomicDouble} as a {@code float} * after a narrowing primitive conversion. */ public float floatValue() { return (float) get(); } /** * Returns the value of this {@code AtomicDouble} as a {@code double}. */ public double doubleValue() { return get(); } /** * Saves the state to a stream (that is, serializes it). * * @serialData The current value is emitted (a {@code double}). */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); s.writeDouble(get()); } /** * Reconstitutes the instance from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); set(s.readDouble()); } }
apache-2.0
jasonstack/cassandra
src/java/org/apache/cassandra/metrics/KeyspaceMetrics.java
19056
/* * 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.cassandra.metrics; import java.util.Set; import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.Histogram; import com.codahale.metrics.Meter; import com.codahale.metrics.Timer; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.Keyspace; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import static org.apache.cassandra.metrics.CassandraMetricsRegistry.Metrics; /** * Metrics for {@link ColumnFamilyStore}. */ public class KeyspaceMetrics { /** Total amount of live data stored in the memtable, excluding any data structure overhead */ public final Gauge<Long> memtableLiveDataSize; /** Total amount of data stored in the memtable that resides on-heap, including column related overhead and partitions overwritten. */ public final Gauge<Long> memtableOnHeapDataSize; /** Total amount of data stored in the memtable that resides off-heap, including column related overhead and partitions overwritten. */ public final Gauge<Long> memtableOffHeapDataSize; /** Total amount of live data stored in the memtables (2i and pending flush memtables included) that resides off-heap, excluding any data structure overhead */ public final Gauge<Long> allMemtablesLiveDataSize; /** Total amount of data stored in the memtables (2i and pending flush memtables included) that resides on-heap. */ public final Gauge<Long> allMemtablesOnHeapDataSize; /** Total amount of data stored in the memtables (2i and pending flush memtables included) that resides off-heap. */ public final Gauge<Long> allMemtablesOffHeapDataSize; /** Total number of columns present in the memtable. */ public final Gauge<Long> memtableColumnsCount; /** Number of times flush has resulted in the memtable being switched out. */ public final Gauge<Long> memtableSwitchCount; /** Estimated number of tasks pending for this column family */ public final Gauge<Long> pendingFlushes; /** Estimate of number of pending compactios for this CF */ public final Gauge<Long> pendingCompactions; /** Disk space used by SSTables belonging to this CF */ public final Gauge<Long> liveDiskSpaceUsed; /** Total disk space used by SSTables belonging to this CF, including obsolete ones waiting to be GC'd */ public final Gauge<Long> totalDiskSpaceUsed; /** Disk space used by bloom filter */ public final Gauge<Long> bloomFilterDiskSpaceUsed; /** Off heap memory used by bloom filter */ public final Gauge<Long> bloomFilterOffHeapMemoryUsed; /** Off heap memory used by index summary */ public final Gauge<Long> indexSummaryOffHeapMemoryUsed; /** Off heap memory used by compression meta data*/ public final Gauge<Long> compressionMetadataOffHeapMemoryUsed; /** (Local) read metrics */ public final LatencyMetrics readLatency; /** (Local) range slice metrics */ public final LatencyMetrics rangeLatency; /** (Local) write metrics */ public final LatencyMetrics writeLatency; /** Histogram of the number of sstable data files accessed per read */ public final Histogram sstablesPerReadHistogram; /** Tombstones scanned in queries on this Keyspace */ public final Histogram tombstoneScannedHistogram; /** Live cells scanned in queries on this Keyspace */ public final Histogram liveScannedHistogram; /** Column update time delta on this Keyspace */ public final Histogram colUpdateTimeDeltaHistogram; /** time taken acquiring the partition lock for materialized view updates on this keyspace */ public final Timer viewLockAcquireTime; /** time taken during the local read of a materialized view update */ public final Timer viewReadTime; /** CAS Prepare metric */ public final LatencyMetrics casPrepare; /** CAS Propose metrics */ public final LatencyMetrics casPropose; /** CAS Commit metrics */ public final LatencyMetrics casCommit; /** Writes failed ideal consistency **/ public final Counter writeFailedIdealCL; /** Ideal CL write latency metrics */ public final LatencyMetrics idealCLWriteLatency; /** Speculative retries **/ public final Counter speculativeRetries; /** Speculative retry occured but still timed out **/ public final Counter speculativeFailedRetries; /** Needed to speculate, but didn't have enough replicas **/ public final Counter speculativeInsufficientReplicas; /** Needed to write to a transient replica to satisfy quorum **/ public final Counter additionalWrites; /** Number of started repairs as coordinator on this keyspace */ public final Counter repairsStarted; /** Number of completed repairs as coordinator on this keyspace */ public final Counter repairsCompleted; /** total time spent as a repair coordinator */ public final Timer repairTime; /** total time spent preparing for repair */ public final Timer repairPrepareTime; /** Time spent anticompacting */ public final Timer anticompactionTime; /** total time spent creating merkle trees */ public final Timer validationTime; /** total time spent syncing data after repair */ public final Timer repairSyncTime; /** histogram over the number of bytes we have validated */ public final Histogram bytesValidated; /** histogram over the number of partitions we have validated */ public final Histogram partitionsValidated; /* * Metrics for inconsistencies detected between repaired data sets across replicas. These * are tracked on the coordinator. */ /** * Incremented where an inconsistency is detected and there are no pending repair sessions affecting * the data being read, indicating a genuine mismatch between replicas' repaired data sets. */ public final Meter confirmedRepairedInconsistencies; /** * Incremented where an inconsistency is detected, but there are pending & uncommitted repair sessions * in play on at least one replica. This may indicate a false positive as the inconsistency could be due to * replicas marking the repair session as committed at slightly different times and so some consider it to * be part of the repaired set whilst others do not. */ public final Meter unconfirmedRepairedInconsistencies; /** * Tracks the amount overreading of repaired data replicas perform in order to produce digests * at query time. For each query, on a full data read following an initial digest mismatch, the replicas * may read extra repaired data, up to the DataLimit of the command, so that the coordinator can compare * the repaired data on each replica. These are tracked on each replica. */ public final Histogram repairedDataTrackingOverreadRows; public final Timer repairedDataTrackingOverreadTime; public final MetricNameFactory factory; private Keyspace keyspace; /** set containing names of all the metrics stored here, for releasing later */ private Set<String> allMetrics = Sets.newHashSet(); /** * Creates metrics for given {@link ColumnFamilyStore}. * * @param ks Keyspace to measure metrics */ public KeyspaceMetrics(final Keyspace ks) { factory = new KeyspaceMetricNameFactory(ks); keyspace = ks; memtableColumnsCount = createKeyspaceGauge("MemtableColumnsCount", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.memtableColumnsCount.getValue(); } }); memtableLiveDataSize = createKeyspaceGauge("MemtableLiveDataSize", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.memtableLiveDataSize.getValue(); } }); memtableOnHeapDataSize = createKeyspaceGauge("MemtableOnHeapDataSize", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.memtableOnHeapSize.getValue(); } }); memtableOffHeapDataSize = createKeyspaceGauge("MemtableOffHeapDataSize", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.memtableOffHeapSize.getValue(); } }); allMemtablesLiveDataSize = createKeyspaceGauge("AllMemtablesLiveDataSize", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.allMemtablesLiveDataSize.getValue(); } }); allMemtablesOnHeapDataSize = createKeyspaceGauge("AllMemtablesOnHeapDataSize", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.allMemtablesOnHeapSize.getValue(); } }); allMemtablesOffHeapDataSize = createKeyspaceGauge("AllMemtablesOffHeapDataSize", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.allMemtablesOffHeapSize.getValue(); } }); memtableSwitchCount = createKeyspaceGauge("MemtableSwitchCount", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.memtableSwitchCount.getCount(); } }); pendingCompactions = createKeyspaceGauge("PendingCompactions", new MetricValue() { public Long getValue(TableMetrics metric) { return (long) metric.pendingCompactions.getValue(); } }); pendingFlushes = createKeyspaceGauge("PendingFlushes", new MetricValue() { public Long getValue(TableMetrics metric) { return (long) metric.pendingFlushes.getCount(); } }); liveDiskSpaceUsed = createKeyspaceGauge("LiveDiskSpaceUsed", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.liveDiskSpaceUsed.getCount(); } }); totalDiskSpaceUsed = createKeyspaceGauge("TotalDiskSpaceUsed", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.totalDiskSpaceUsed.getCount(); } }); bloomFilterDiskSpaceUsed = createKeyspaceGauge("BloomFilterDiskSpaceUsed", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.bloomFilterDiskSpaceUsed.getValue(); } }); bloomFilterOffHeapMemoryUsed = createKeyspaceGauge("BloomFilterOffHeapMemoryUsed", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.bloomFilterOffHeapMemoryUsed.getValue(); } }); indexSummaryOffHeapMemoryUsed = createKeyspaceGauge("IndexSummaryOffHeapMemoryUsed", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.indexSummaryOffHeapMemoryUsed.getValue(); } }); compressionMetadataOffHeapMemoryUsed = createKeyspaceGauge("CompressionMetadataOffHeapMemoryUsed", new MetricValue() { public Long getValue(TableMetrics metric) { return metric.compressionMetadataOffHeapMemoryUsed.getValue(); } }); // latency metrics for TableMetrics to update readLatency = new LatencyMetrics(factory, "Read"); writeLatency = new LatencyMetrics(factory, "Write"); rangeLatency = new LatencyMetrics(factory, "Range"); // create histograms for TableMetrics to replicate updates to sstablesPerReadHistogram = Metrics.histogram(factory.createMetricName("SSTablesPerReadHistogram"), true); tombstoneScannedHistogram = Metrics.histogram(factory.createMetricName("TombstoneScannedHistogram"), false); liveScannedHistogram = Metrics.histogram(factory.createMetricName("LiveScannedHistogram"), false); colUpdateTimeDeltaHistogram = Metrics.histogram(factory.createMetricName("ColUpdateTimeDeltaHistogram"), false); viewLockAcquireTime = Metrics.timer(factory.createMetricName("ViewLockAcquireTime")); viewReadTime = Metrics.timer(factory.createMetricName("ViewReadTime")); // add manually since histograms do not use createKeyspaceGauge method allMetrics.addAll(Lists.newArrayList("SSTablesPerReadHistogram", "TombstoneScannedHistogram", "LiveScannedHistogram")); casPrepare = new LatencyMetrics(factory, "CasPrepare"); casPropose = new LatencyMetrics(factory, "CasPropose"); casCommit = new LatencyMetrics(factory, "CasCommit"); writeFailedIdealCL = Metrics.counter(factory.createMetricName("WriteFailedIdealCL")); idealCLWriteLatency = new LatencyMetrics(factory, "IdealCLWrite"); speculativeRetries = createKeyspaceCounter("SpeculativeRetries", metric -> metric.speculativeRetries.getCount()); speculativeFailedRetries = createKeyspaceCounter("SpeculativeFailedRetries", metric -> metric.speculativeFailedRetries.getCount()); speculativeInsufficientReplicas = createKeyspaceCounter("SpeculativeInsufficientReplicas", metric -> metric.speculativeInsufficientReplicas.getCount()); additionalWrites = createKeyspaceCounter("AdditionalWrites", metric -> metric.additionalWrites.getCount()); repairsStarted = createKeyspaceCounter("RepairJobsStarted", metric -> metric.repairsStarted.getCount()); repairsCompleted = createKeyspaceCounter("RepairJobsCompleted", metric -> metric.repairsCompleted.getCount()); repairTime = Metrics.timer(factory.createMetricName("RepairTime")); repairPrepareTime = Metrics.timer(factory.createMetricName("RepairPrepareTime")); anticompactionTime = Metrics.timer(factory.createMetricName("AntiCompactionTime")); validationTime = Metrics.timer(factory.createMetricName("ValidationTime")); repairSyncTime = Metrics.timer(factory.createMetricName("RepairSyncTime")); partitionsValidated = Metrics.histogram(factory.createMetricName("PartitionsValidated"), false); bytesValidated = Metrics.histogram(factory.createMetricName("BytesValidated"), false); confirmedRepairedInconsistencies = Metrics.meter(factory.createMetricName("RepairedDataInconsistenciesConfirmed")); unconfirmedRepairedInconsistencies = Metrics.meter(factory.createMetricName("RepairedDataInconsistenciesUnconfirmed")); repairedDataTrackingOverreadRows = Metrics.histogram(factory.createMetricName("RepairedOverreadRows"), false); repairedDataTrackingOverreadTime = Metrics.timer(factory.createMetricName("RepairedOverreadTime")); } /** * Release all associated metrics. */ public void release() { for(String name : allMetrics) { Metrics.remove(factory.createMetricName(name)); } // latency metrics contain multiple metrics internally and need to be released manually readLatency.release(); writeLatency.release(); rangeLatency.release(); idealCLWriteLatency.release(); } /** * Represents a column family metric value. */ private interface MetricValue { /** * get value of a metric * @param metric of a column family in this keyspace * @return current value of a metric */ public Long getValue(TableMetrics metric); } /** * Creates a gauge that will sum the current value of a metric for all column families in this keyspace * @param name * @param extractor * @return Gauge&gt;Long> that computes sum of MetricValue.getValue() */ private Gauge<Long> createKeyspaceGauge(String name, final MetricValue extractor) { allMetrics.add(name); return Metrics.register(factory.createMetricName(name), new Gauge<Long>() { public Long getValue() { long sum = 0; for (ColumnFamilyStore cf : keyspace.getColumnFamilyStores()) { sum += extractor.getValue(cf.metric); } return sum; } }); } /** * Creates a counter that will sum the current value of a metric for all column families in this keyspace * @param name * @param extractor * @return Counter that computes sum of MetricValue.getValue() */ private Counter createKeyspaceCounter(String name, final MetricValue extractor) { allMetrics.add(name); return Metrics.register(factory.createMetricName(name), new Counter() { @Override public long getCount() { long sum = 0; for (ColumnFamilyStore cf : keyspace.getColumnFamilyStores()) { sum += extractor.getValue(cf.metric); } return sum; } }); } static class KeyspaceMetricNameFactory implements MetricNameFactory { private final String keyspaceName; KeyspaceMetricNameFactory(Keyspace ks) { this.keyspaceName = ks.getName(); } public CassandraMetricsRegistry.MetricName createMetricName(String metricName) { String groupName = TableMetrics.class.getPackage().getName(); StringBuilder mbeanName = new StringBuilder(); mbeanName.append(groupName).append(":"); mbeanName.append("type=Keyspace"); mbeanName.append(",keyspace=").append(keyspaceName); mbeanName.append(",name=").append(metricName); return new CassandraMetricsRegistry.MetricName(groupName, "keyspace", metricName, keyspaceName, mbeanName.toString()); } } }
apache-2.0
grzesuav/gjpf-core
src/tests/gov/nasa/jpf/test/basic/ListenerTest.java
1990
/* * Copyright (C) 2014, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The Java Pathfinder core (jpf-core) platform is licensed under the * Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gov.nasa.jpf.test.basic; import gov.nasa.jpf.Config; import gov.nasa.jpf.JPF; import gov.nasa.jpf.ListenerAdapter; import gov.nasa.jpf.search.Search; import gov.nasa.jpf.util.test.TestJPF; import gov.nasa.jpf.vm.SingleProcessVM; import gov.nasa.jpf.vm.Verify; import org.junit.Test; public class ListenerTest extends TestJPF { public static class Listener extends ListenerAdapter { @Override public void searchStarted (Search search){ System.out.println("-- listener got searchStarted() notification"); Verify.incrementCounter(0); } } public static class TestVM extends SingleProcessVM { public TestVM (JPF jpf, Config config){ super(jpf, config); jpf.addListener( new Listener()); } } @Test public void testPendingListeners (){ if (!isJPFRun()){ Verify.resetCounter(0); } if (verifyNoPropertyViolation("+vm.class=gov.nasa.jpf.test.basic.ListenerTest$TestVM")){ System.out.println("this is verified by JPF"); } if (!isJPFRun()){ assertTrue("init listener got no searchStarted() notification", Verify.getCounter(0) == 1); } } // <2do> ... and tons more to follow }
apache-2.0
lpxz/grail-derby104
java/testing/org/apache/derbyTesting/functionTests/tests/lang/ExistsWithSubqueriesTest.java
21767
/* Derby - Class org.apache.derbyTesting.functionTests.tests.lang.ExistsWithSubqueriesTest 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.derbyTesting.functionTests.tests.lang; import junit.framework.*; import org.apache.derbyTesting.junit.BaseJDBCTestCase; import org.apache.derbyTesting.junit.CleanDatabaseTestSetup; import org.apache.derbyTesting.junit.JDBC; import org.apache.derbyTesting.junit.TestConfiguration; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; /** * This test contains a variety of cases of EXISTS predicates with subqueries. * * Several tests ensure that an EXISTS predicate which wraps a set operation-- * meaning a UNION, INTERSECT, or EXCEPT node--returns the correct results. * For example: * * select * from ( values 'BAD' ) as T * where exists ((values 1) intersect (values 2)) * * should return zero rows. Prompted by DERBY-2370. * * A somewhat unrelated test verifies the DERBY-3033 behavior, which * involves flattening of subqueries with NOT EXISTS predicates. The * issue here is that a flattened NOT EXISTS subquery cannot be used * to perform equi-join transitive closure, because the implied predicate * that results from the flattening is a NOT EQUALS condition. */ public class ExistsWithSubqueriesTest extends BaseJDBCTestCase { private static final String EXISTS_PREFIX_1 = "select * from ( values 'GOT_A_ROW' ) as T where exists ("; private static final String EXISTS_PREFIX_2 = "select j from onerow where exists ("; /** * Create a test with the given name. * @param name name of the test. * */ public ExistsWithSubqueriesTest(String name) { super(name); } /** * Return suite with all tests of the class. */ public static Test suite() { TestSuite suite = new TestSuite("EXISTS with SET operations"); /* This is a language/optimization test so behavior will be the * same for embedded and client/server. Therefore we only need * to run the test against one or the other; we choose embedded. */ suite.addTest( TestConfiguration.embeddedSuite(ExistsWithSubqueriesTest.class)); /* Wrap the suite in a CleanDatabaseTestSetup that will create * and populate the test tables. */ return new CleanDatabaseTestSetup(suite) { /** * Create and populate the test table. */ protected void decorateSQL(Statement s) throws SQLException { s.executeUpdate("create table empty (i int)"); s.executeUpdate("create table onerow (j int)"); s.executeUpdate("insert into onerow values 2"); s.executeUpdate("create table diffrow (k int)"); s.executeUpdate("insert into diffrow values 4"); s.executeUpdate("create table tworows (p int)"); s.executeUpdate("insert into tworows values 2, 4"); s.executeUpdate("create table onerow2col (j1 int, j2 int)"); s.executeUpdate("insert into onerow2col values (2, 2)"); } }; } /** * Test queries where the set operation just involves VALUES * expressions. */ public void testSetOpsWithVALUES() throws Exception { Statement st = createStatement(); String [][] expRS = new String [1][1]; expRS[0][0] = "GOT_A_ROW"; checkQuery(st, expRS, EXISTS_PREFIX_1 + "values 1 union values 1)"); checkQuery(st, expRS, EXISTS_PREFIX_1 + "values 1 intersect values 1)"); checkQuery(st, expRS, EXISTS_PREFIX_1 + "values 1 except values 0)"); checkQuery(st, null, EXISTS_PREFIX_1 + "values 1 intersect values 0)"); checkQuery(st, null, EXISTS_PREFIX_1 + "values 1 except values 1)"); st.close(); } /** * Test queries where the set operation has subqueries which are not * correlated to the outer query. It's important to check for cases * where we have explicit columns _and_ cases where we have "*" because * the binding codepaths differ and we want to verify both. */ public void testNonCorrelatedSetOps() throws Exception { Statement st = createStatement(); String [][] expRS = new String [1][1]; expRS[0][0] = "GOT_A_ROW"; // Expect 1 row for the following. // Simple UNION with "*". checkQuery(st, expRS, EXISTS_PREFIX_1 + "select * from diffrow union select * from onerow)"); // Simple UNION with explicit columns. checkQuery(st, expRS, EXISTS_PREFIX_1 + "select k from diffrow union select j from onerow)"); // Simple INTERSECT with "*". checkQuery(st, expRS, EXISTS_PREFIX_1 + "select * from diffrow intersect select 4 from onerow)"); // Simple INTERSECT with explicit columns. checkQuery(st, expRS, EXISTS_PREFIX_1 + "select k from diffrow intersect select 4 from onerow)"); // Simple EXCEPT with "*". checkQuery(st, expRS, EXISTS_PREFIX_1 + "select * from diffrow except select * from onerow)"); // Simple EXCEPT with explicit columns. checkQuery(st, expRS, EXISTS_PREFIX_1 + "select k from diffrow except select j from onerow)"); // EXCEPT with "*" where left and right children have their // own preds. checkQuery(st, expRS, EXISTS_PREFIX_1 + "(select * from tworows where p = 2) except " + "(select * from tworows where p <> 2))"); // INTERSECT with "*" where left and right children have their // own preds. checkQuery(st, expRS, EXISTS_PREFIX_1 + "(select * from tworows where p = 2) intersect " + "(select * from tworows where p = 2))"); // Expect 0 rows for the following. Similar queries to // above except modified to return no rows. checkQuery(st, null, EXISTS_PREFIX_1 + "select i from empty union select * from empty)"); checkQuery(st, null, EXISTS_PREFIX_1 + "select * from onerow intersect select * from empty)"); checkQuery(st, null, EXISTS_PREFIX_1 + "select j from onerow intersect select i from empty)"); checkQuery(st, null, EXISTS_PREFIX_1 + "select * from empty except select * from onerow)"); checkQuery(st, null, EXISTS_PREFIX_1 + "select i from empty except select j from onerow)"); checkQuery(st, null, EXISTS_PREFIX_1 + "select * from onerow intersect select * from diffrow)"); checkQuery(st, null, EXISTS_PREFIX_1 + "select j from onerow intersect select k from diffrow)"); checkQuery(st, null, EXISTS_PREFIX_1 + "select * from onerow except select * from onerow)"); checkQuery(st, null, EXISTS_PREFIX_1 + "select j from onerow except select j from onerow)"); checkQuery(st, null, EXISTS_PREFIX_1 + "(select * from tworows where p = 2) intersect " + "(select * from tworows where p <> 2))"); checkQuery(st, null, EXISTS_PREFIX_1 + "(select * from tworows where p = 2) except " + "(select * from tworows where p = 2))"); // Negative cases. These should fail because "oops" is not // a valid column in ONEROW. assertCompileError("42X04", EXISTS_PREFIX_1 + "(select * from onerow where j = 2) intersect " + "(select oops from onerow where j <> 2))"); assertCompileError("42X04", EXISTS_PREFIX_1 + "(select * from onerow where j = 2) intersect " + "(select * from onerow where oops <> 2))"); st.close(); } /** * Test queries where the set operation has subqueries which are * correlated to the outer query. Subqueries should still be able * reference the outer query table and execute without error. */ public void testCorrelatedSetOps() throws Exception { Statement st = createStatement(); String [][] expRS = new String [1][1]; // "2" here is the value that was inserted into "onerow". expRS[0][0] = "2"; // Expect 1 row for the following. // Right child of UNION has "*" for RCL and references table // from outer query. checkQuery(st, expRS, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 1 union " + "select * from diffrow where onerow.j < k)"); // Right child of UNION has qualified "*" for RCL and references // table from outer query. checkQuery(st, expRS, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 1 union " + "select diffrow.* from diffrow where onerow.j < k)"); // Right child of UNION has explicit RCL and references // table from outer query. checkQuery(st, expRS, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 1 union " + "select k from diffrow where onerow.j < k)"); /* Right child of UNION is itself another EXISTS query whose * child is another set operator (INTERSECT). The INTERSECT in * turn has a right child which references a table from the * outer-most query. */ checkQuery(st, expRS, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 0 union " + "select * from diffrow where exists " + " (select 2 from diffrow intersect " + " select 2 from diffrow where onerow.j < k))"); /* Right child of UNION is itself another EXISTS query whose * child is another set operator (INTERSECT). The INTERSECT in * turn has a right child which references a table from the * outer-most query. In this one the INTERSECT returns zero * rows. */ checkQuery(st, expRS, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 1 union " + "select * from diffrow where exists " + " (select 2 from empty intersect " + " select 3 from empty where onerow.j < i))"); /* Right child of UNION is itself another EXISTS query whose * child is another set operator (INTERSECT). The INTERSECT in * turn has a right child which references 1) a table from the * outer-most query, and 2) a table from the INTERSECT node's * "parent" subquery (i.e. from the UNION's right subquery). */ checkQuery(st, expRS, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 1 union " + "select * from diffrow where exists " + " (select 2 from onerow2col intersect " + " select 3 from empty where onerow.j < diffrow.k))"); /* Right child of UNION is itself another EXISTS query whose * child is another set operator (INTERSECT). The INTERSECT in * turn has a right child which references 1) a table from the * outer-most query, and 2) a table from the INTERSECT node's * "parent" query. In addition, add another predicate to the * UNION's right subquery and make that predicate reference * both 1) a table from the outer-most query, and 2) a table * in the subquery's own FROM list. All of this to ensure * that binding finds the correct columns at all levels of * the query. */ checkQuery(st, expRS, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 1 union " + "select * from diffrow where exists " + " (select 2 from onerow2col intersect " + " select 3 from empty where onerow.j < k) " + " and (onerow.j < diffrow.k))"); // Expect 0 rows for the following. Similar queries to // above except modified to return no rows. checkQuery(st, null, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 0 union " + "select * from diffrow where onerow.j > k)"); checkQuery(st, null, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 0 union " + "select * from diffrow where exists " + " (select 2 from diffrow intersect " + " select 3 from diffrow where onerow.j < k))"); checkQuery(st, null, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 0 union " + "select * from diffrow where exists " + " (select 2 from empty intersect " + " select 3 from empty where onerow.j < i))"); checkQuery(st, null, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 0 union " + "select * from diffrow where exists " + " (select 2 from onerow2col intersect " + " select 3 from empty where onerow.j < diffrow.k))"); checkQuery(st, null, EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 0 union " + "select * from diffrow where exists " + " (select 2 from onerow2col intersect " + " select 3 from empty where onerow.j < k) " + " and (onerow.j < diffrow.k))"); // Negative cases. // Should fail because left and right children of the UNION // have different RCL sizes. (NOTE: Would have passed prior // to DERBY-2370, but that was incorrect). assertCompileError("42X58", EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 0 union " + "select * from onerow2col where onerow.j < j)"); /* Should fail because there is an explicit subquery ("SELECT *") * within the EXISTS query and such a subquery is not allowed to * reference outer tables. So we will be unable to find the * column "onerow.j" in this case. */ assertCompileError("42X04", EXISTS_PREFIX_2 + "select * from (select 1 from diffrow where 1 = 0 " + "union select * from diffrow where onerow.j < k) x)"); /* Should fail because the UNION's right subquery is trying to * select from an outer table. While the subquery is allowed * to reference the outer table in expressions, it cannot * include the outer table in its RCL. */ assertCompileError("42X10", EXISTS_PREFIX_2 + "select 1 from diffrow where 1 = 1 union " + "select onerow.* from diffrow where onerow.j < k)"); st.close(); } /** * Simple helper method to assert the results of the received * query. If the array representing expected results is null * then we assert that the query returns no rows. */ private void checkQuery(Statement st, String [][] expRS, String query) throws Exception { ResultSet rs = st.executeQuery(query); if (expRS == null) JDBC.assertEmpty(rs); else JDBC.assertFullResultSet(rs, expRS); rs.close(); } /** * Regression test for Derby-3033. * * This method constructs a query with the property that it: * - contains a NOT EXISTS condition against a correlated subquery * - such that if that subquery is flattened, the result is 3 tables * which all have join predicates on the same key. * The point of the test is that it is *not* correct to construct * a new equijoin predicate between table d3033_a and d3033_c via * transitive closure, because the join condition between d3033_b and * d3033_c is NOT EXISTS. * * In the original bug, the compiler/optimizer erroneously generated * the extra equijoin predicate, which caused NPE exceptions at * runtime due to attempts to reference the non-existent (NOT EXISTS) row. * * So this test succeeds if it gets the right results and no NPE. */ public void testDerby3033() throws Exception { setupDerby3033(); PreparedStatement pstmt = prepareStatement( "select c1, c2_b " + "from (select distinct st.c1,st.c2_b,dsr.c3_a,st.c3_b " + " from " + " d3033_a dsr, " + // Table order matters here! " d3033_b st " + " where dsr.c4_a is null " + " and dsr.c2 = ? " + " and dsr.c1 = st.c1 " + " and not exists ( " + " select 1 " + " from d3033_c " + " where d3033_c.c1 = st.c1 " + " and d3033_c.c2 = ? " + " and d3033_c.c3_c = ? " + " ) " + ") temp " ); pstmt.setInt(1, 4); pstmt.setInt(2, 4); pstmt.setInt(3, 100); String [][]expected = { { "1", "100" }, { "2", "200" }, { "3", "300" }, }; ResultSet rs = pstmt.executeQuery(); JDBC.assertFullResultSet(rs, expected); pstmt.close(); } /** * Ensure that the #rows statistics are updated */ private void updateStats(Statement st, String tName) throws Exception { ResultSet rs = st.executeQuery("select * from " + tName); int numRows = 0; while (rs.next()) numRows ++; rs.close(); } private void setupDerby3033() throws Exception { // The pattern of inserting the data is fairly important, as we // are going to do a combination of joins between the three tables // and we want both matching data and non-matching data. We load: // // d3033_a d3033_b d3033_c // -------- -------- -------- // 1 1 1 // 2 2 3 // 3 3 // 4 // // We also load a whole pile of irrelevant data into tables a and c // so that the index becomes relevant in the optimizer's analysis, // then we create some constraints and indexes and delete the rows // from table d3033_c (the NOT EXISTS table). // Statement s = createStatement(); s.executeUpdate("create table d3033_a "+ "(c1 int, c2 int, c3_a int, c4_a date)"); s.executeUpdate("create table d3033_b "+ "(c1 int primary key not null, c2_b int, c3_b date)"); s.executeUpdate("create table d3033_c (c1 int, c2 int, c3_c int)"); s.executeUpdate("insert into d3033_a (c1,c2,c3_a) values(1, 4, 10)"); s.executeUpdate("insert into d3033_a (c1,c2,c3_a) values(2, 4, 20)"); s.executeUpdate("insert into d3033_a (c1,c2,c3_a) values(3, 4, 30)"); s.executeUpdate("insert into d3033_b values(1, 100, CURRENT_DATE)"); s.executeUpdate("insert into d3033_b values(2, 200, CURRENT_DATE)"); s.executeUpdate("insert into d3033_b values(3, 300, CURRENT_DATE)"); s.executeUpdate("insert into d3033_b values(4, 400, CURRENT_DATE)"); s.executeUpdate("insert into d3033_c values(1, 4, 100)"); s.executeUpdate("insert into d3033_c values(3, 4, 100)"); PreparedStatement pstmt2 = prepareStatement( "insert into d3033_a (c1, c2, c3_a) values (?,?,?)"); PreparedStatement pstmt = prepareStatement( "insert into d3033_b (c1, c2_b, c3_b) values (?,?,?)"); java.util.Date now = new java.util.Date(); java.sql.Timestamp nowTS = new java.sql.Timestamp(now.getTime()); for (int i = 0; i < 15; i++) { pstmt.setInt(1, 100+i); pstmt.setInt(2, 100+i); pstmt.setTimestamp(3, nowTS); pstmt.executeUpdate(); for (int j = 0; j < 200; j++) { pstmt2.setInt(1, 1000+j); pstmt2.setInt(2, 100+i); // note "i" here (FK) pstmt2.setInt(3, 1000 + (j+1)*10); pstmt2.executeUpdate(); } } s.executeUpdate("alter table d3033_a add constraint " + "d3033_a_fk foreign key (c2) references d3033_b(c1) " + "on delete cascade on update no action"); s.executeUpdate("alter table d3033_c add constraint " + "d3033_c_fk foreign key (c1) references d3033_b(c1) " + "on delete cascade on update no action"); s.executeUpdate("delete from d3033_c"); // Update the statistics on the 3 tables: updateStats(s, "d3033_a"); updateStats(s, "d3033_b"); updateStats(s, "d3033_c"); s.close(); } }
apache-2.0
strapdata/elassandra
server/src/main/java/org/elasticsearch/action/admin/cluster/state/ClusterStateResponse.java
6664
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.action.admin.cluster.state; import org.elasticsearch.Version; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.cluster.ClusterModule; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.unit.ByteSizeValue; import java.io.IOException; import java.util.Objects; /** * The response for getting the cluster state. */ public class ClusterStateResponse extends ActionResponse { private ClusterName clusterName; private ClusterState clusterState; // the total compressed size of the full cluster state, not just // the parts included in this response private ByteSizeValue totalCompressedSize; private boolean waitForTimedOut = false; public ClusterStateResponse() { } public ClusterStateResponse(ClusterName clusterName, ClusterState clusterState, long sizeInBytes, boolean waitForTimedOut) { this.clusterName = clusterName; this.clusterState = clusterState; this.totalCompressedSize = new ByteSizeValue(sizeInBytes); this.waitForTimedOut = waitForTimedOut; } /** * The requested cluster state. Only the parts of the cluster state that were * requested are included in the returned {@link ClusterState} instance. */ public ClusterState getState() { return this.clusterState; } /** * The name of the cluster. */ public ClusterName getClusterName() { return this.clusterName; } /** * The total compressed size of the full cluster state, not just the parts * returned by {@link #getState()}. The total compressed size is the size * of the cluster state as it would be transmitted over the network during * intra-node communication. */ @Deprecated public ByteSizeValue getTotalCompressedSize() { return totalCompressedSize; } /** * Returns whether the request timed out waiting for a cluster state with a metadata version equal or * higher than the specified metadata. */ public boolean isWaitForTimedOut() { return waitForTimedOut; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); clusterName = new ClusterName(in); if (in.getVersion().onOrAfter(Version.V_6_6_0)) { clusterState = in.readOptionalWriteable(innerIn -> ClusterState.readFrom(innerIn, null)); } else { clusterState = ClusterState.readFrom(in, null); } if (in.getVersion().onOrAfter(Version.V_6_0_0_alpha1)) { totalCompressedSize = new ByteSizeValue(in); } else { // in a mixed cluster, if a pre 6.0 node processes the get cluster state // request, then a compressed size won't be returned, so just return 0; // its a temporary situation until all nodes in the cluster have been upgraded, // at which point the correct cluster state size will always be reported totalCompressedSize = new ByteSizeValue(0L); } if (in.getVersion().onOrAfter(Version.V_6_6_0)) { waitForTimedOut = in.readBoolean(); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); clusterName.writeTo(out); if (out.getVersion().onOrAfter(Version.V_6_6_0)) { out.writeOptionalWriteable(clusterState); } else { if (out.getVersion().onOrAfter(Version.V_6_3_0)) { clusterState.writeTo(out); } else { ClusterModule.filterCustomsForPre63Clients(clusterState).writeTo(out); } } if (out.getVersion().onOrAfter(Version.V_6_0_0_alpha1)) { totalCompressedSize.writeTo(out); } if (out.getVersion().onOrAfter(Version.V_6_6_0)) { out.writeBoolean(waitForTimedOut); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClusterStateResponse response = (ClusterStateResponse) o; return waitForTimedOut == response.waitForTimedOut && Objects.equals(clusterName, response.clusterName) && // Best effort. Only compare cluster state version and master node id, // because cluster state doesn't implement equals() Objects.equals(getVersion(clusterState), getVersion(response.clusterState)) && Objects.equals(getMasterNodeId(clusterState), getMasterNodeId(response.clusterState)) && Objects.equals(totalCompressedSize, response.totalCompressedSize); } @Override public int hashCode() { // Best effort. Only use cluster state version and master node id, // because cluster state doesn't implement hashcode() return Objects.hash( clusterName, getVersion(clusterState), getMasterNodeId(clusterState), totalCompressedSize, waitForTimedOut ); } private static String getMasterNodeId(ClusterState clusterState) { if (clusterState == null) { return null; } DiscoveryNodes nodes = clusterState.getNodes(); if (nodes != null) { return nodes.getMasterNodeId(); } else { return null; } } private static Long getVersion(ClusterState clusterState) { if (clusterState != null) { return clusterState.getVersion(); } else { return null; } } }
apache-2.0