repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
mfietz/AntennaPod | core/src/play/java/de/danoeh/antennapod/core/ClientConfig.java | 1708 | package de.danoeh.antennapod.core;
import android.content.Context;
import de.danoeh.antennapod.core.cast.CastManager;
import de.danoeh.antennapod.core.preferences.PlaybackPreferences;
import de.danoeh.antennapod.core.preferences.SleepTimerPreferences;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.storage.PodDBAdapter;
import de.danoeh.antennapod.core.util.NetworkUtils;
/**
* Stores callbacks for core classes like Services, DB classes etc. and other configuration variables.
* Apps using the core module of AntennaPod should register implementations of all interfaces here.
*/
public class ClientConfig {
private ClientConfig(){}
/**
* Should be used when setting User-Agent header for HTTP-requests.
*/
public static String USER_AGENT;
public static ApplicationCallbacks applicationCallbacks;
public static DownloadServiceCallbacks downloadServiceCallbacks;
public static PlaybackServiceCallbacks playbackServiceCallbacks;
public static GpodnetCallbacks gpodnetCallbacks;
public static FlattrCallbacks flattrCallbacks;
public static DBTasksCallbacks dbTasksCallbacks;
public static CastCallbacks castCallbacks;
private static boolean initialized = false;
public static synchronized void initialize(Context context) {
if(initialized) {
return;
}
PodDBAdapter.init(context);
UserPreferences.init(context);
UpdateManager.init(context);
PlaybackPreferences.init(context);
NetworkUtils.init(context);
CastManager.init(context);
SleepTimerPreferences.init(context);
initialized = true;
}
}
| mit |
wesleyegberto/study-ocjp | src/construtores/ConstrutorTesteDrive.java | 449 | package construtores;
public class ConstrutorTesteDrive {
public static void main(String[] args) {
// Construtor c1 = new Construtor();
// System.out.println("--c1\n" + c1.getNomeERg() + "\n\n");
Construtor c2 = new Construtor("Odair");
System.out.println("--c2\n" + c2.getNomeERg() + "\n\n");
Construtor c3 = new Construtor("Odair", "123456");
System.out.println("--c3\n" + c3.getNomeERg() + "\n\n");
}
}
| mit |
Veaer/Glass | glass/src/main/java/com/veaer/glass/viewpager/PagerTrigger.java | 1762 | package com.veaer.glass.viewpager;
import android.support.v4.view.ViewPager;
import com.veaer.glass.trigger.Trigger;
/**
* Created by Veaer on 15/11/18.
*/
public class PagerTrigger extends Trigger implements ViewPager.OnPageChangeListener {
private ColorProvider colorProvider;
private int startPosition, endPosition, maxLimit;
public static Trigger addTrigger(ViewPager viewPager, ColorProvider colorProvider) {
PagerTrigger viewPagerTrigger = new PagerTrigger(colorProvider);
viewPager.addOnPageChangeListener(viewPagerTrigger);
viewPagerTrigger.onPageSelected(0);
return viewPagerTrigger;
}
PagerTrigger(ColorProvider colorProvider) {
this.colorProvider = colorProvider;
maxLimit = colorProvider.getCount() - 1;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (isScrollingRight(position)) {
startPosition = position;
endPosition = Math.min(maxLimit, position + 1);
} else {
startPosition = Math.min(maxLimit, position + 1);
endPosition = position;
}
initColorGenerator();
setColor(ColorGenerator.getColor(position, positionOffset));
}
@Override
public void onPageScrollStateChanged(int state) {
//do nothing
}
@Override
public void onPageSelected(int position) {
endPosition = position;
startPosition = position;
initColorGenerator();
}
private boolean isScrollingRight(int position) {
return position == startPosition;
}
private void initColorGenerator() {
ColorGenerator.init(startPosition, endPosition, colorProvider);
}
}
| mit |
aenon/OnlineJudge | leetcode/1.Array_String/125.valid_palindrome.java | 423 | /* 125.valid_palindrome
*/
public class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
int ni = nums[i];
for (int j = i + 1; j < nums.length; j++) {
int nj = nums[j];
if (ni + nj == target) {
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
| mit |
kz/balances-android | app/src/main/java/in/iamkelv/balances/alarms/SchedulingService.java | 5935 | package in.iamkelv.balances.alarms;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import in.iamkelv.balances.R;
import in.iamkelv.balances.activities.MainActivity;
import in.iamkelv.balances.models.Balances;
import in.iamkelv.balances.models.BalancesDeserializer;
import in.iamkelv.balances.models.PreferencesModel;
import in.iamkelv.balances.models.WisePayService;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.converter.GsonConverter;
public class SchedulingService extends IntentService {
private final String ENDPOINT = "https://balances.iamkelv.in";
private PreferencesModel mPreferences;
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID = 1;
NotificationCompat.Builder builder;
public SchedulingService() {
super("SchedulingService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("Balances", "Starting notification check");
mPreferences = new PreferencesModel(this);
if (isNetworkAvailable()) {
checkBalances();
} else {
Log.e("Balances", "Network Unavailable");
}
Log.i("Balances", "Notification check complete");
AlarmReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String title, String message) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private void checkBalances() {
// Assign variables
String mUsername = mPreferences.getUsername();
String mPassword = mPreferences.getPassword();
// Set type adapter
Gson gson = new GsonBuilder()
.registerTypeAdapter(Balances.class, new BalancesDeserializer())
.create();
// Send balance request
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.setConverter(new GsonConverter(gson))
.build();
WisePayService service = restAdapter.create(WisePayService.class);
Callback<Balances> callback = new Callback<Balances>() {
@Override
public void success(Balances balances, Response response) {
// Get balances
Double lunch = balances.lunch;
Double tuck = balances.tuck;
int lunchBalance = lunch.intValue();
int tuckBalance= tuck.intValue();
lunch /= 100;
tuck /= 100;
String strLunch = String.format("%.2f",lunch);
String strTuck = String.format("%.2f",tuck);
// Update preferences
mPreferences.setLunchBalance(strLunch);
mPreferences.setTuckBalance(strTuck);
mPreferences.setLastChecked(System.currentTimeMillis());
int lunchThreshold = mPreferences.getLunchThreshold() * 100;
int tuckThreshold = mPreferences.getTuckThreshold() * 100;
if (lunchBalance < lunchThreshold && tuckBalance < tuckThreshold) {
sendNotification("Balances Alert", "Your lunch and tuck balances are low");
} else if (lunchBalance < lunchThreshold) {
sendNotification("Balances Alert", "Your lunch balance is low");
} else if (tuckBalance < tuckThreshold) {
sendNotification("Balances Alert", "Your tuck balance is low");
}
}
@Override
public void failure(RetrofitError retrofitError) {
Log.e("BALANCES", "Failed callback");
// Check for authentication error
if (retrofitError.getResponse().getStatus() == 401) {
mPreferences.setAuthState(false);
sendNotification("Balances - Error", "Your WisePay login details are incorrect. Tap here to fix.");
} else {
JsonObject jsonResponse = (JsonObject) retrofitError.getBodyAs(JsonObject.class);
try {
sendNotification("Balances - Error", jsonResponse.get("message").getAsString());
} catch (NullPointerException e) {
sendNotification("Balances - Error", "An unknown error occurred while checking your balances.");
}
}
}
};
service.checkBalances(mUsername, mPassword, callback);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
} | mit |
wrpinheiro/easy-factory | core/src/main/java/com/thecodeinside/easyfactory/core/Attribute.java | 795 | package com.thecodeinside.easyfactory.core;
/**
* A factory's attribute.
*
* @author Wellington Pinheiro <wellington.pinheiro@gmail.com>
*
* @param <T> type of the attribute
*/
public class Attribute<T> {
private String id;
private T value;
public String getId() {
return this.id;
}
public T getValue() {
return this.value;
}
public Attribute() {
}
public Attribute(String id, T value) {
this.id = id;
this.value = value;
}
@Override
public String toString() {
return "Attribute [id=" + id + ", value=" + value + "]";
}
public boolean isReference() {
return value instanceof FactoryReference;
}
public boolean isNotReference() {
return !isReference();
}
}
| mit |
nbv3/voogasalad_CS308 | src/com/syntacticsugar/vooga/gameplayer/objects/items/bullets/SlowBullet.java | 465 | package com.syntacticsugar.vooga.gameplayer.objects.items.bullets;
import com.syntacticsugar.vooga.gameplayer.event.implementations.SlowEvent;
import com.syntacticsugar.vooga.gameplayer.objects.GameObjectType;
public class SlowBullet extends AbstractBullet {
public SlowBullet(BulletParams params, double speedDecrease, int time) {
super(params);
SlowEvent slow = new SlowEvent(speedDecrease, time);
addCollisionBinding(GameObjectType.ENEMY, slow);
}
}
| mit |
grinning/war-tommybranch | war/src/main/java/com/tommytony/war/job/ResetCursorJob.java | 2006 | package com.tommytony.war.job;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import com.tommytony.war.War;
import com.tommytony.war.volume.BlockInfo;
public class ResetCursorJob implements Runnable {
private final Block cornerBlock;
private final BlockInfo[] originalCursorBlocks;
private final boolean isSoutheast;
public ResetCursorJob(Block cornerBlock, BlockInfo[] originalCursorBlocks, boolean isSoutheast) {
this.cornerBlock = cornerBlock;
this.originalCursorBlocks = originalCursorBlocks;
this.isSoutheast = isSoutheast;
}
public void run() {
if (this.isSoutheast) {
this.cornerBlock.setType(this.originalCursorBlocks[0].getType());
this.cornerBlock.setData(this.originalCursorBlocks[0].getData());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.WEST : BlockFace.SOUTH).setType(this.originalCursorBlocks[1].getType());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.WEST : BlockFace.SOUTH).setData(this.originalCursorBlocks[1].getData());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.NORTH : BlockFace.WEST).setType(this.originalCursorBlocks[2].getType());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.NORTH : BlockFace.WEST).setData(this.originalCursorBlocks[2].getData());
} else {
this.cornerBlock.setType(this.originalCursorBlocks[0].getType());
this.cornerBlock.setData(this.originalCursorBlocks[0].getData());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.EAST : BlockFace.NORTH).setType(this.originalCursorBlocks[1].getType());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.EAST : BlockFace.NORTH).setData(this.originalCursorBlocks[1].getData());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.SOUTH : BlockFace.EAST).setType(this.originalCursorBlocks[2].getType());
this.cornerBlock.getRelative(War.legacyBlockFace ? BlockFace.SOUTH : BlockFace.EAST).setData(this.originalCursorBlocks[2].getData());
}
}
}
| mit |
jeremyje/android-beryl | beryl/src/org/beryl/app/AndroidVersion.java | 6414 | package org.beryl.app;
/** Convenience class for retrieving the current Android version that's running on the device.
*
* Code example on how to use AndroidVersion to load a multi-versioned class at runtime for backwards compatibility without using reflection.
* <pre class="code"><code class="java">
import org.beryl.app.AndroidVersion;
public class StrictModeEnabler {
public static void enableOnThread() {
IStrictModeEnabler enabler = getStrictModeEnabler();
}
// Strict Mode is only supported on Gingerbread or higher.
private static IStrictModeEnabler getStrictModeEnabler() {
if(AndroidVersion.isGingerbreadOrHigher()) {
return new GingerbreadAndAboveStrictModeEnabler();
} else {
return new NoStrictModeEnabler();
}
}
}
</code></pre>*/
@SuppressWarnings("deprecation")
public class AndroidVersion {
private static final int _ANDROID_SDK_VERSION;
private static final int ANDROID_SDK_VERSION_PREVIEW = Integer.MAX_VALUE;
static {
int android_sdk = 3; // 3 is Android 1.5 (Cupcake) which is the earliest Android SDK available.
try {
android_sdk = Integer.parseInt(android.os.Build.VERSION.SDK);
}
catch (Exception e) {
android_sdk = ANDROID_SDK_VERSION_PREVIEW;
}
finally {}
_ANDROID_SDK_VERSION = android_sdk;
}
/** Returns true if running on development or preview version of Android. */
public static boolean isPreviewVersion() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
}
/** Gets the SDK Level available to the device. */
public static int getSdkVersion() {
return _ANDROID_SDK_VERSION;
}
/** Returns true if running on Android 1.5 or higher. */
public static boolean isCupcakeOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.CUPCAKE;
}
/** Returns true if running on Android 1.6 or higher. */
public static boolean isDonutOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.DONUT;
}
/** Returns true if running on Android 2.0 or higher. */
public static boolean isEclairOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR;
}
/** Returns true if running on Android 2.1-update1 or higher. */
public static boolean isEclairMr1OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR_MR1;
}
/** Returns true if running on Android 2.2 or higher. */
public static boolean isFroyoOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.FROYO;
}
/** Returns true if running on Android 2.3 or higher. */
public static boolean isGingerbreadOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.GINGERBREAD;
}
/** Returns true if running on Android 2.3.3 or higher. */
public static boolean isGingerbreadMr1OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1;
}
/** Returns true if running on Android 3.0 or higher. */
public static boolean isHoneycombOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB;
}
/** Returns true if running on Android 3.1 or higher. */
public static boolean isHoneycombMr1OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1;
}
/** Returns true if running on Android 3.2 or higher. */
public static boolean isHoneycombMr2OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
}
/** Returns true if running on Android 4.0 or higher. */
public static boolean isIceCreamSandwichOrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
/** Returns true if running on Android 4.0.3 or higher. */
public static boolean isIceCreamSandwichMr1OrHigher() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
}
/** Returns true if running on an earlier version than Android 4.0.3. */
public static boolean isBeforeIceCreamSandwichMr1() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
}
/** Returns true if running on an earlier version than Android 4.0. */
public static boolean isBeforeIceCreamSandwich() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
/** Returns true if running on an earlier version than Android 3.2. */
public static boolean isBeforeHoneycombMr2() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
}
/** Returns true if running on an earlier version than Android 3.1. */
public static boolean isBeforeHoneycombMr1() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB_MR1;
}
/** Returns true if running on an earlier version than Android 3.0. */
public static boolean isBeforeHoneycomb() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.HONEYCOMB;
}
/** Returns true if running on an earlier version than Android 2.3.3. */
public static boolean isBeforeGingerbreadMr1() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.GINGERBREAD_MR1;
}
/** Returns true if running on an earlier version than Android 2.3. */
public static boolean isBeforeGingerbread() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.GINGERBREAD;
}
/** Returns true if running on an earlier version than Android 2.2. */
public static boolean isBeforeFroyo() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.FROYO;
}
/** Returns true if running on an earlier version than Android 2.1-update. */
public static boolean isBeforeEclairMr1() {
return _ANDROID_SDK_VERSION >= android.os.Build.VERSION_CODES.ECLAIR_MR1;
}
/** Returns true if running on an earlier version than Android 2.0. */
public static boolean isBeforeEclair() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.ECLAIR;
}
/** Returns true if running on an earlier version than Android 1.6. */
public static boolean isBeforeDonut() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.DONUT;
}
/** Returns true if running on an earlier version than Android 1.5. */
public static boolean isBeforeCupcake() {
return _ANDROID_SDK_VERSION < android.os.Build.VERSION_CODES.CUPCAKE;
}
private AndroidVersion() {
// Prevent users from instantiating this class.
}
}
| mit |
zporky/langs-and-paradigms | projects/EJULOK/Java/prognyelvek/src/main/java/bence/prognyelvek/contexts/ContextFactory.java | 224 | package bence.prognyelvek.contexts;
import java.util.List;
/**
* @param <T> Input token type.
* @param <O> Output token type.
*/
public interface ContextFactory<T, O> {
Context<T, O> getInstance(List<T> tokens);
}
| mit |
tomaskir/netxms-config-repository | src/test/java/sk/atris/netxms/confrepo/tests/service/database/DatabaseTest.java | 992 | package sk.atris.netxms.confrepo.tests.service.database;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import sk.atris.netxms.confrepo.exceptions.DatabaseException;
import sk.atris.netxms.confrepo.service.database.DbConnectionManager;
import sk.atris.netxms.confrepo.service.database.DbObjectHandler;
import sk.atris.netxms.confrepo.tests.MockedDatabase;
public class DatabaseTest {
@Before
public void environmentSetup() throws Exception {
MockedDatabase.setup();
}
@After
public void environmentCleanup() throws Exception {
MockedDatabase.cleanup();
}
@Test
public void testDatabase() throws DatabaseException {
Revision object = new Revision("test", "test", 1);
// make sure database works
DbObjectHandler.getInstance().saveToDb(object);
DbObjectHandler.getInstance().removeFromDb(object);
// test shutdown
DbConnectionManager.getInstance().shutdown();
}
}
| mit |
lathspell/java_test | java_test_spring_aop/src/test/java/de/lathspell/test/service/BarTest.java | 1425 | package de.lathspell.test.service;
import lombok.extern.slf4j.Slf4j;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import de.lathspell.test.config.AopConfiguration;
import de.lathspell.test.service.BarService;
import de.lathspell.test.service.DebugService;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AopConfiguration.class)
@Slf4j
public class BarTest {
@Autowired
private BarService barService;
@Autowired
private DebugService logService;
@Before
public void before() {
logService.setLog("");
}
@Test
public void testAfterReturning() {
String result = barService.hello("Tim");
assertThat(result, is("Hello Tim"));
assertThat(logService.getLog(), is("afterHello()-afterReturningFromHello([Tim]) => Hello Tim"));
}
@Test
public void testAfterThrowing() {
try {
barService.hello(null);
} catch (Exception e) {
// ignore
}
assertThat(logService.getLog(), is("afterHello()-afterThrowingFromHello([null]) @" + barService.toString() + " => No name!"));
}
}
| cc0-1.0 |
samirprakash/spring-aop | src/com/sp/jb/service/ShapeService.java | 482 | package com.sp.jb.service;
import com.sp.jb.model.Circle;
import com.sp.jb.model.Triangle;
public class ShapeService {
private Circle circle;
private Triangle triangle;
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
public Triangle getTriangle() {
return triangle;
}
public void setTriangle(Triangle triangle) {
this.triangle = triangle;
}
}
| cc0-1.0 |
sebhoss/memoization.java | memoization-core/src/main/java/de/xn__ho_hia/memoization/map/ConcurrentMapBasedDoubleBinaryOperatorMemoizer.java | 1887 | /*
* This file is part of memoization.java. It is subject to the license terms in the LICENSE file found in the top-level
* directory of this distribution and at http://creativecommons.org/publicdomain/zero/1.0/. No part of memoization.java,
* including this file, may be copied, modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
package de.xn__ho_hia.memoization.map;
import static java.util.Objects.requireNonNull;
import java.util.concurrent.ConcurrentMap;
import java.util.function.DoubleBinaryOperator;
import de.xn__ho_hia.memoization.shared.DoubleBinaryFunction;
import de.xn__ho_hia.quality.suppression.CompilerWarnings;
final class ConcurrentMapBasedDoubleBinaryOperatorMemoizer<KEY>
extends ConcurrentMapBasedMemoizer<KEY, Double>
implements DoubleBinaryOperator {
private final DoubleBinaryFunction<KEY> keyFunction;
private final DoubleBinaryOperator operator;
@SuppressWarnings(CompilerWarnings.NLS)
public ConcurrentMapBasedDoubleBinaryOperatorMemoizer(
final ConcurrentMap<KEY, Double> cache,
final DoubleBinaryFunction<KEY> keyFunction,
final DoubleBinaryOperator operator) {
super(cache);
this.keyFunction = requireNonNull(keyFunction,
"Provide a key function, might just be 'MemoizationDefaults.doubleBinaryOperatorHashCodeKeyFunction()'.");
this.operator = requireNonNull(operator,
"Cannot memoize a NULL DoubleBinaryOperator - provide an actual DoubleBinaryOperator to fix this.");
}
@Override
public double applyAsDouble(final double left, final double right) {
final KEY key = keyFunction.apply(left, right);
return computeIfAbsent(key, givenKey -> Double.valueOf(operator.applyAsDouble(left, right)))
.doubleValue();
}
}
| cc0-1.0 |
SigmaOne/DesignPatterns | src/main/java/patterns/behavioral/command/Command.java | 150 | package patterns.behavioral.command;
// General interface for all the commands
public abstract class Command {
public abstract void execute();
}
| cc0-1.0 |
MeasureAuthoringTool/clinical_quality_language | Src/java/tools/cql-parsetree/src/main/java/org/cqframework/cql/tools/parsetree/Main.java | 1105 | package org.cqframework.cql.tools.parsetree;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.cqframework.cql.gen.cqlLexer;
import org.cqframework.cql.gen.cqlParser;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* A simple wrapper around the ANTLR4 testrig.
*/
public class Main {
public static void main(String[] args) throws IOException {
String inputFile = null;
if (args.length > 0) {
inputFile = args[0];
}
InputStream is = System.in;
if (inputFile != null) {
is = new FileInputStream(inputFile);
}
ANTLRInputStream input = new ANTLRInputStream(is);
cqlLexer lexer = new cqlLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
tokens.fill();
cqlParser parser = new cqlParser(tokens);
parser.setBuildParseTree(true);
ParserRuleContext tree = parser.library();
tree.inspect(parser);
}
}
| cc0-1.0 |
mtstv/accesscontroltool | accesscontroltool-bundle/src/main/java/biz/netcentric/cq/tools/actool/validators/Validators.java | 3216 | /*
* (C) Copyright 2015 Netcentric AG.
*
* 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 biz.netcentric.cq.tools.actool.validators;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.jcr.RepositoryException;
import javax.jcr.security.AccessControlManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.security.util.CqActions;
public class Validators {
private static final Logger LOG = LoggerFactory.getLogger(Validators.class);
public static boolean isValidNodePath(final String path) {
if (StringUtils.isBlank(path)) {
return true; // repository level permissions are created with 'left-out' path property
}
if (!path.startsWith("/")) {
return false;
}
return true;
}
/**
* Validates in the same way as <a href="https://github.com/apache/jackrabbit-oak/blob/7999b5cbce87295b502ea4d1622e729f5b96701d/oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/UserManagerImpl.java#L421">Oak's UserManagerImpl</a>.
* @param id the authorizable id to validate
* @return {@code true} in case the given id is a valid authorizable id, otherwise {@code false}
*/
public static boolean isValidAuthorizableId(final String id) {
if (StringUtils.isBlank(id)) {
return false;
}
return true;
}
public static boolean isValidRegex(String expression) {
if (StringUtils.isBlank(expression)) {
return true;
}
boolean isValid = true;
if (expression.startsWith("*")) {
expression = expression.replaceFirst("\\*", "\\\\*");
}
try {
Pattern.compile(expression);
} catch (PatternSyntaxException e) {
LOG.error("Error while validating rep glob: {} ", expression, e);
isValid = false;
}
return isValid;
}
public static boolean isValidAction(String action) {
List<String> validActions = Arrays.asList(CqActions.ACTIONS);
if (action == null) {
return false;
}
if (!validActions.contains(action)) {
return false;
}
return true;
}
public static boolean isValidJcrPrivilege(String privilege, AccessControlManager aclManager) {
if (privilege == null) {
return false;
}
try {
aclManager.privilegeFromName(privilege);
} catch (RepositoryException e) {
return false;
}
return true;
}
public static boolean isValidPermission(String permission) {
if (permission == null) {
return false;
}
if (StringUtils.equals("allow", permission)
|| StringUtils.equals("deny", permission)) {
return true;
}
return false;
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/annotations/Cache.java | 5380 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.eclipse.persistence.config.CacheIsolationType;
import static org.eclipse.persistence.config.CacheIsolationType.SHARED;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.eclipse.persistence.annotations.CacheType.SOFT_WEAK;
import static org.eclipse.persistence.annotations.CacheCoordinationType.SEND_OBJECT_CHANGES;
/**
* The Cache annotation is used to configure the EclipseLink object cache.
* By default EclipseLink uses a shared object cache to cache all objects.
* The caching type and options can be configured on a per class basis to allow
* optimal caching.
* <p>
* This includes options for configuring the type of caching,
* setting the size, disabling the shared cache, expiring objects, refreshing,
* and cache coordination (clustering).
* <p>
* A Cache annotation may be defined on an Entity or MappedSuperclass. In the
* case of inheritance, a Cache annotation should only be defined on the root
* of the inheritance hierarchy.
*
* @see org.eclipse.persistence.annotations.CacheType
* @see org.eclipse.persistence.annotations.CacheCoordinationType
*
* @see org.eclipse.persistence.descriptors.ClassDescriptor
* @see org.eclipse.persistence.descriptors.invalidation.CacheInvalidationPolicy
*
* @author Guy Pelletier
* @since Oracle TopLink 11.1.1.0.0
*/
@Target({TYPE})
@Retention(RUNTIME)
public @interface Cache {
/**
* (Optional) The type of cache to use.
* The default is SOFT_WEAK.
*/
CacheType type() default SOFT_WEAK;
/**
* (Optional) The size of cache to use.
* The default is 100.
*/
int size() default 100;
/**
* (Optional) Cached instances in the shared cache,
* or only a per EntityManager isolated cache.
* The default is shared.
* @deprecated As of Eclipselink 2.2. See the attribute 'isolation'
*/
@Deprecated
boolean shared() default true;
/**
* (Optional) Controls the level of caching this Entity will use.
* The default is CacheIsolationType.SHARED which has EclipseLink
* Caching all Entities in the Shared Cache.
* @see org.eclipse.persistence.config.CacheIsolationType
*/
CacheIsolationType isolation() default SHARED;
/**
* (Optional) Expire cached instance after a fix period of time (ms).
* Queries executed against the cache after this will be forced back
* to the database for a refreshed copy.
* By default there is no expiry.
*/
int expiry() default -1; // minus one is no expiry.
/**
* (Optional) Expire cached instance a specific time of day. Queries
* executed against the cache after this will be forced back to the
* database for a refreshed copy.
*/
TimeOfDay expiryTimeOfDay() default @TimeOfDay(specified=false);
/**
* (Optional) Force all queries that go to the database to always
* refresh the cache.
* Default is false.
* Consider disabling the shared cache instead of forcing refreshing.
*/
boolean alwaysRefresh() default false;
/**
* (Optional) For all queries that go to the database, refresh the cache
* only if the data received from the database by a query is newer than
* the data in the cache (as determined by the optimistic locking field).
* This is normally used in conjunction with alwaysRefresh, and by itself
* it only affect explicit refresh calls or queries.
* Default is false.
*/
boolean refreshOnlyIfNewer() default false;
/**
* (Optional) Setting to true will force all queries to bypass the
* cache for hits but still resolve against the cache for identity.
* This forces all queries to hit the database.
*/
boolean disableHits() default false;
/**
* (Optional) The cache coordination mode.
* Note that cache coordination must also be configured for the persistence unit/session.
*/
CacheCoordinationType coordinationType() default SEND_OBJECT_CHANGES;
/**
* (Optional) The database change notification mode.
* Note that database event listener must also be configured for the persistence unit/session.
*/
DatabaseChangeNotificationType databaseChangeNotificationType() default DatabaseChangeNotificationType.INVALIDATE;
}
| epl-1.0 |
trajano/app-ms | ms-common-impl/src/main/java/net/trajano/ms/vertx/beans/package-info.java | 92 | /**
* Java Beans.
*
* @author Archimedes Trajano
*/
package net.trajano.ms.vertx.beans;
| epl-1.0 |
ModelWriter/Deliverables | WP2/D2.5.2_Generation/Jeni/src/edu/stanford/nlp/lm/TestSRILM.java | 639 | package edu.stanford.nlp.lm;
import java.io.File;
import java.util.Arrays;
/**
* This is a simple test of srilm.
* @author Alexandre Denis
*
*/
public class TestSRILM
{
/**
* @param args
*/
public static void main(String[] args)
{
SRILanguageModel model = new SRILanguageModel(new File("resources/ranking/lm-genia-lemma"), 3);
System.out.println(model.getSentenceLogProb(Arrays.asList("the central nucleotide be proportional to the size of the vacuole".split(" "))));
System.out.println(model.getSentenceLogProb(Arrays.asList("the be size to the nucleotide vacuole central the proportional to".split(" "))));
}
}
| epl-1.0 |
DaanielZ/DToolsZ | DToolsZ/src/daanielz/tools/commands/WorkbenchCmd.java | 978 | package daanielz.tools.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import daanielz.tools.Utils;
public class WorkbenchCmd implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(sender instanceof Player){
Player p = (Player) sender;
if(cmd.getName().equalsIgnoreCase("workbench")){
if(!sender.hasPermission("vetesda.workbench")){
sender.sendMessage(Utils.getColor("&8» &7Nie masz uprawnien."));
} else{
p.openWorkbench(null, true);
}
} else if(cmd.getName().equalsIgnoreCase("enchanttable")){
if(!sender.hasPermission("vetesda.enchanttable")){
sender.sendMessage(Utils.getColor("&8» &7Nie masz uprawnien."));
} else{
p.openEnchanting(null, true);
}
}
} return true;
}
} | epl-1.0 |
NABUCCO/org.nabucco.framework.base | org.nabucco.framework.base.impl.service/src/main/man/org/nabucco/framework/base/impl/service/timer/Timer.java | 3676 | /*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), 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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.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.
*/
package org.nabucco.framework.base.impl.service.timer;
import java.io.Serializable;
import org.nabucco.framework.base.facade.datatype.logger.NabuccoLogger;
import org.nabucco.framework.base.facade.datatype.logger.NabuccoLoggingFactory;
/**
* Timer
*
* @author Nicolas Moser, PRODYNA AG
*/
public abstract class Timer implements Serializable {
private static final long serialVersionUID = 1L;
private final String name;
private final TimerPriority priority;
private final NabuccoLogger logger = NabuccoLoggingFactory.getInstance().getLogger(this.getClass());
/**
* Creates a new {@link Timer} instance.
*
* @param name
* the timer name
* @param priority
* the timer priority
*/
public Timer(String name, TimerPriority priority) {
if (name == null) {
throw new IllegalArgumentException("Cannot create Timer for name [null].");
}
if (priority == null) {
throw new IllegalArgumentException("Cannot create Timer for priority [null].");
}
this.name = name;
this.priority = priority;
}
/**
* Getter for the logger.
*
* @return Returns the logger.
*/
protected NabuccoLogger getLogger() {
return this.logger;
}
/**
* Getter for the name.
*
* @return Returns the name.
*/
public final String getName() {
return this.name;
}
/**
* Getter for the priority.
*
* @return Returns the priority.
*/
public final TimerPriority getPriority() {
return this.priority;
}
/**
* Method that executes the appropriate timer logic.
*
* @throws TimerExecutionException
* when an exception during timer execution occurs
*/
public abstract void execute() throws TimerExecutionException;
@Override
public final int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
return result;
}
@Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Timer other = (Timer) obj;
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
return true;
}
@Override
public final String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.name);
builder.append(" [");
builder.append(this.getClass().getCanonicalName());
builder.append(", ");
builder.append(this.priority);
builder.append("]");
return builder.toString();
}
}
| epl-1.0 |
argocasegeo/argocasegeo | src/org/argouml/application/api/PluggableProjectWriter.java | 1869 | // Copyright (c) 1996-2002 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.application.api;
/** An plugin interface which identifies an ArgoUML data loader.
* <br>
* TODO: identify methods
*
* @author Thierry Lach
* @since ARGO0.11.3
*/
public interface PluggableProjectWriter extends Pluggable {
} /* End interface PluggableProjectWriter */
| epl-1.0 |
aporo69/junit-issue-1167 | poc/src/main/java/org/junit/runners/fix/v411/Parameterized.java | 13537 | package org.junit.runners.fix.v411;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.Suite;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
/**
* <p>
* The custom runner <code>Parameterized</code> implements parameterized tests.
* When running a parameterized test class, instances are created for the
* cross-product of the test methods and the test data elements.
* </p>
*
* For example, to test a Fibonacci function, write:
*
* <pre>
* @RunWith(Parameterized.class)
* public class FibonacciTest {
* @Parameters(name= "{index}: fib({0})={1}")
* public static Iterable<Object[]> data() {
* return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
* { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
* }
*
* private int fInput;
*
* private int fExpected;
*
* public FibonacciTest(int input, int expected) {
* fInput= input;
* fExpected= expected;
* }
*
* @Test
* public void test() {
* assertEquals(fExpected, Fibonacci.compute(fInput));
* }
* }
* </pre>
*
* <p>
* Each instance of <code>FibonacciTest</code> will be constructed using the
* two-argument constructor and the data values in the
* <code>@Parameters</code> method.
*
* <p>
* In order that you can easily identify the individual tests, you may provide a
* name for the <code>@Parameters</code> annotation. This name is allowed
* to contain placeholders, which are replaced at runtime. The placeholders are
* <dl>
* <dt>{index}</dt>
* <dd>the current parameter index</dd>
* <dt>{0}</dt>
* <dd>the first parameter value</dd>
* <dt>{1}</dt>
* <dd>the second parameter value</dd>
* <dt>...</dt>
* <dd></dd>
* </dl>
* In the example given above, the <code>Parameterized</code> runner creates
* names like <code>[1: fib(3)=2]</code>. If you don't use the name parameter,
* then the current parameter index is used as name.
* </p>
*
* You can also write:
*
* <pre>
* @RunWith(Parameterized.class)
* public class FibonacciTest {
* @Parameters
* public static Iterable<Object[]> data() {
* return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
* { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
* }
* @Parameter(0)
* public int fInput;
*
* @Parameter(1)
* public int fExpected;
*
* @Test
* public void test() {
* assertEquals(fExpected, Fibonacci.compute(fInput));
* }
* }
* </pre>
*
* <p>
* Each instance of <code>FibonacciTest</code> will be constructed with the default constructor
* and fields annotated by <code>@Parameter</code> will be initialized
* with the data values in the <code>@Parameters</code> method.
* </p>
*
* @since 4.0
*/
public class Parameterized extends Suite {
/**
* Annotation for a method which provides parameters to be injected into the
* test class constructor by <code>Parameterized</code>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Parameters {
/**
* <p>
* Optional pattern to derive the test's name from the parameters. Use
* numbers in braces to refer to the parameters or the additional data
* as follows:
* </p>
*
* <pre>
* {index} - the current parameter index
* {0} - the first parameter value
* {1} - the second parameter value
* etc...
* </pre>
* <p>
* Default value is "{index}" for compatibility with previous JUnit
* versions.
* </p>
*
* @return {@link MessageFormat} pattern string, except the index
* placeholder.
* @see MessageFormat
*/
String name() default "{index}";
}
/**
* Annotation for fields of the test class which will be initialized by the
* method annotated by <code>Parameters</code><br/>
* By using directly this annotation, the test class constructor isn't needed.<br/>
* Index range must start at 0.
* Default value is 0.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public static @interface Parameter {
/**
* Method that returns the index of the parameter in the array
* returned by the method annotated by <code>Parameters</code>.<br/>
* Index range must start at 0.
* Default value is 0.
*
* @return the index of the parameter.
*/
int value() default 0;
}
protected static final Map<Character, String> ESCAPE_SEQUENCES = new HashMap<Character, String>();
static {
ESCAPE_SEQUENCES.put('\0', "\\\\0");
ESCAPE_SEQUENCES.put('\t', "\\\\t");
ESCAPE_SEQUENCES.put('\b', "\\\\b");
ESCAPE_SEQUENCES.put('\n', "\\\\n");
ESCAPE_SEQUENCES.put('\r', "\\\\r");
ESCAPE_SEQUENCES.put('\f', "\\\\f");
}
private class TestClassRunnerForParameters extends BlockJUnit4ClassRunner {
private final Object[] fParameters;
private final String fName;
TestClassRunnerForParameters(final Class<?> type, final Object[] parameters, final String name) throws InitializationError {
super(type);
this.fParameters = parameters;
this.fName = name;
}
@Override
public Object createTest() throws Exception {
if (fieldsAreAnnotated()) {
return createTestUsingFieldInjection();
} else {
return createTestUsingConstructorInjection();
}
}
private Object createTestUsingConstructorInjection() throws Exception {
return getTestClass().getOnlyConstructor().newInstance(this.fParameters);
}
private Object createTestUsingFieldInjection() throws Exception {
List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
if (annotatedFieldsByParameter.size() != this.fParameters.length) {
throw new Exception(
"Wrong number of parameters and @Parameter fields." + " @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + this.fParameters.length + ".");
}
Object testClassInstance = getTestClass().getJavaClass().newInstance();
for (FrameworkField each : annotatedFieldsByParameter) {
Field field = each.getField();
Parameter annotation = field.getAnnotation(Parameter.class);
int index = annotation.value();
try {
field.set(testClassInstance, this.fParameters[index]);
} catch (IllegalArgumentException iare) {
throw new Exception(
getTestClass().getName() + ": Trying to set " + field.getName() + " with the value " + this.fParameters[index] + " that is not the right type (" + this.fParameters[index].getClass()
.getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare);
}
}
return testClassInstance;
}
@Override
protected String getName() {
return this.fName;
}
@Override
protected String testName(final FrameworkMethod method) {
return method.getName() + getName();
}
@Override
protected void validateConstructor(final List<Throwable> errors) {
validateOnlyOneConstructor(errors);
if (fieldsAreAnnotated()) {
validateZeroArgConstructor(errors);
}
}
@Override
protected void validateFields(final List<Throwable> errors) {
super.validateFields(errors);
if (fieldsAreAnnotated()) {
List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
int[] usedIndices = new int[annotatedFieldsByParameter.size()];
for (FrameworkField each : annotatedFieldsByParameter) {
int index = each.getField().getAnnotation(Parameter.class).value();
if ((index < 0) || (index > (annotatedFieldsByParameter.size() - 1))) {
errors.add(new Exception(
"Invalid @Parameter value: " + index + ". @Parameter fields counted: " + annotatedFieldsByParameter.size() + ". Please use an index between 0 and " + (annotatedFieldsByParameter.size() - 1) + "."));
} else {
usedIndices[index]++;
}
}
for (int index = 0; index < usedIndices.length; index++) {
int numberOfUse = usedIndices[index];
if (numberOfUse == 0) {
errors.add(new Exception("@Parameter(" + index + ") is never used."));
} else if (numberOfUse > 1) {
errors.add(new Exception("@Parameter(" + index + ") is used more than once (" + numberOfUse + ")."));
}
}
}
}
@Override
protected Statement classBlock(final RunNotifier notifier) {
return childrenInvoker(notifier);
}
@Override
protected Annotation[] getRunnerAnnotations() {
return new Annotation[0];
}
}
private static final List<Runner> NO_RUNNERS = Collections.<Runner> emptyList();
private final ArrayList<Runner> runners = new ArrayList<Runner>();
/**
* Only called reflectively. Do not use programmatically.
*/
public Parameterized(final Class<?> klass) throws Throwable {
super(klass, NO_RUNNERS);
Parameters parameters = getParametersMethod().getAnnotation(Parameters.class);
createRunnersForParameters(allParameters(), parameters.name());
}
@Override
protected List<Runner> getChildren() {
return this.runners;
}
@SuppressWarnings("unchecked")
private Iterable<Object[]> allParameters() throws Throwable {
Object parameters = getParametersMethod().invokeExplosively(null);
if (parameters instanceof Iterable) {
return (Iterable<Object[]>) parameters;
} else {
throw parametersMethodReturnedWrongType();
}
}
private FrameworkMethod getParametersMethod() throws Exception {
List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(Parameters.class);
for (FrameworkMethod each : methods) {
if (each.isStatic() && each.isPublic()) {
return each;
}
}
throw new Exception("No public static parameters method on class " + getTestClass().getName());
}
private void createRunnersForParameters(final Iterable<Object[]> allParameters, final String namePattern) throws InitializationError, Exception {
try {
int i = 0;
for (Object[] parametersOfSingleTest : allParameters) {
String name = nameFor(namePattern, i, parametersOfSingleTest);
TestClassRunnerForParameters runner = new TestClassRunnerForParameters(getTestClass().getJavaClass(), parametersOfSingleTest, name);
this.runners.add(runner);
++i;
}
} catch (ClassCastException e) {
throw parametersMethodReturnedWrongType();
}
}
private String nameFor(final String namePattern, final int index, final Object[] parameters) {
String finalPattern = namePattern.replaceAll("\\{index\\}", Integer.toString(index));
String name = MessageFormat.format(finalPattern, parameters);
return "[" + sanitizeEscapeSequencesWithName(name) + "]";
}
private String sanitizeEscapeSequencesWithName(final String name) {
String result = name;
for (Map.Entry<Character, String> currentSequence : ESCAPE_SEQUENCES.entrySet()) {
result = result.replaceAll("" + currentSequence.getKey(), currentSequence.getValue());
}
return result;
}
private Exception parametersMethodReturnedWrongType() throws Exception {
String className = getTestClass().getName();
String methodName = getParametersMethod().getName();
String message = MessageFormat.format("{0}.{1}() must return an Iterable of arrays.", className, methodName);
return new Exception(message);
}
private List<FrameworkField> getAnnotatedFieldsByParameter() {
return getTestClass().getAnnotatedFields(Parameter.class);
}
private boolean fieldsAreAnnotated() {
return !getAnnotatedFieldsByParameter().isEmpty();
}
}
| epl-1.0 |
adolfosbh/cs2as | org.xtext.example.delphi/src-gen/org/xtext/example/delphi/tx/AbstractInvocation.java | 4339 | /**
* This file was copied and re-packaged automatically by
* org.xtext.example.delphi.build.GenerateCS2AST
* from
* ..\..\org.eclipse.qvtd\plugins\org.eclipse.qvtd.runtime\src\org\eclipse\qvtd\runtime\evaluation\AbstractInvocation.java
*
* Do not edit this file.
*/
/*******************************************************************************
* Copyright (c) 2013, 2016 Willink Transformations 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:
* E.D.Willink - Initial API and implementation
*******************************************************************************/
package org.xtext.example.delphi.tx;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.ocl.pivot.ids.TypeId;
import org.xtext.example.delphi.internal.tx.AbstractInvocationInternal;
/**
* AbstractInvocation provides the mandatory shared functionality of the intrusive blocked/waiting linked list functionality.
*/
public abstract class AbstractInvocation extends AbstractInvocationInternal
{
public abstract static class Incremental extends AbstractInvocation implements Invocation.Incremental
{
public static final @NonNull List<@NonNull Object> EMPTY_OBJECT_LIST = Collections.emptyList();
public static final @NonNull List<SlotState.@NonNull Incremental> EMPTY_SLOT_LIST = Collections.emptyList();
protected final @NonNull InvocationConstructor constructor;
protected final int sequence;
private Set<@NonNull Object> createdObjects = null;
private Set<SlotState.@NonNull Incremental> readSlots = null;
private Set<SlotState.@NonNull Incremental> writeSlots = null;
protected Incremental(InvocationConstructor.@NonNull Incremental constructor) {
super(constructor);
this.constructor = constructor;
this.sequence = constructor.nextSequence();
}
@Override
public void addCreatedObject(@NonNull Object createdObject) {
if (createdObjects == null) {
createdObjects = new HashSet<>();
}
createdObjects.add(createdObject);
}
@Override
public void addReadSlot(SlotState.@NonNull Incremental readSlot) {
if (readSlots == null) {
readSlots = new HashSet<>();
}
readSlots.add(readSlot);
readSlot.addTargetInternal(this);
}
@Override
public void addWriteSlot(SlotState.@NonNull Incremental writeSlot) {
if (writeSlots == null) {
writeSlots = new HashSet<>();
}
writeSlots.add(writeSlot);
writeSlot.addSourceInternal(this);
}
protected @NonNull Connection createConnection(@NonNull String name, @NonNull TypeId typeId, boolean isStrict) {
return constructor.getInterval().createConnection(name, typeId, isStrict);
}
protected Connection.@NonNull Incremental createIncrementalConnection(@NonNull String name, @NonNull TypeId typeId, boolean isStrict) {
return constructor.getInterval().createIncrementalConnection(name, typeId, isStrict);
}
@Override
public @NonNull Iterable<@NonNull Object> getCreatedObjects() {
return createdObjects != null ? createdObjects : EMPTY_OBJECT_LIST;
}
@SuppressWarnings("null")
@Override
public @NonNull String getName() {
InvocationConstructor constructor2 = constructor; // May be invoked from toString() during constructor debugging
return (constructor2 != null ? constructor2.getName() : "null") + "-" + sequence;
}
@Override
public @NonNull Iterable<SlotState.@NonNull Incremental> getReadSlots() {
return readSlots != null ? readSlots : EMPTY_SLOT_LIST;
}
@Override
public @NonNull Iterable<SlotState.@NonNull Incremental> getWriteSlots() {
return writeSlots != null ? writeSlots : EMPTY_SLOT_LIST;
}
@Override
public @NonNull String toString() {
return getName();
}
}
protected AbstractInvocation(@NonNull InvocationConstructor constructor) {
super(constructor.getInterval());
}
@Override
public <R> R accept(@NonNull ExecutionVisitor<R> visitor) {
return visitor.visitInvocation(this);
}
@Override
public @NonNull String getName() {
return toString().replace("@", "\n@");
}
} | epl-1.0 |
rahulopengts/myhome | bundles/model/org.openhab.model.sitemap/src/org/openhab/model/sitemap/internal/SitemapProviderImpl.java | 1935 | /**
* Copyright (c) 2010-2015, openHAB.org 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.openhab.model.sitemap.internal;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.openhab.model.core.ModelRepository;
import org.openhab.model.sitemap.Sitemap;
import org.openhab.model.sitemap.SitemapProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides access to the sitemap model files.
*
* @author Kai Kreuzer
*
*/
public class SitemapProviderImpl implements SitemapProvider {
private static final Logger logger = LoggerFactory.getLogger(SitemapProviderImpl.class);
private ModelRepository modelRepo = null;
public void setModelRepository(ModelRepository modelRepo) {
this.modelRepo = modelRepo;
}
public void unsetModelRepository(ModelRepository modelRepo) {
this.modelRepo = null;
}
/* (non-Javadoc)
* @see org.openhab.model.sitemap.internal.SitemapProvider#getSitemap(java.lang.String)
*/
public Sitemap getSitemap(String sitemapName) {
if(modelRepo!=null) {
//System.out.println("\n***SiteMapProviderImpl->getSitemap->"+modelRepo.getName());
Sitemap sitemap = (Sitemap) modelRepo.getModel(sitemapName + ".sitemap");
if(sitemap!=null) {
return sitemap;
} else {
logger.debug("Sitemap {} can not be found", sitemapName);
return null;
}
} else {
logger.debug("No model repository service is available");
return null;
}
}
public void iterate(EObject sitemap){
final TreeIterator<EObject> contentIterator=sitemap.eAllContents();
while (contentIterator.hasNext()) {
final EObject next=contentIterator.next();
}
}
}
| epl-1.0 |
dhuebner/che | wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/project/server/DtoConverter.java | 11509 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.project.server;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.model.project.SourceStorage;
import org.eclipse.che.api.core.model.project.type.Attribute;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.api.core.util.LinksHelper;
import org.eclipse.che.api.project.server.importer.ProjectImporter;
import org.eclipse.che.api.project.server.type.ProjectTypeDef;
import org.eclipse.che.api.project.shared.dto.AttributeDto;
import org.eclipse.che.api.project.shared.dto.ItemReference;
import org.eclipse.che.api.project.shared.dto.ProjectImporterDescriptor;
import org.eclipse.che.api.project.shared.dto.ProjectTypeDto;
import org.eclipse.che.api.project.shared.dto.ValueDto;
import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto;
import org.eclipse.che.api.workspace.shared.dto.ProjectProblemDto;
import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import static javax.ws.rs.HttpMethod.DELETE;
import static javax.ws.rs.HttpMethod.GET;
import static javax.ws.rs.HttpMethod.PUT;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_CHILDREN;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_DELETE;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_GET_CONTENT;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_TREE;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_UPDATE_CONTENT;
import static org.eclipse.che.api.project.server.Constants.LINK_REL_UPDATE_PROJECT;
import static org.eclipse.che.dto.server.DtoFactory.newDto;
/**
* Helper methods for convert server essentials to DTO and back.
*
* @author andrew00x
*/
public class DtoConverter {
private DtoConverter() {
}
public static ProjectTypeDto toTypeDefinition(ProjectTypeDef projectType) {
final ProjectTypeDto definition = newDto(ProjectTypeDto.class).withId(projectType.getId())
.withDisplayName(projectType.getDisplayName())
.withPrimaryable(projectType.isPrimaryable())
.withMixable(projectType.isMixable())
.withAncestors(projectType.getAncestors());
final List<AttributeDto> typeAttributes = new ArrayList<>();
for (Attribute attr : projectType.getAttributes()) {
ValueDto valueDto = newDto(ValueDto.class);
if (attr.getValue() != null) {
valueDto.withList(attr.getValue().getList());
}
typeAttributes.add(newDto(AttributeDto.class).withName(attr.getName())
.withDescription(attr.getDescription())
.withRequired(attr.isRequired())
.withVariable(attr.isVariable())
.withValue(valueDto));
}
definition.withAttributes(typeAttributes).withParents(projectType.getParents());
return definition;
}
public static ProjectImporterDescriptor toImporterDescriptor(ProjectImporter importer) {
return newDto(ProjectImporterDescriptor.class).withId(importer.getId())
.withInternal(importer.isInternal())
.withDescription(importer.getDescription() != null ? importer.getDescription()
: "description not found")
.withCategory(importer.getCategory().getValue());
}
public static ItemReference toItemReference(FileEntry file, String workspace, UriBuilder uriBuilder)
throws ServerException {
return newDto(ItemReference.class).withName(file.getName())
.withPath(file.getPath().toString())
.withType("file")
.withAttributes(file.getAttributes())
.withModified(file.getModified())
.withContentLength(file.getVirtualFile().getLength())
.withLinks(generateFileLinks(file, workspace, uriBuilder));
}
public static ItemReference toItemReference(FolderEntry folder, String workspace, UriBuilder uriBuilder) {
return newDto(ItemReference.class).withName(folder.getName())
.withPath(folder.getPath().toString())
.withType(folder.isProject() ? "project" : "folder")
.withAttributes(folder.getAttributes())
.withModified(folder.getModified())
.withLinks(generateFolderLinks(folder, workspace, uriBuilder));
}
/**
* The method tries to provide as much as possible information about project.If get error then save information about error
* with 'problems' field in ProjectConfigDto.
*
* @param project
* project from which we need get information
* @param serviceUriBuilder
* service for building URI
* @return an instance of {@link ProjectConfigDto}
*/
public static ProjectConfigDto toProjectConfig(RegisteredProject project, String workspace, UriBuilder serviceUriBuilder) {
ProjectConfigDto projectConfigDto = newDto(ProjectConfigDto.class);
projectConfigDto.withName(project.getName())
.withPath(project.getPath())
.withDescription(project.getDescription());
List <String> mixins = project.getMixinTypes().keySet().stream().collect(Collectors.toList());
projectConfigDto.withMixins(mixins);
projectConfigDto.withAttributes(project.getAttributes());
projectConfigDto.withType(project.getProjectType().getId());
projectConfigDto.withSource(toSourceDto(project.getSource()));
for (RegisteredProject.Problem p : project.getProblems()) {
ProjectProblemDto projectProblem = newDto(ProjectProblemDto.class).withCode(p.code).withMessage(p.message);
projectConfigDto.getProblems().add(projectProblem);
}
if (serviceUriBuilder != null) {
projectConfigDto.withLinks(generateProjectLinks(project, workspace, serviceUriBuilder));
}
return projectConfigDto;
}
private static SourceStorageDto toSourceDto(SourceStorage sourceStorage) {
SourceStorageDto storageDto = newDto(SourceStorageDto.class);
if (sourceStorage != null) {
storageDto.withType(sourceStorage.getType())
.withLocation(sourceStorage.getLocation())
.withParameters(sourceStorage.getParameters());
}
return storageDto;
}
private static List<Link> generateProjectLinks(RegisteredProject project, String workspace, UriBuilder uriBuilder) {
final List<Link> links = new LinkedList<>();
if (project.getBaseFolder() != null) { //here project can be not imported so base directory not exist on file system but project exist in workspace config
links.addAll(generateFolderLinks(project.getBaseFolder(), workspace, uriBuilder));
}
final String relPath = project.getPath().substring(1);
links.add(LinksHelper.createLink(PUT,
uriBuilder.clone()
.path(ProjectService.class, "updateProject")
.build(workspace, relPath)
.toString(),
APPLICATION_JSON,
APPLICATION_JSON,
LINK_REL_UPDATE_PROJECT
));
return links;
}
private static List<Link> generateFolderLinks(FolderEntry folder, String workspace, UriBuilder uriBuilder) {
final List<Link> links = new LinkedList<>();
final String relPath = folder.getPath().toString().substring(1);
// links.add(LinksHelper.createLink(GET,
// uriBuilder.clone().path(ProjectService.class, "exportZip").build(workspace, relPath).toString(),
// ExtMediaType.APPLICATION_ZIP, LINK_REL_EXPORT_ZIP));
links.add(LinksHelper.createLink(GET,
uriBuilder.clone().path(ProjectService.class, "getChildren").build(workspace, relPath).toString(),
APPLICATION_JSON, LINK_REL_CHILDREN));
links.add(LinksHelper.createLink(GET,
uriBuilder.clone().path(ProjectService.class, "getTree").build(workspace, relPath).toString(),
null, APPLICATION_JSON, LINK_REL_TREE)
);
links.add(LinksHelper.createLink(DELETE,
uriBuilder.clone().path(ProjectService.class, "delete").build(workspace, relPath).toString(),
LINK_REL_DELETE));
return links;
}
private static List<Link> generateFileLinks(FileEntry file, String workspace, UriBuilder uriBuilder) {
final List<Link> links = new LinkedList<>();
final String relPath = file.getPath().toString().substring(1);
links.add(LinksHelper.createLink(GET, uriBuilder.clone().path(ProjectService.class, "getFile").build(workspace, relPath).toString(),
null, null, LINK_REL_GET_CONTENT));
links.add(LinksHelper.createLink(PUT,
uriBuilder.clone().path(ProjectService.class, "updateFile").build(workspace, relPath).toString(),
MediaType.WILDCARD, null, LINK_REL_UPDATE_CONTENT));
links.add(LinksHelper.createLink(DELETE,
uriBuilder.clone().path(ProjectService.class, "delete").build(workspace, relPath).toString(),
LINK_REL_DELETE));
return links;
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/namespaces/DifferentNamespacesTestCases.java | 3331 | /*******************************************************************************
* Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Denise Smith - 2.4
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.json.namespaces;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.PropertyException;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.eclipse.persistence.testing.jaxb.json.JSONMarshalUnmarshalTestCases;
public class DifferentNamespacesTestCases extends JSONMarshalUnmarshalTestCases{
private final static String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/json/namespaces/person.json";
private final static String JSON_WRITE_RESOURCE = "org/eclipse/persistence/testing/jaxb/json/namespaces/person_different.json";
public DifferentNamespacesTestCases(String name) throws Exception {
super(name);
setControlJSON(JSON_RESOURCE);
setWriteControlJSON(JSON_WRITE_RESOURCE);
setClasses(new Class[]{Person.class});
}
protected Object getControlObject() {
Person p = new Person();
p.setId(10);
p.setFirstName("Jill");
p.setLastName("MacDonald");
List<String> middleNames = new ArrayList<String>();
middleNames.add("Jane");
middleNames.add("Janice");
p.setMiddleNames(middleNames);
Address addr = new Address();
addr.setStreet("The Street");
addr.setCity("Ottawa");
p.setAddress(addr);
return p;
}
public void setUp() throws Exception{
super.setUp();
Map<String, String> marshalNamespaceMap = new HashMap<String, String>();
marshalNamespaceMap.put("namespace0", "aaa");
marshalNamespaceMap.put("namespace1", "bbb");
marshalNamespaceMap.put("namespace2", "ccc");
marshalNamespaceMap.put("namespace3", "ddd");
Map<String, String> unmarshalNamespaceMap = new HashMap<String, String>();
unmarshalNamespaceMap.put("namespace0", "ns0");
unmarshalNamespaceMap.put("namespace1", "ns1");
unmarshalNamespaceMap.put("namespace2", "ns2");
unmarshalNamespaceMap.put("namespace3", "ns3");
try{
jsonMarshaller.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER, marshalNamespaceMap);
jsonUnmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, unmarshalNamespaceMap);
}catch(PropertyException e){
e.printStackTrace();
fail("An error occurred setting properties during setup.");
}
}
public Map getProperties(){
Map props = new HashMap();
props.put(JAXBContextProperties.JSON_ATTRIBUTE_PREFIX, "@");
return props;
}
}
| epl-1.0 |
BOTlibre/BOTlibre | botlibre-web/source/org/botlibre/web/rest/IssueTrackerConfig.java | 1868 | /******************************************************************************
*
* Copyright 2013-2019 Paphus Solutions 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.
*
******************************************************************************/
package org.botlibre.web.rest;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.botlibre.util.Utils;
import org.botlibre.web.admin.AccessMode;
import org.botlibre.web.bean.IssueTrackerBean;
import org.botlibre.web.bean.LoginBean;
/**
* DTO for XML IssueTracker config.
*/
@XmlRootElement(name="issuetracker")
@XmlAccessorType(XmlAccessType.FIELD)
public class IssueTrackerConfig extends WebMediumConfig {
@XmlAttribute
public String createAccessMode;
@XmlAttribute
public String issues;
public String getCreateAccessMode() {
if (this.createAccessMode == null || this.createAccessMode.isEmpty()) {
return AccessMode.Everyone.name();
}
return this.createAccessMode;
}
public IssueTrackerBean getBean(LoginBean loginBean) {
return loginBean.getBean(IssueTrackerBean.class);
}
public void sanitize() {
createAccessMode = Utils.sanitize(createAccessMode);
issues = Utils.sanitize(issues);
}
}
| epl-1.0 |
NABUCCO/org.nabucco.framework.base | org.nabucco.framework.base.facade.datatype/src/main/man/org/nabucco/framework/base/facade/datatype/NByteArray.java | 4346 | /*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), 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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.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.
*/
package org.nabucco.framework.base.facade.datatype;
import java.util.Arrays;
/**
* NByteArray
*
* @author Nicolas Moser, PRODYNA AG
*/
public abstract class NByteArray extends BasetypeSupport implements Basetype, Comparable<NByteArray> {
private static final long serialVersionUID = 1L;
private byte[] value;
/**
* Default constructor
*/
public NByteArray() {
this(null);
}
/**
* Constructor initializing the value.
*
* @param value
* the value to initialize
*/
public NByteArray(byte[] value) {
super(BasetypeType.BYTE_ARRAY);
this.value = value;
}
@Override
public byte[] getValue() {
return value;
}
@Override
public String getValueAsString() {
if (this.value == null) {
return null;
}
return new String(this.value);
}
@Override
public void setValue(Object value) throws IllegalArgumentException {
if (value != null && !(value instanceof byte[])) {
throw new IllegalArgumentException("Cannot set value '" + value + "' to NByteArray.");
}
this.setValue((byte[]) value);
}
/**
* Setter for the byte[] value.
*
* @param value
* the byte[] value to set.
*/
public void setValue(byte[] value) {
this.value = value;
}
/**
* Returns a <code>String</code> object representing this <code>NByteArray</code>'s value.
*
* @return a string representation of the value of this object in base 10.
*/
@Override
public String toString() {
if (this.value == null) {
return null;
}
return new String(this.value);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof NByteArray))
return false;
NByteArray other = (NByteArray) obj;
if (!Arrays.equals(this.value, other.value))
return false;
return true;
}
@Override
public int compareTo(NByteArray other) {
if (other == null) {
return -1;
}
if (getValue() == null) {
if (other.getValue() == null) {
return 0;
}
return 1;
}
if (other.getValue() == null) {
return -1;
}
if (this.value.length != other.value.length) {
if (this.value.length > other.value.length) {
return 1;
}
if (this.value.length < other.value.length) {
return -1;
}
}
for (int i = 0; i < this.value.length; i++) {
if (this.value[i] != other.value[i]) {
if (this.value[i] > other.value[i]) {
return 1;
}
if (this.value[i] < other.value[i]) {
return -1;
}
}
}
return 0;
}
@Override
public abstract NByteArray cloneObject();
/**
* Clones the properties of this basetype into the given basetype.
*
* @param clone
* the cloned basetype
*/
protected void cloneObject(NByteArray clone) {
if (this.value != null) {
clone.value = Arrays.copyOf(this.value, this.value.length);
}
}
}
| epl-1.0 |
DavidGutknecht/elexis-3-base | bundles/ch.elexis.docbox.ws.client/src-gen/ch/docbox/ws/cdachservicesv2/GetInboxClinicalDocuments.java | 1395 |
package ch.docbox.ws.cdachservicesv2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.hl7.v3.CE;
/**
* <p>Java-Klasse für anonymous complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="code" type="{urn:hl7-org:v3}CE" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"code"
})
@XmlRootElement(name = "getInboxClinicalDocuments")
public class GetInboxClinicalDocuments {
protected CE code;
/**
* Ruft den Wert der code-Eigenschaft ab.
*
* @return
* possible object is
* {@link CE }
*
*/
public CE getCode() {
return code;
}
/**
* Legt den Wert der code-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link CE }
*
*/
public void setCode(CE value) {
this.code = value;
}
}
| epl-1.0 |
DavidGutknecht/elexis-3-base | bundles/at.medevit.elexis.tarmed.model/src-gen/ch/fd/invoice440/request/CompanyType.java | 5377 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.03.18 at 03:48:09 PM CET
//
package ch.fd.invoice440.request;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for companyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="companyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="companyname" type="{http://www.forum-datenaustausch.ch/invoice}stringType1_35"/>
* <element name="department" type="{http://www.forum-datenaustausch.ch/invoice}stringType1_35" minOccurs="0"/>
* <element name="subaddressing" type="{http://www.forum-datenaustausch.ch/invoice}stringType1_35" minOccurs="0"/>
* <element name="postal" type="{http://www.forum-datenaustausch.ch/invoice}postalAddressType"/>
* <element name="telecom" type="{http://www.forum-datenaustausch.ch/invoice}telecomAddressType" minOccurs="0"/>
* <element name="online" type="{http://www.forum-datenaustausch.ch/invoice}onlineAddressType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "companyType", propOrder = {
"companyname",
"department",
"subaddressing",
"postal",
"telecom",
"online"
})
public class CompanyType {
@XmlElement(required = true)
protected String companyname;
protected String department;
protected String subaddressing;
@XmlElement(required = true)
protected PostalAddressType postal;
protected TelecomAddressType telecom;
protected OnlineAddressType online;
/**
* Gets the value of the companyname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCompanyname() {
return companyname;
}
/**
* Sets the value of the companyname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCompanyname(String value) {
this.companyname = value;
}
/**
* Gets the value of the department property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDepartment() {
return department;
}
/**
* Sets the value of the department property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDepartment(String value) {
this.department = value;
}
/**
* Gets the value of the subaddressing property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubaddressing() {
return subaddressing;
}
/**
* Sets the value of the subaddressing property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubaddressing(String value) {
this.subaddressing = value;
}
/**
* Gets the value of the postal property.
*
* @return
* possible object is
* {@link PostalAddressType }
*
*/
public PostalAddressType getPostal() {
return postal;
}
/**
* Sets the value of the postal property.
*
* @param value
* allowed object is
* {@link PostalAddressType }
*
*/
public void setPostal(PostalAddressType value) {
this.postal = value;
}
/**
* Gets the value of the telecom property.
*
* @return
* possible object is
* {@link TelecomAddressType }
*
*/
public TelecomAddressType getTelecom() {
return telecom;
}
/**
* Sets the value of the telecom property.
*
* @param value
* allowed object is
* {@link TelecomAddressType }
*
*/
public void setTelecom(TelecomAddressType value) {
this.telecom = value;
}
/**
* Gets the value of the online property.
*
* @return
* possible object is
* {@link OnlineAddressType }
*
*/
public OnlineAddressType getOnline() {
return online;
}
/**
* Sets the value of the online property.
*
* @param value
* allowed object is
* {@link OnlineAddressType }
*
*/
public void setOnline(OnlineAddressType value) {
this.online = value;
}
}
| epl-1.0 |
sleshchenko/che | wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/search/server/impl/SearchResultEntry.java | 1751 | /*
* Copyright (c) 2012-2018 Red Hat, 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:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.search.server.impl;
import java.util.List;
import org.eclipse.che.api.search.server.OffsetData;
/** Single item in {@code SearchResult}. */
public class SearchResultEntry {
private final String filePath;
private final List<OffsetData> data;
public SearchResultEntry(String filePath, List<OffsetData> data) {
this.filePath = filePath;
this.data = data;
}
public List<OffsetData> getData() {
return data;
}
/** Path of file that matches the search criteria. */
public String getFilePath() {
return filePath;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SearchResultEntry)) {
return false;
}
SearchResultEntry that = (SearchResultEntry) o;
if (getFilePath() != null
? !getFilePath().equals(that.getFilePath())
: that.getFilePath() != null) {
return false;
}
return getData() != null ? getData().equals(that.getData()) : that.getData() == null;
}
@Override
public int hashCode() {
int result = getFilePath() != null ? getFilePath().hashCode() : 0;
result = 31 * result + (getData() != null ? getData().hashCode() : 0);
return result;
}
@Override
public String toString() {
return "SearchResultEntry{" + "filePath='" + filePath + '\'' + ", data=" + data + '}';
}
}
| epl-1.0 |
guhanjie/test-for-apply | src/test/TestString.java | 642 | package test;
/**
* StringÊÇ×Ö·û´®¶ÔÏóÀ࣬ÇÒÊDz»¿É±äµÄ¡£
* ËüÓÐÒ»¸öºÜÖØÒªµÄÌØÐÔ£¬¾ÍÊÇÔÚ¶¨Òå×Ö·û´®³£Á¿Ê±£¬ÓÃÁËÒ»¸ö»º³å³Ø£¡
* @author gu
*
*/
public class TestString {
public static void main(String[] args) {
String str1 = new String("abc"); //·²ÊÇnew³öÀ´µÄ¶ÔÏó¶¼ÊÇÔڶѿռäÖпª±ÙеÄÄÚ´æ
String str2 = "abc"; //ÕâÀﶨÒåÁËÒ»¸ö×Ö·û´®³£Á¿£¬ÏµÍ³»áÈ¥JVMµ±Ç°×Ö·û´®»º³å³ØÖÐÕÒÓÐÎ޸öÔÏó£¬Ã»ÓУ¬Ôò´´½¨Ò»¸ö¸Ã´®
String str3 = "abc"; //Èç¹ûÓУ¬ÔòÖ±½Ó½«´æÔÚÓÚ×Ö·û´®»º³å³ØÖеÄÊý¾Ý¸ø³öÀ´£¬Ò²¾ÍÊÇÖ¸Ïòͬһ¸ö¶ÔÏóµØÖ·
System.out.println(str1 == str2);
System.out.println(str2 == str3);
}
} | epl-1.0 |
bradsdavis/windup | graph/tests/src/test/java/org/jboss/windup/graph/typedgraph/TestFooSubModel.java | 829 | package org.jboss.windup.graph.typedgraph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.frames.Property;
import com.tinkerpop.frames.modules.javahandler.JavaHandler;
import com.tinkerpop.frames.modules.javahandler.JavaHandlerContext;
import com.tinkerpop.frames.modules.typedgraph.TypeValue;
/**
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
@TypeValue("FooSub")
public interface TestFooSubModel extends TestFooModel
{
@Property("fooProperty")
public String getFoo();
@Property("fooProperty")
public void setFoo(String foo);
@Override
@JavaHandler
public String testJavaMethod();
abstract class Impl implements TestFooSubModel, JavaHandlerContext<Vertex>
{
public String testJavaMethod()
{
return "subclass";
}
}
}// class
| epl-1.0 |
GazeboHub/ghub-portal-doc | doc/modelio/GHub Portal/mda/JavaDesigner/res/java/tomcat/java/org/apache/tomcat/util/net/SocketStatus.java | 992 | /*
* 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.tomcat.util.net;
/**
* Someone, please change the enum name.
*
* @author remm
*/
public enum SocketStatus {
OPEN, STOP, TIMEOUT, DISCONNECT, ERROR
}
| epl-1.0 |
smeup/asup | org.smeup.sys.db.core/src/org/smeup/sys/db/core/QTableProvider.java | 865 | /**
* Copyright (c) 2012, 2016 Sme.UP 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.smeup.sys.db.core;
import org.eclipse.datatools.modelbase.sql.tables.Table;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Table Provider</b></em>'.
* <!-- end-user-doc -->
*
*
* @see org.smeup.sys.db.core.QDatabaseCorePackage#getTableProvider()
* @model interface="true" abstract="true"
* @generated
*/
public interface QTableProvider {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model required="true"
* @generated
*/
Table getTable(String schema, String table);
} // QTableProvider
| epl-1.0 |
codenvy/che-core | platform-api/che-core-api-dto/src/main/java/org/eclipse/che/dto/generator/DtoImpl.java | 17115 | /*******************************************************************************
* Copyright (c) 2012-2014 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.dto.generator;
import org.eclipse.che.dto.shared.CompactJsonDto;
import org.eclipse.che.dto.shared.DTO;
import org.eclipse.che.dto.shared.DelegateTo;
import org.eclipse.che.dto.shared.JsonFieldName;
import org.eclipse.che.dto.shared.SerializationIndex;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Abstract base class for the source generating template for a single DTO. */
abstract class DtoImpl {
protected static final String COPY_JSONS_PARAM = "copyJsons";
private final Class<?> dtoInterface;
private final DtoTemplate enclosingTemplate;
private final boolean compactJson;
private final String implClassName;
private final List<Method> dtoMethods;
DtoImpl(DtoTemplate enclosingTemplate, Class<?> dtoInterface) {
this.enclosingTemplate = enclosingTemplate;
this.dtoInterface = dtoInterface;
this.implClassName = dtoInterface.getSimpleName() + "Impl";
this.compactJson = DtoTemplate.implementsInterface(dtoInterface, CompactJsonDto.class);
this.dtoMethods = ImmutableList.copyOf(calcDtoMethods());
}
protected boolean isCompactJson() {
return compactJson;
}
public Class<?> getDtoInterface() {
return dtoInterface;
}
public DtoTemplate getEnclosingTemplate() {
return enclosingTemplate;
}
protected String getJavaFieldName(String getterName) {
String fieldName;
if (getterName.startsWith("get")) {
fieldName = getterName.substring(3);
} else {
// starts with "is", see method '#ignoreMethod(Method)'
fieldName = getterName.substring(2);
}
return normalizeIdentifier(Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1));
}
private String normalizeIdentifier(String fieldName) {
// use $ prefix according to http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8
switch (fieldName) {
case "default":
fieldName = "$" + fieldName;
break;
// add other keywords here
}
return fieldName;
}
private String getCamelCaseName(String fieldName) {
// see normalizeIdentifier method
if (fieldName.charAt(0) == '$') {
fieldName = fieldName.substring(1);
}
return Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
}
protected String getImplClassName() {
return implClassName;
}
protected String getSetterName(String fieldName) {
return "set" + getCamelCaseName(fieldName);
}
protected String getWithName(String fieldName) {
return "with" + getCamelCaseName(fieldName);
}
protected String getListAdderName(String fieldName) {
return "add" + getCamelCaseName(fieldName);
}
protected String getMapPutterName(String fieldName) {
return "put" + getCamelCaseName(fieldName);
}
protected String getClearName(String fieldName) {
return "clear" + getCamelCaseName(fieldName);
}
protected String getEnsureName(String fieldName) {
return "ensure" + getCamelCaseName(fieldName);
}
/**
* Get the canonical name of the field by deriving it from a getter method's name.
*/
protected String getFieldNameFromGetterName(String getterName) {
String fieldName;
if (getterName.startsWith("get")) {
fieldName = getterName.substring(3);
} else {
// starts with "is", see method '#ignoreMethod(Method)'
fieldName = getterName.substring(2);
}
return Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1);
}
/**
* Get the name of the JSON field that corresponds to the given getter method in a DTO-annotated type.
*/
protected String getJsonFieldName(Method getterMethod) {
// First, check if a custom field name is defined for the getter
JsonFieldName fieldNameAnn = getterMethod.getAnnotation(JsonFieldName.class);
if (fieldNameAnn != null) {
String customFieldName = fieldNameAnn.value();
if (customFieldName != null && !customFieldName.isEmpty()) {
return customFieldName;
}
}
// If no custom name is given for the field, deduce it from the camel notation
return getFieldNameFromGetterName(getterMethod.getName());
}
/**
* Our super interface may implement some other interface (or not). We need to know because if it does then we need to directly extend
* said super interfaces impl class.
*/
protected Class<?> getSuperDtoInterface(Class<?> dto) {
Class<?>[] superInterfaces = dto.getInterfaces();
if (superInterfaces.length > 0) {
for (Class<?> superInterface : superInterfaces) {
if (superInterface.isAnnotationPresent(DTO.class)) {
return superInterface;
}
}
}
return null;
}
protected List<Method> getDtoGetters(Class<?> dto) {
final Map<String, Method> getters = new HashMap<>();
if (enclosingTemplate.isDtoInterface(dto)) {
addDtoGetters(dto, getters);
addSuperGetters(dto, getters);
}
return new ArrayList<>(getters.values());
}
/**
* Get the names of all the getters in the super DTO interface and upper ancestors.
*/
protected Set<String> getSuperGetterNames(Class<?> dto) {
final Map<String, Method> getters = new HashMap<>();
Class<?> superDto = getSuperDtoInterface(dto);
if (superDto != null) {
addDtoGetters(superDto, getters);
addSuperGetters(superDto, getters);
}
return getters.keySet();
}
/**
* Adds all getters from parent <b>NOT DTO</b> interfaces for given {@code dto} interface.
* Does not add method when it is already present in getters map.
*/
private void addSuperGetters(Class<?> dto, Map<String, Method> getters) {
for (Class<?> superInterface : dto.getInterfaces()) {
if (!superInterface.isAnnotationPresent(DTO.class)) {
for (Method method : superInterface.getDeclaredMethods()) {
//when method is already present in map then child interface
//overrides it, which means that it should not be put into getters
if (isDtoGetter(method) && !getters.containsKey(method.getName())) {
getters.put(method.getName(), method);
}
}
addSuperGetters(superInterface, getters);
}
}
}
protected List<Method> getInheritedDtoGetters(Class<?> dto) {
List<Method> getters = new ArrayList<>();
if (enclosingTemplate.isDtoInterface(dto)) {
Class<?> superInterface = getSuperDtoInterface(dto);
while (superInterface != null) {
addDtoGetters(superInterface, getters);
superInterface = getSuperDtoInterface(superInterface);
}
addDtoGetters(dto, getters);
}
return getters;
}
private void addDtoGetters(Class<?> dto, Map<String, Method> getters) {
for (Method method : dto.getDeclaredMethods()) {
if (!method.isDefault() && isDtoGetter(method)) {
getters.put(method.getName(), method);
}
}
}
private void addDtoGetters(Class<?> dto, List<Method> getters) {
for (Method method : dto.getDeclaredMethods()) {
if (!method.isDefault() && isDtoGetter(method)) {
getters.add(method);
}
}
}
/** Check is specified method is DTO getter. */
protected boolean isDtoGetter(Method method) {
if (method.isAnnotationPresent(DelegateTo.class)) {
return false;
}
String methodName = method.getName();
if ((methodName.startsWith("get") || methodName.startsWith("is")) && method.getParameterTypes().length == 0) {
if (methodName.startsWith("is") && methodName.length() > 2) {
return method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class;
}
return methodName.length() > 3;
}
return false;
}
/** Tests whether or not a given generic type is allowed to be used as a generic. */
protected static boolean isWhitelisted(Class<?> genericType) {
return DtoTemplate.jreWhitelist.contains(genericType);
}
/** Tests whether or not a given return type is a number primitive or its wrapper type. */
protected static boolean isNumber(Class<?> returnType) {
final Class<?>[] numericTypes = {int.class, long.class, short.class, float.class, double.class, byte.class,
Integer.class, Long.class, Short.class, Float.class, Double.class, Byte.class};
for (Class<?> standardPrimitive : numericTypes) {
if (returnType.equals(standardPrimitive)) {
return true;
}
}
return false;
}
/** Tests whether or not a given return type is a boolean primitive or its wrapper type. */
protected static boolean isBoolean(Class<?> returnType) {
return returnType.equals(Boolean.class) || returnType.equals(boolean.class);
}
protected static String getPrimitiveName(Class<?> returnType) {
if (returnType.equals(Integer.class) || returnType.equals(int.class)) {
return "int";
} else if (returnType.equals(Long.class) || returnType.equals(long.class)) {
return "long";
} else if (returnType.equals(Short.class) || returnType.equals(short.class)) {
return "short";
} else if (returnType.equals(Float.class) || returnType.equals(float.class)) {
return "float";
} else if (returnType.equals(Double.class) || returnType.equals(double.class)) {
return "double";
} else if (returnType.equals(Byte.class) || returnType.equals(byte.class)) {
return "byte";
} else if (returnType.equals(Boolean.class) || returnType.equals(boolean.class)) {
return "boolean";
} else if (returnType.equals(Character.class) || returnType.equals(char.class)) {
return "char";
}
throw new IllegalArgumentException("Unknown wrapper class type.");
}
/** Tests whether or not a given return type is a java.util.List. */
public static boolean isList(Class<?> returnType) {
return returnType.equals(List.class);
}
/** Tests whether or not a given return type is a java.util.Map. */
public static boolean isMap(Class<?> returnType) {
return returnType.equals(Map.class);
}
public static boolean isAny(Class<?> returnType) {
return returnType.equals(Object.class);
}
/**
* Expands the type and its first generic parameter (which can also have a first generic parameter (...)).
* <p/>
* For example, JsonArray<JsonStringMap<JsonArray<SomeDto>>> would produce [JsonArray, JsonStringMap, JsonArray,
* SomeDto].
*/
public static List<Type> expandType(Type curType) {
List<Type> types = new LinkedList<>();
do {
types.add(curType);
if (curType instanceof ParameterizedType) {
Type[] genericParamTypes = ((ParameterizedType)curType).getActualTypeArguments();
Type rawType = ((ParameterizedType)curType).getRawType();
boolean map = rawType instanceof Class<?> && rawType == Map.class;
if (!map && genericParamTypes.length != 1) {
throw new IllegalStateException("Multiple type parameters are not supported (neither are zero type parameters)");
}
Type genericParamType = map ? genericParamTypes[1] : genericParamTypes[0];
if (genericParamType instanceof Class<?>) {
Class<?> genericParamTypeClass = (Class<?>)genericParamType;
if (isWhitelisted(genericParamTypeClass)) {
assert genericParamTypeClass.equals(
String.class) : "For JSON serialization there can be only strings or DTO types. ";
}
}
curType = genericParamType;
} else {
if (curType instanceof Class) {
Class<?> clazz = (Class<?>)curType;
if (isList(clazz) || isMap(clazz)) {
throw new DtoTemplate.MalformedDtoInterfaceException(
"JsonArray and JsonStringMap MUST have a generic type specified (and no... ? doesn't cut it!).");
}
}
curType = null;
}
} while (curType != null);
return types;
}
public static Class<?> getRawClass(Type type) {
return (Class<?>)((type instanceof ParameterizedType) ? ((ParameterizedType)type).getRawType() : type);
}
/**
* Returns public methods specified in DTO interface.
* <p/>
* <p>For compact DTO (see {@link org.eclipse.che.dto.shared.CompactJsonDto}) methods are ordered corresponding to {@link
* org.eclipse.che.dto.shared.SerializationIndex} annotation.
* <p/>
* <p>Gaps in index sequence are filled with {@code null}s.
*/
protected List<Method> getDtoMethods() {
return dtoMethods;
}
private Method[] calcDtoMethods() {
if (!compactJson) {
return dtoInterface.getMethods();
}
Map<Integer, Method> methodsMap = new HashMap<>();
int maxIndex = 0;
for (Method method : dtoInterface.getMethods()) {
SerializationIndex serializationIndex = method.getAnnotation(SerializationIndex.class);
Preconditions.checkNotNull(serializationIndex, "Serialization index is not specified for %s in %s",
method.getName(), dtoInterface.getSimpleName());
// "53" is the number of bits in JS integer.
// This restriction will allow to add simple bit-field
// "serialization-skipping-list" in the future.
int index = serializationIndex.value();
Preconditions.checkState(index > 0 && index <= 53, "Serialization index out of range [1..53] for %s in %s",
method.getName(), dtoInterface.getSimpleName());
Preconditions.checkState(!methodsMap.containsKey(index), "Duplicate serialization index for %s in %s",
method.getName(), dtoInterface.getSimpleName());
maxIndex = Math.max(index, maxIndex);
methodsMap.put(index, method);
}
Method[] result = new Method[maxIndex];
for (int index = 0; index < maxIndex; index++) {
result[index] = methodsMap.get(index + 1);
}
return result;
}
protected boolean isLastMethod(Method method) {
Preconditions.checkNotNull(method);
return method == dtoMethods.get(dtoMethods.size() - 1);
}
/**
* Create a textual representation of a string literal that evaluates to the given value.
*/
protected String quoteStringLiteral(String value) {
StringWriter sw = new StringWriter();
try (JsonWriter writer = new JsonWriter(sw)) {
writer.setLenient(true);
writer.value(value);
writer.flush();
} catch (IOException ex) {
throw new RuntimeException("Unexpected I/O failure: " + ex.getLocalizedMessage(), ex);
}
return sw.toString();
}
/**
* @return String representing the source definition for the DTO impl as an inner class.
*/
abstract String serialize();
} | epl-1.0 |
aptana/Pydev | tests/org.python.pydev.tests/src/org/python/pydev/plugin/nature/PythonNatureStoreTest.java | 5941 | /**
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
/*
* Created on Oct 28, 2006
* @author Fabio
*/
package org.python.pydev.plugin.nature;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.python.pydev.editor.actions.PySelectionTest;
import org.python.pydev.editor.codecompletion.revisited.ProjectModulesManager;
import org.python.pydev.plugin.PydevPlugin;
import org.python.pydev.shared_core.SharedCorePlugin;
import org.python.pydev.tests.BundleInfoStub;
public class PythonNatureStoreTest extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(PythonNatureStoreTest.class);
}
private String contents1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+
"<?eclipse-pydev version=\"1.0\"?>\r\n"
+
"\r\n"
+
"<pydev_project>\r\n"
+
"<pydev_property name=\"PyDevPluginID(null plugin).PYTHON_PROJECT_VERSION\">python 2.5</pydev_property>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_SOURCE_PATH\">\r\n"
+
"<path>/test</path>\r\n" +
"</pydev_pathproperty>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_EXTERNAL_SOURCE_PATH\"/>\r\n"
+
"</pydev_project>\r\n" +
"";
private String contents2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+
"<?eclipse-pydev version=\"1.0\"?>\r\n"
+
"\r\n"
+
"<pydev_project>\r\n"
+
"<pydev_property name=\"PyDevPluginID(null plugin).PYTHON_PROJECT_VERSION\">python 2.5</pydev_property>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_SOURCE_PATH\">\r\n"
+
"<path>/test/foo</path>\r\n" +
"<path>/bar/kkk</path>\r\n" +
"</pydev_pathproperty>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_EXTERNAL_SOURCE_PATH\"/>\r\n"
+
"</pydev_project>\r\n" +
"";
private String contents3 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+
"<?eclipse-pydev version=\"1.0\"?>\r\n"
+
"\r\n"
+
"<pydev_project>\r\n"
+
"<pydev_property name=\"PyDevPluginID(null plugin).PYTHON_PROJECT_VERSION\">python 2.5</pydev_property>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_SOURCE_PATH\">\r\n"
+
"<path>/test/foo</path>\r\n" +
"<path>/bar/kkk</path>\r\n" +
"</pydev_pathproperty>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_EXTERNAL_SOURCE_PATH\"/>\r\n"
+
"<pydev_variables_property name=\"PyDevPluginID(null plugin).PROJECT_VARIABLE_SUBSTITUTION\">\r\n"
+
"<key>MY_KEY</key>\r\n" +
"<value>MY_VALUE</value>\r\n" +
"</pydev_variables_property>\r\n"
+
"</pydev_project>\r\n" +
"";
@Override
protected void setUp() throws Exception {
super.setUp();
ProjectModulesManager.IN_TESTS = true;
PydevPlugin.setBundleInfo(new BundleInfoStub());
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testLoad() throws Exception {
// This test fails because of whitespace comparison problems. It may be better to
// use something like XMLUnit to compare the two XML files?
if (SharedCorePlugin.skipKnownFailures()) {
return;
}
PythonNatureStore store = new PythonNatureStore();
ProjectStub2 projectStub2 = new ProjectStub2("test");
//when setting the project, a side-effect must be that we create the xml file if it still does not exist
store.setProject(projectStub2);
//check the contents
String strContents = store.getLastLoadedContents();
PySelectionTest.checkStrEquals(contents1, strContents.replaceFirst(" standalone=\"no\"", "")); //depending on the java version, standalone="no" may be generated
//in ProjectStub2, the initial setting is /test (see the getPersistentProperty)
assertEquals("/test", store.getPathProperty(PythonPathNature.getProjectSourcePathQualifiedName()));
store.setPathProperty(PythonPathNature.getProjectSourcePathQualifiedName(), "/test/foo|/bar/kkk");
assertEquals("/test/foo|/bar/kkk", store.getPathProperty(PythonPathNature.getProjectSourcePathQualifiedName()));
strContents = store.getLastLoadedContents();
PySelectionTest.checkStrEquals(contents2, strContents.replaceFirst(" standalone=\"no\"", "")); //depending on the java version, standalone="no" may be generated
assertNull(store.getPathProperty(PythonPathNature.getProjectExternalSourcePathQualifiedName()));
Map<String, String> map = new HashMap<String, String>();
map.put("MY_KEY", "MY_VALUE");
store.setMapProperty(PythonPathNature.getProjectVariableSubstitutionQualifiedName(), map);
strContents = store.getLastLoadedContents();
PySelectionTest.checkStrEquals(contents3, strContents.replaceFirst(" standalone=\"no\"", "")); //depending on the java version, standalone="no" may be generated
assertEquals(map, store.getMapProperty(PythonPathNature.getProjectVariableSubstitutionQualifiedName()));
}
}
| epl-1.0 |
mcarlson/openlaszlo | WEB-INF/lps/server/src/org/openlaszlo/compiler/FontInfo.java | 8728 | /* ****************************************************************************
* FontInfo.java
* ****************************************************************************/
/* J_LZ_COPYRIGHT_BEGIN *******************************************************
* Copyright 2001-2006 Laszlo Systems, Inc. All Rights Reserved. *
* Use is subject to license terms. *
* J_LZ_COPYRIGHT_END *********************************************************/
package org.openlaszlo.compiler;
import org.openlaszlo.utils.ChainedException;
import java.io.Serializable;
import java.util.*;
/**
* Font information used for measuring text.
*
* @author <a href="mailto:bloch@laszlosystems.com">Eric Bloch</a>
*/
public class FontInfo implements java.io.Serializable {
public static final String NULL_FONT = null;
public static final int NULL_SIZE = -1;
public static final int NULL_STYLE = -1;
/** bit fields for text style */
public final static int PLAIN = 0x0;
/** bit fields for text style */
public final static int BOLD = 0x1;
/** bit fields for text style */
public final static int ITALIC = 0x2;
/** bit fields for text style */
public final static int BOLDITALIC = 0x3;
/** font face */
private String mName = null;
/** font size */
private int mSize;
/** used for compile-time width/height cascading */
private int mWidth = NULL_SIZE;
private int mHeight = NULL_SIZE;
/** font style bits */
public int styleBits = 0;
/** This can have three values:
-1 = unset
0 = false
1 = true
*/
public final static int FONTINFO_NULL = -1;
public final static int FONTINFO_FALSE = 0;
public final static int FONTINFO_TRUE = 1;
// resizable defaults to false
public int resizable = FONTINFO_NULL;
// multiline default to false
public int multiline = FONTINFO_NULL;
public String toString() {
return "FontInfo: name="+mName+", size="+mSize+", style="+getStyle();
}
public String toStringLong() {
return "FontInfo: name="+mName+", size="+mSize+", style="+getStyle()+", width="+mWidth+", height="+mHeight+", resizable="+resizable+", multiline="+multiline;
}
/**
* Create a new FontInfo
* @param name name
* @param sz size
* @param st style
*/
public FontInfo(String name, String sz, String st) {
mName = name;
setSize(sz);
setStyle(st);
}
public FontInfo(FontInfo i) {
this.mName = i.mName;
this.mSize = i.mSize;
this.styleBits = i.styleBits;
// static text optimization params
this.resizable = i.resizable;
this.multiline = i.multiline;
this.mWidth = i.getWidth();
this.mHeight = i.getHeight();
}
public FontInfo(String name, int sz, int st) {
mName = name;
mSize = sz;
styleBits = st;
}
/** Extra params for static textfield optimization.
Tracks width and height of a view.
*/
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public void setWidth (int w) {
mWidth = w;
}
public void setHeight (int w) {
mHeight = w;
}
/**
* Set the name
* @param f the name
*/
public void setName(String f) {
mName = f;
}
/**
* Set the style
* @param st style
*/
public void setStyle(String st) {
styleBits = styleBitsFromString(st);
}
/**
* Set the style bits directly
* @param st stylebits
*/
public void setStyleBits(int st) {
styleBits = st;
}
/**
* Set the size
* @param sz the size
*/
public void setSize(String sz) {
mSize = Integer.parseInt(sz);
}
/**
* Set the size
* @param sz the size
*/
public void setSize(int sz) {
mSize = sz;
}
/**
* @return the size
*/
public int getSize() {
return mSize;
}
/**
* @return the stylebits
*/
public int getStyleBits() {
return styleBits;
}
/**
* @return the name
*/
public String getName() {
return mName;
}
public static FontInfo blankFontInfo() {
FontInfo fi = new FontInfo(FontInfo.NULL_FONT, FontInfo.NULL_SIZE, FontInfo.NULL_STYLE);
return fi;
}
/** Does this font spec contain a known font name,size,style ?
*/
public boolean isFullySpecified () {
return ((mSize != NULL_SIZE) &&
(styleBits != NULL_STYLE) &&
(mName != NULL_FONT) &&
// we don't understand constraint expressions, just string literals
(mName.charAt(0) != '$'));
}
/** If OTHER has non-null fields, copy
them from OTHER to us.
null fields are indicated by:
name == null,
size == -1,
stylebits == -1,
*/
public void mergeFontInfoFrom(FontInfo other) {
if (other.getSize()!= NULL_SIZE) {
mSize = other.getSize();
}
if (other.getStyleBits() != NULL_STYLE) {
styleBits = other.getStyleBits();
}
if (other.getName()!= NULL_FONT) {
mName = other.getName();
}
if (other.resizable != FONTINFO_NULL) {
resizable = other.resizable;
}
if (other.multiline != FONTINFO_NULL) {
multiline = other.multiline;
}
if (other.getWidth() != NULL_SIZE) {
mWidth = other.getWidth();
}
if (other.getHeight() != NULL_SIZE) {
mHeight = other.getHeight();
}
}
/**
* @return the name
*/
public final String getStyle() {
return styleBitsToString(styleBits);
}
/**
* @return the name
*/
public final String getStyle(boolean whitespace) {
return styleBitsToString(styleBits, whitespace);
}
/**
* Return the string representation of the style.
*
* @param styleBits an <code>int</code> encoding the style
* @param whitespace whether to separate style names by spaces; e.g. true for "bold italic", false for "bolditalic"
*/
public static String styleBitsToString(int styleBits, boolean whitespace) {
switch (styleBits) {
case PLAIN:
return "plain";
case BOLD:
return "bold";
case ITALIC:
return "italic";
case BOLDITALIC:
if (whitespace) {
return "bold italic";
} else {
return "bolditalic";
}
default:
return null;
}
}
/**
* Return the string representation of the style, e.g. "bold italic".
*
* @param styleBits an <code>int</code> value
*/
public static String styleBitsToString(int styleBits) {
return styleBitsToString(styleBits, true);
}
/**
/**
* @return the bits for a style
*/
public static int styleBitsFromString(String name) {
int style = PLAIN;
if (name != null) {
StringTokenizer st = new StringTokenizer(name);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.equals("bold")) {
style |= BOLD;
} else if (token.equals("italic")) {
style |= ITALIC;
} else if (token.equals("plain")) {
style |= PLAIN;
} else if (token.equals("bolditalic")) {
style |= ITALIC | BOLD;
} else {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Unknown style " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
FontInfo.class.getName(),"051018-315", new Object[] {name})
);
}
}
}
return style;
}
/**
* "bold italic", "italic bold" -> "bold italic" or "bolditalic"
* (depending on the value of <code>whitespace</code>
*
* @param style a <code>String</code> value
* @return a <code>String</code> value
*/
public static String normalizeStyleString(String style, boolean whitespace) {
if (style.matches("^\\s*\\$(\\w*)\\{(.*)}\\s*")) {
return style;
} else {
return styleBitsToString(styleBitsFromString(style), whitespace);
}
}
}
| epl-1.0 |
Link1234Gamer/Five-Nights-at-Candy-s-Mod | src/main/java/com/fnacmod/fnac/Reference.java | 466 | package com.fnacmod.fnac;
//This code is copyright SoggyMustache, Link1234Gamer and Andrew_Playz
public class Reference {
public static final String MOD_ID = "fnac";
public static final String MOD_NAME = "Five Nights at Candy's Mod";
public static final String VERSION = "1.0";
public static final String CLIENT_PROXY_CLASS = "com.fnacmod.fnac.proxy.ClientProxy";
public static final String SERVER_PROXY_CLASS = "com.fnacmod.fnac.proxy.ServerProxy";
}
| epl-1.0 |
NickLW/JamSS | src/uk/ac/brighton/jamss/MidiPlayer.java | 4026 | package uk.ac.brighton.jamss;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
/**
* Creates a sequencer used to play a percussion sequence taken
* from a .midi file.
* @author Nick Walker
*/
class MidiPlayer {
// Midi meta event
public static final int END_OF_TRACK_MESSAGE = 47;
private Sequencer sequencer;
public float tempo;
private boolean loop;
public boolean paused;
public void setBPMs(float beatsPerMinute){
tempo = beatsPerMinute;
}
/**
* Creates a new MidiPlayer object.
*/
public MidiPlayer() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
//sequencer.addMetaEventListener(this);
} catch (MidiUnavailableException ex) {
sequencer = null;
}
}
/**
* Loads a sequence from the file system. Returns null if an error occurs.
*/
public Sequence getSequence(String filename) {
try {
return getSequence(new FileInputStream(filename));
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
/**
* Loads a sequence from an input stream. Returns null if an error occurs.
*/
public Sequence getSequence(InputStream is) {
try {
if (!is.markSupported()) {
is = new BufferedInputStream(is);
}
Sequence s = MidiSystem.getSequence(is);
is.close();
return s;
} catch (InvalidMidiDataException ex) {
ex.printStackTrace();
return null;
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
/**
* Plays a sequence, optionally looping. This method returns immediately.
* The sequence is not played if it is invalid.
*/
public void play(Sequence sequence, boolean loop) {
if (sequencer != null && sequence != null && sequencer.isOpen()) {
try {
sequencer.setSequence(sequence);
sequencer.open();
/*if(loop) {
sequencer.setLoopStartPoint(0);
sequencer.setLoopEndPoint(-1);
sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
sequencer.setTempoInBPM(tempo);
}*/
sequencer.setTempoInBPM(tempo);
sequencer.start();
this.loop = loop;
} catch (InvalidMidiDataException ex) {
ex.printStackTrace();
} catch (MidiUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* This method is called by the sound system when a meta event occurs. In
* this case, when the end-of-track meta event is received, the sequence is
* restarted if looping is on.
*/
/*public void meta(MetaMessage event) {
if (event.getType() == END_OF_TRACK_MESSAGE) {
if (sequencer != null && sequencer.isOpen() && loop) {
sequencer.setMicrosecondPosition(0);
sequencer.setTempoInBPM(tempo);
sequencer.start();
}
}
}*/
/**
* Stops the sequencer and resets its position to the
* start of the sequence.
*/
public void stop() {
if (sequencer != null && sequencer.isOpen()) {
sequencer.stop();
sequencer.setMicrosecondPosition(0);
}
}
/**
* Closes the sequencer.
*/
public void close() {
if (sequencer != null && sequencer.isOpen()) {
sequencer.close();
}
}
/**
* Gets the sequencer.
*/
public Sequencer getSequencer() {
return sequencer;
}
/**
* Sets the paused state. Music may not immediately pause.
*/
public void setPaused(boolean paused) {
if (this.paused != paused && sequencer != null && sequencer.isOpen()) {
this.paused = paused;
if (paused) {
sequencer.stop();
} else {
sequencer.start();
}
}
}
/**
* Returns the paused state.
*/
public boolean isPaused() {
return paused;
}
} | epl-1.0 |
neelance/swt4ruby | swt4ruby/src/linux-x86_64/org/eclipse/swt/internal/gtk/GtkFixed.java | 958 | /*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others. All rights reserved.
* The contents of this file are made available under the terms
* of the GNU Lesser General Public License (LGPL) Version 2.1 that
* accompanies this distribution (lgpl-v21.txt). The LGPL is also
* available at http://www.gnu.org/licenses/lgpl.html. If the version
* of the LGPL at http://www.gnu.org is different to the version of
* the LGPL accompanying this distribution and there is any conflict
* between the two license versions, the terms of the LGPL accompanying
* this distribution shall govern.
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.internal.gtk;
public class GtkFixed {
/** @field cast=(GList *) */
public long /*int*/ children;
}
| epl-1.0 |
whizzosoftware/hobson-hub-rules | src/test/java/com/whizzosoftware/hobson/rules/condition/PresenceArrivalConditionClassTest.java | 2537 | /*******************************************************************************
* Copyright (c) 2015 Whizzo Software, LLC.
* 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 com.whizzosoftware.hobson.rules.condition;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.presence.PresenceEntityContext;
import com.whizzosoftware.hobson.api.presence.PresenceLocationContext;
import com.whizzosoftware.hobson.api.property.PropertyContainer;
import org.jruleengine.rule.Assumption;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class PresenceArrivalConditionClassTest {
@Test
public void testCreateAssumptions() {
PluginContext pctx = PluginContext.createLocal("plugin1");
PresenceArrivalConditionClass pdcc = new PresenceArrivalConditionClass(pctx);
Map<String,Object> values = new HashMap<>();
values.put("person", PresenceEntityContext.createLocal("person1"));
values.put("location", PresenceLocationContext.createLocal("location1"));
PropertyContainer conditions = new PropertyContainer(
pdcc.getContext(),
values
);
List<Assumption> assumps = pdcc.createConditionAssumptions(conditions);
assertEquals(4, assumps.size());
assertEquals("com.whizzosoftware.hobson.rules.jruleengine.JREEventContext.eventId", assumps.get(0).getLeftTerm());
assertEquals("=", assumps.get(0).getOperator());
assertEquals("presenceUpdateNotify", assumps.get(0).getRightTerm());
assertEquals("event.person", assumps.get(1).getLeftTerm());
assertEquals("=", assumps.get(1).getOperator());
assertEquals("local:person1", assumps.get(1).getRightTerm());
assertEquals("event.oldLocation", assumps.get(2).getLeftTerm());
assertEquals("<>", assumps.get(2).getOperator());
assertEquals("local:location1", assumps.get(2).getRightTerm());
assertEquals("event.newLocation", assumps.get(3).getLeftTerm());
assertEquals("=", assumps.get(3).getOperator());
assertEquals("local:location1", assumps.get(3).getRightTerm());
}
}
| epl-1.0 |
sschafer/atomic | org.allmyinfo.result/src/org/allmyinfo/result/ValidStringResult.java | 432 | package org.allmyinfo.result;
import org.eclipse.jdt.annotation.NonNull;
public final class ValidStringResult implements StringResult
{
private final String value;
public ValidStringResult(final @NonNull String value)
{
this.value = value;
}
@Override
public boolean isPresent()
{
return true;
}
@Override
public boolean isValid()
{
return true;
}
@Override
public String getValue()
{
return value;
}
} | epl-1.0 |
spearce/egit | org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestProject.java | 6918 | /*******************************************************************************
* Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
* Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org>
*
* 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.egit.core.test;
import java.net.URL;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.osgi.framework.Bundle;
public class TestProject {
public IProject project;
public IJavaProject javaProject;
private IPackageFragmentRoot sourceFolder;
/**
* @throws CoreException
* If project already exists
*/
public TestProject() throws CoreException {
this(false);
}
/**
* @param remove
* should project be removed if already exists
* @throws CoreException
*/
public TestProject(final boolean remove) throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
project = root.getProject("Project-1");
if (remove)
project.delete(true, null);
project.create(null);
project.open(null);
javaProject = JavaCore.create(project);
IFolder binFolder = createBinFolder();
setJavaNature();
javaProject.setRawClasspath(new IClasspathEntry[0], null);
createOutputFolder(binFolder);
addSystemLibraries();
}
public IProject getProject() {
return project;
}
public IJavaProject getJavaProject() {
return javaProject;
}
public void addJar(String plugin, String jar) throws JavaModelException {
Path result = findFileInPlugin(plugin, jar);
IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
newEntries[oldEntries.length] = JavaCore.newLibraryEntry(result, null,
null);
javaProject.setRawClasspath(newEntries, null);
}
public IPackageFragment createPackage(String name) throws CoreException {
if (sourceFolder == null)
sourceFolder = createSourceFolder();
return sourceFolder.createPackageFragment(name, false, null);
}
public IType createType(IPackageFragment pack, String cuName, String source)
throws JavaModelException {
StringBuffer buf = new StringBuffer();
buf.append("package " + pack.getElementName() + ";\n");
buf.append("\n");
buf.append(source);
ICompilationUnit cu = pack.createCompilationUnit(cuName,
buf.toString(), false, null);
return cu.getTypes()[0];
}
public void dispose() throws CoreException {
waitForIndexer();
project.delete(true, true, null);
}
private IFolder createBinFolder() throws CoreException {
IFolder binFolder = project.getFolder("bin");
binFolder.create(false, true, null);
return binFolder;
}
private void setJavaNature() throws CoreException {
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID });
project.setDescription(description, null);
}
private void createOutputFolder(IFolder binFolder)
throws JavaModelException {
IPath outputLocation = binFolder.getFullPath();
javaProject.setOutputLocation(outputLocation, null);
}
public IPackageFragmentRoot createSourceFolder() throws CoreException {
IFolder folder = project.getFolder("src");
folder.create(false, true, null);
IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);
IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
javaProject.setRawClasspath(newEntries, null);
return root;
}
private void addSystemLibraries() throws JavaModelException {
IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
newEntries[oldEntries.length] = JavaRuntime
.getDefaultJREContainerEntry();
javaProject.setRawClasspath(newEntries, null);
}
private Path findFileInPlugin(String plugin, String file) {
Bundle bundle = Platform.getBundle(plugin);
URL resource = bundle.getResource(file);
return new Path(resource.getPath());
}
public void waitForIndexer() {
// new SearchEngine().searchAllTypeNames(ResourcesPlugin.getWorkspace(),
// null, null, IJavaSearchConstants.EXACT_MATCH,
// IJavaSearchConstants.CASE_SENSITIVE,
// IJavaSearchConstants.CLASS, SearchEngine
// .createJavaSearchScope(new IJavaElement[0]),
// new ITypeNameRequestor() {
// public void acceptClass(char[] packageName,
// char[] simpleTypeName, char[][] enclosingTypeNames,
// String path) {
// }
// public void acceptInterface(char[] packageName,
// char[] simpleTypeName, char[][] enclosingTypeNames,
// String path) {
// }
// }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
}
/**
* @return Returns the sourceFolder.
*/
public IPackageFragmentRoot getSourceFolder() {
return sourceFolder;
}
/**
* @param sourceFolder The sourceFolder to set.
*/
public void setSourceFolder(IPackageFragmentRoot sourceFolder) {
this.sourceFolder = sourceFolder;
}
}
| epl-1.0 |
info-sharing-environment/NIEM-Modeling-Tool | plugins/org.search.niem.uml.ui.acceptance_tests/src/test/java/org/search/niem/uml/ui/acceptance_tests/UIUtils.java | 2407 | /*
* 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:
* SEARCH Group, Incorporated - initial API and implementation
*
*/
package org.search.niem.uml.ui.acceptance_tests;
import static org.search.niem.uml.ui.util.UIExt.select;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
public class UIUtils {
public static IWorkbench get_the_workbench() {
return PlatformUI.getWorkbench();
}
public static IWorkbenchWindow get_the_active_workbench_window() {
return get_the_workbench().getActiveWorkbenchWindow();
}
public static IWorkbenchPage get_the_active_workbench_page() {
return get_the_active_workbench_window().getActivePage();
}
public static IEditorPart get_the_active_editor() {
return get_the_active_workbench_page().getActiveEditor();
}
@SuppressWarnings("unchecked")
private static <V extends IViewPart> V find_the_view(final String id) {
for (final IWorkbenchPage p : get_the_active_workbench_window().getPages()) {
final IViewPart view = p.findView(id);
if (view != null) {
return (V) view;
}
}
return null;
}
@SuppressWarnings("unchecked")
public static <V extends IViewPart> V activate_the_view(final String id) throws PartInitException {
final IViewPart theView = find_the_view(id);
if (theView == null) {
return (V) get_the_active_workbench_page().showView(id);
}
theView.setFocus();
return (V) theView;
}
public static void close_all_open_editors() {
for (final IWorkbenchWindow w : get_the_workbench().getWorkbenchWindows()) {
for (final IWorkbenchPage p : w.getPages()) {
p.closeAllEditors(false);
}
}
}
public static void select_the_default_button(final IShellProvider provider) {
select(provider.getShell().getDefaultButton());
}
}
| epl-1.0 |
stormc/hawkbit | hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java | 41642 | /**
* Copyright (c) 2015 Bosch Software Innovations GmbH 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.hawkbit.repository.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.repository.FilterParams;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
import org.junit.Test;
import org.springframework.data.domain.Slice;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Repository")
@Stories("Target Management Searches")
public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests different parameter combinations for target search operations. "
+ "That includes both the test itself, as a count operation with the same filters "
+ "and query definitions by RSQL (named and un-named).")
public void targetSearchWithVariousFilterCombinations() {
final TargetTag targTagX = targetTagManagement.create(entityFactory.tag().create().name("TargTag-X"));
final TargetTag targTagY = targetTagManagement.create(entityFactory.tag().create().name("TargTag-Y"));
final TargetTag targTagZ = targetTagManagement.create(entityFactory.tag().create().name("TargTag-Z"));
final TargetTag targTagW = targetTagManagement.create(entityFactory.tag().create().name("TargTag-W"));
final DistributionSet setA = testdataFactory.createDistributionSet("");
final DistributionSet installedSet = testdataFactory.createDistributionSet("another");
final Long lastTargetQueryNotOverdue = Instant.now().toEpochMilli();
final Long lastTargetQueryAlwaysOverdue = 0L;
final Long lastTargetNull = null;
final String targetDsAIdPref = "targ-A";
List<Target> targAs = testdataFactory.createTargets(100, targetDsAIdPref,
targetDsAIdPref.concat(" description"), lastTargetQueryNotOverdue);
targAs = toggleTagAssignment(targAs, targTagX).getAssignedEntity();
final Target targSpecialName = targetManagement
.update(entityFactory.target().update(targAs.get(0).getControllerId()).name("targ-A-special"));
final String targetDsBIdPref = "targ-B";
List<Target> targBs = testdataFactory.createTargets(100, targetDsBIdPref,
targetDsBIdPref.concat(" description"), lastTargetQueryAlwaysOverdue);
targBs = toggleTagAssignment(targBs, targTagY).getAssignedEntity();
targBs = toggleTagAssignment(targBs, targTagW).getAssignedEntity();
final String targetDsCIdPref = "targ-C";
List<Target> targCs = testdataFactory.createTargets(100, targetDsCIdPref,
targetDsCIdPref.concat(" description"), lastTargetQueryAlwaysOverdue);
targCs = toggleTagAssignment(targCs, targTagZ).getAssignedEntity();
targCs = toggleTagAssignment(targCs, targTagW).getAssignedEntity();
final String targetDsDIdPref = "targ-D";
final List<Target> targDs = testdataFactory.createTargets(100, targetDsDIdPref,
targetDsDIdPref.concat(" description"), lastTargetNull);
final String assignedC = targCs.iterator().next().getControllerId();
assignDistributionSet(setA.getId(), assignedC);
final String assignedA = targAs.iterator().next().getControllerId();
assignDistributionSet(setA.getId(), assignedA);
final String assignedB = targBs.iterator().next().getControllerId();
assignDistributionSet(setA.getId(), assignedB);
final String installedC = targCs.iterator().next().getControllerId();
final Long actionId = assignDistributionSet(installedSet.getId(), assignedC).getActions().get(0);
// set one installed DS also
controllerManagement.addUpdateActionStatus(
entityFactory.actionStatus().create(actionId).status(Status.FINISHED).message("message"));
assignDistributionSet(setA.getId(), installedC);
final List<TargetUpdateStatus> unknown = Arrays.asList(TargetUpdateStatus.UNKNOWN);
final List<TargetUpdateStatus> pending = Arrays.asList(TargetUpdateStatus.PENDING);
final List<TargetUpdateStatus> both = Arrays.asList(TargetUpdateStatus.UNKNOWN, TargetUpdateStatus.PENDING);
// get final updated version of targets
targAs = targetManagement
.getByControllerID(targAs.stream().map(Target::getControllerId).collect(Collectors.toList()));
targBs = targetManagement
.getByControllerID(targBs.stream().map(Target::getControllerId).collect(Collectors.toList()));
targCs = targetManagement
.getByControllerID(targCs.stream().map(Target::getControllerId).collect(Collectors.toList()));
// try to find several targets with different filter settings
verifyThat1TargetHasNameAndId("targ-A-special", targSpecialName.getControllerId());
verifyThatRepositoryContains400Targets();
verifyThat200TargetsHaveTagD(targTagW, concat(targBs, targCs));
verifyThat100TargetsContainsGivenTextAndHaveTagAssigned(targTagY, targTagW, targBs);
verifyThat1TargetHasTagHasDescOrNameAndDs(targTagW, setA, targetManagement.getByControllerID(assignedC).get());
verifyThat0TargetsWithTagAndDescOrNameHasDS(targTagW, setA);
verifyThat0TargetsWithNameOrdescAndDSHaveTag(targTagX, setA);
verifyThat3TargetsHaveDSAssigned(setA,
targetManagement.getByControllerID(Arrays.asList(assignedA, assignedB, assignedC)));
verifyThat1TargetWithDescOrNameHasDS(setA, targetManagement.getByControllerID(assignedA).get());
List<Target> expected = concat(targAs, targBs, targCs, targDs);
expected.removeAll(targetManagement.getByControllerID(Arrays.asList(assignedA, assignedB, assignedC)));
verifyThat397TargetsAreInStatusUnknown(unknown, expected);
expected = concat(targBs, targCs);
expected.removeAll(targetManagement.getByControllerID(Arrays.asList(assignedB, assignedC)));
verifyThat198TargetsAreInStatusUnknownAndHaveGivenTags(targTagY, targTagW, unknown, expected);
verfyThat0TargetsAreInStatusUnknownAndHaveDSAssigned(setA, unknown);
expected = concat(targAs);
expected.remove(targetManagement.getByControllerID(assignedA).get());
verifyThat99TargetsWithNameOrDescriptionAreInGivenStatus(unknown, expected);
expected = concat(targBs);
expected.remove(targetManagement.getByControllerID(assignedB).get());
verifyThat99TargetsWithGivenNameOrDescAndTagAreInStatusUnknown(targTagW, unknown, expected);
verifyThat3TargetsAreInStatusPending(pending,
targetManagement.getByControllerID(Arrays.asList(assignedA, assignedB, assignedC)));
verifyThat3TargetsWithGivenDSAreInPending(setA, pending,
targetManagement.getByControllerID(Arrays.asList(assignedA, assignedB, assignedC)));
verifyThat1TargetWithGivenNameOrDescAndDSIsInPending(setA, pending,
targetManagement.getByControllerID(assignedA).get());
verifyThat1TargetWithGivenNameOrDescAndTagAndDSIsInPending(targTagW, setA, pending,
targetManagement.getByControllerID(assignedB).get());
verifyThat2TargetsWithGivenTagAndDSIsInPending(targTagW, setA, pending,
targetManagement.getByControllerID(Arrays.asList(assignedB, assignedC)));
verifyThat2TargetsWithGivenTagAreInPending(targTagW, pending,
targetManagement.getByControllerID(Arrays.asList(assignedB, assignedC)));
verifyThat200targetsWithGivenTagAreInStatusPendingorUnknown(targTagW, both, concat(targBs, targCs));
verfiyThat1TargetAIsInStatusPendingAndHasDSInstalled(installedSet, pending,
targetManagement.getByControllerID(installedC).get());
expected = concat(targBs, targCs);
expected.removeAll(targetManagement.getByControllerID(Arrays.asList(assignedB, assignedC)));
verifyThat198TargetsAreInStatusUnknownAndOverdue(unknown, expected);
}
@Step
private void verfiyThat1TargetAIsInStatusPendingAndHasDSInstalled(final DistributionSet installedSet,
final List<TargetUpdateStatus> pending, final Target expected) {
final String query = "updatestatus==pending and installedds.name==" + installedSet.getName();
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(pending, null, null, installedSet.getId(), Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(1)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(pending, null, null,
installedSet.getId(), Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsExactly(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat200targetsWithGivenTagAreInStatusPendingorUnknown(final TargetTag targTagW,
final List<TargetUpdateStatus> both, final List<Target> expected) {
final String query = "(updatestatus==pending or updatestatus==unknown) and tag==" + targTagW.getName();
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(both, null, null, null, Boolean.FALSE, targTagW.getName()))
.getContent()).as("has number of elements").hasSize(200)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(both, null, null, null,
Boolean.FALSE, targTagW.getName())))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat2TargetsWithGivenTagAreInPending(final TargetTag targTagW,
final List<TargetUpdateStatus> pending, final List<Target> expected) {
final String query = "updatestatus==pending and tag==" + targTagW.getName();
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(pending, null, null, null, Boolean.FALSE, targTagW.getName()))
.getContent()).as("has number of elements").hasSize(2)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(pending, null, null, null,
Boolean.FALSE, targTagW.getName())))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat2TargetsWithGivenTagAndDSIsInPending(final TargetTag targTagW, final DistributionSet setA,
final List<TargetUpdateStatus> pending, final List<Target> expected) {
final String query = "updatestatus==pending and (assignedds.name==" + setA.getName() + " or installedds.name=="
+ setA.getName() + ") and tag==" + targTagW.getName();
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(pending, null, null, setA.getId(), Boolean.FALSE, targTagW.getName()))
.getContent()).as("has number of elements").hasSize(2)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(pending, null, null, setA.getId(),
Boolean.FALSE, targTagW.getName())))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat1TargetWithGivenNameOrDescAndTagAndDSIsInPending(final TargetTag targTagW,
final DistributionSet setA, final List<TargetUpdateStatus> pending, final Target expected) {
final String query = "updatestatus==pending and (assignedds.name==" + setA.getName() + " or installedds.name=="
+ setA.getName() + ") and (name==*targ-B* or description==*targ-B*) and tag==" + targTagW.getName();
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(pending, null, "%targ-B%", setA.getId(), Boolean.FALSE, targTagW.getName()))
.getContent()).as("has number of elements").hasSize(1)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(pending, null, "%targ-B%",
setA.getId(), Boolean.FALSE, targTagW.getName())))
.as("and contains the following elements").containsExactly(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat1TargetWithGivenNameOrDescAndDSIsInPending(final DistributionSet setA,
final List<TargetUpdateStatus> pending, final Target expected) {
final String query = "updatestatus==pending and (assignedds.name==" + setA.getName() + " or installedds.name=="
+ setA.getName() + ") and (name==*targ-A* or description==*targ-A*)";
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(pending, null, "%targ-A%", setA.getId(), Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(1)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(pending, null, "%targ-A%",
setA.getId(), Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsExactly(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat3TargetsWithGivenDSAreInPending(final DistributionSet setA,
final List<TargetUpdateStatus> pending, final List<Target> expected) {
final String query = "updatestatus==pending and (assignedds.name==" + setA.getName() + " or installedds.name=="
+ setA.getName() + ")";
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(pending, null, null, setA.getId(), Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(3)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(pending, null, null, setA.getId(),
Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat3TargetsAreInStatusPending(final List<TargetUpdateStatus> pending,
final List<Target> expected) {
final String query = "updatestatus==pending";
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(pending, null, null, null, Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(3)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(pending, null, null, null,
Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat99TargetsWithGivenNameOrDescAndTagAreInStatusUnknown(final TargetTag targTagW,
final List<TargetUpdateStatus> unknown, final List<Target> expected) {
final String query = "updatestatus==unknown and (name==*targ-B* or description==*targ-B*) and tag=="
+ targTagW.getName();
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(unknown, null, "%targ-B%", null, Boolean.FALSE, targTagW.getName()))
.getContent()).as("has number of elements").hasSize(99)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(unknown, null, "%targ-B%", null,
Boolean.FALSE, targTagW.getName())))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat99TargetsWithNameOrDescriptionAreInGivenStatus(final List<TargetUpdateStatus> unknown,
final List<Target> expected) {
final String query = "updatestatus==unknown and (name==*targ-A* or description==*targ-A*)";
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(unknown, null, "%targ-A%", null, Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(99)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(unknown, null, "%targ-A%", null,
Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verfyThat0TargetsAreInStatusUnknownAndHaveDSAssigned(final DistributionSet setA,
final List<TargetUpdateStatus> unknown) {
final String query = "updatestatus==unknown and (assignedds.name==" + setA.getName() + " or installedds.name=="
+ setA.getName() + ")";
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(unknown, null, null, setA.getId(), Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(0)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(unknown, null, null, setA.getId(),
Boolean.FALSE, new String[0])))
.as("and filter query returns the same result")
.hasSize(targetManagement.findByRsql(PAGE, query).getContent().size());
}
@Step
private void verifyThat198TargetsAreInStatusUnknownAndHaveGivenTags(final TargetTag targTagY,
final TargetTag targTagW, final List<TargetUpdateStatus> unknown, final List<Target> expected) {
final String query = "updatestatus==unknown and (tag==" + targTagY.getName() + " or tag==" + targTagW.getName()
+ ")";
assertThat(targetManagement.findByFilters(PAGE,
new FilterParams(unknown, null, null, null, Boolean.FALSE, targTagY.getName(), targTagW.getName()))
.getContent()).as("has number of elements").hasSize(198)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(unknown, null, null, null,
Boolean.FALSE, targTagY.getName(), targTagW.getName())))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat397TargetsAreInStatusUnknown(final List<TargetUpdateStatus> unknown,
final List<Target> expected) {
final String query = "updatestatus==unknown";
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(unknown, null, null, null, Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(397)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(unknown, null, null, null,
Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat198TargetsAreInStatusUnknownAndOverdue(final List<TargetUpdateStatus> unknown,
final List<Target> expected) {
// be careful: simple filters are concatenated using AND-gating
final String query = "lastcontrollerrequestat=le=${overdue_ts};updatestatus==UNKNOWN";
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(unknown, Boolean.TRUE, null, null, Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(198)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(unknown, Boolean.TRUE, null, null,
Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat1TargetWithDescOrNameHasDS(final DistributionSet setA, final Target expected) {
final String query = "(name==*targ-A* or description==*targ-A*) and (assignedds.name==" + setA.getName()
+ " or installedds.name==" + setA.getName() + ")";
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(null, null, "%targ-A%", setA.getId(), Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(1)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(null, null, "%targ-A%",
setA.getId(), Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsExactly(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat3TargetsHaveDSAssigned(final DistributionSet setA, final List<Target> expected) {
final String query = "assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName();
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(null, null, null, setA.getId(), Boolean.FALSE, new String[0]))
.getContent()).as("has number of elements").hasSize(3)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(null, null, null, setA.getId(),
Boolean.FALSE, new String[0])))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat0TargetsWithNameOrdescAndDSHaveTag(final TargetTag targTagX, final DistributionSet setA) {
final String query = "(name==*targ-C* or description==*targ-C*) and tag==" + targTagX.getName()
+ " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")";
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(null, null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagX.getName()))
.getContent()).as("has number of elements").hasSize(0)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(null, null, "%targ-C%",
setA.getId(), Boolean.FALSE, targTagX.getName())))
.as("and filter query returns the same result")
.hasSize(targetManagement.findByRsql(PAGE, query).getContent().size());
}
@Step
private void verifyThat0TargetsWithTagAndDescOrNameHasDS(final TargetTag targTagW, final DistributionSet setA) {
final String query = "(name==*targ-A* or description==*targ-A*) and tag==" + targTagW.getName()
+ " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")";
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(null, null, "%targ-A%", setA.getId(), Boolean.FALSE, targTagW.getName()))
.getContent()).as("has number of elements").hasSize(0)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(null, null, "%targ-A%",
setA.getId(), Boolean.FALSE, targTagW.getName())))
.as("and filter query returns the same result")
.hasSize(targetManagement.findByRsql(PAGE, query).getContent().size());
}
@Step
private void verifyThat1TargetHasTagHasDescOrNameAndDs(final TargetTag targTagW, final DistributionSet setA,
final Target expected) {
final String query = "(name==*targ-c* or description==*targ-C*) and tag==" + targTagW.getName()
+ " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")";
assertThat(targetManagement
.findByFilters(PAGE,
new FilterParams(null, null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagW.getName()))
.getContent()).as("has number of elements").hasSize(1)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(null, null, "%targ-C%",
setA.getId(), Boolean.FALSE, targTagW.getName())))
.as("and contains the following elements").containsExactly(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThat1TargetHasNameAndId(final String name, final String controllerId) {
assertThat(targetManagement.findByFilters(PAGE, new FilterParams(null, null, name, null, Boolean.FALSE))
.getContent()).as("has number of elements").hasSize(1).as("that number is also returned by count query")
.hasSize(Ints
.saturatedCast(targetManagement.countByFilters(null, null, name, null, Boolean.FALSE)));
assertThat(targetManagement.findByFilters(PAGE, new FilterParams(null, null, controllerId, null, Boolean.FALSE))
.getContent()).as("has number of elements").hasSize(1).as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(
targetManagement.countByFilters(null, null, controllerId, null, Boolean.FALSE)));
}
@Step
private void verifyThat100TargetsContainsGivenTextAndHaveTagAssigned(final TargetTag targTagY,
final TargetTag targTagW, final List<Target> expected) {
final String query = "(name==*targ-B* or description==*targ-B*) and (tag==" + targTagY.getName() + " or tag=="
+ targTagW.getName() + ")";
assertThat(targetManagement.findByFilters(PAGE,
new FilterParams(null, null, "%targ-B%", null, Boolean.FALSE, targTagY.getName(), targTagW.getName()))
.getContent()).as("has number of elements").hasSize(100)
.as("that number is also returned by count query")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(null, null, "%targ-B%", null,
Boolean.FALSE, targTagY.getName(), targTagW.getName())))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@SafeVarargs
private final List<Target> concat(final List<Target>... targets) {
final List<Target> result = new ArrayList<>();
Arrays.asList(targets).forEach(result::addAll);
return result;
}
@Step
private void verifyThat200TargetsHaveTagD(final TargetTag targTagD, final List<Target> expected) {
final String query = "tag==" + targTagD.getName();
assertThat(targetManagement
.findByFilters(PAGE, new FilterParams(null, null, null, null, Boolean.FALSE, targTagD.getName()))
.getContent()).as("Expected number of results is").hasSize(200)
.as("and is expected number of results is equal to ")
.hasSize(Ints.saturatedCast(targetManagement.countByFilters(null, null, null, null,
Boolean.FALSE, targTagD.getName())))
.as("and contains the following elements").containsAll(expected)
.as("and filter query returns the same result")
.containsAll(targetManagement.findByRsql(PAGE, query).getContent());
}
@Step
private void verifyThatRepositoryContains400Targets() {
assertThat(targetManagement.findByFilters(PAGE, new FilterParams(null, null, null, null, null, new String[0]))
.getContent()).as("Overall we expect that many targets in the repository").hasSize(400)
.as("which is also reflected by repository count")
.hasSize(Ints.saturatedCast(targetManagement.count()))
.as("which is also reflected by call without specification")
.containsAll(targetManagement.findAll(PAGE).getContent());
}
@Test
@Description("Tests the correct order of targets based on selected distribution set. The system expects to have an order based on installed, assigned DS.")
public void targetSearchWithVariousFilterCombinationsAndOrderByDistributionSet() {
final List<Target> notAssigned = testdataFactory.createTargets(3, "not", "first description");
List<Target> targAssigned = testdataFactory.createTargets(3, "assigned", "first description");
List<Target> targInstalled = testdataFactory.createTargets(3, "installed", "first description");
final DistributionSet ds = testdataFactory.createDistributionSet("a");
targAssigned = Lists.newLinkedList(assignDistributionSet(ds, targAssigned).getAssignedEntity());
targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity();
targInstalled = testdataFactory
.sendUpdateActionStatusToTargets(targInstalled, Status.FINISHED, Collections.singletonList("installed"))
.stream().map(Action::getTarget).collect(Collectors.toList());
final Slice<Target> result = targetManagement.findByFilterOrderByLinkedDistributionSet(PAGE, ds.getId(),
new FilterParams(null, null, null, null, Boolean.FALSE, new String[0]));
final Comparator<TenantAwareBaseEntity> byId = (e1, e2) -> Long.compare(e2.getId(), e1.getId());
assertThat(result.getNumberOfElements()).isEqualTo(9);
final List<Target> expected = new ArrayList<>();
Collections.sort(targInstalled, byId);
Collections.sort(targAssigned, byId);
Collections.sort(notAssigned, byId);
expected.addAll(targInstalled);
expected.addAll(targAssigned);
expected.addAll(notAssigned);
assertThat(result.getContent()).containsExactly(expected.toArray(new Target[0]));
}
@Test
@Description("Tests the correct order of targets with applied overdue filter based on selected distribution set. The system expects to have an order based on installed, assigned DS.")
public void targetSearchWithOverdueFilterAndOrderByDistributionSet() {
final Long lastTargetQueryAlwaysOverdue = 0L;
final Long lastTargetQueryNotOverdue = Instant.now().toEpochMilli();
final Long lastTargetNull = null;
final Long[] overdueMix = { lastTargetQueryAlwaysOverdue, lastTargetQueryNotOverdue,
lastTargetQueryAlwaysOverdue, lastTargetNull, lastTargetQueryAlwaysOverdue };
final List<Target> notAssigned = Lists.newArrayListWithExpectedSize(overdueMix.length);
List<Target> targAssigned = Lists.newArrayListWithExpectedSize(overdueMix.length);
List<Target> targInstalled = Lists.newArrayListWithExpectedSize(overdueMix.length);
for (int i = 0; i < overdueMix.length; i++) {
notAssigned.add(targetManagement
.create(entityFactory.target().create().controllerId("not" + i).lastTargetQuery(overdueMix[i])));
targAssigned.add(targetManagement.create(
entityFactory.target().create().controllerId("assigned" + i).lastTargetQuery(overdueMix[i])));
targInstalled.add(targetManagement.create(
entityFactory.target().create().controllerId("installed" + i).lastTargetQuery(overdueMix[i])));
}
final DistributionSet ds = testdataFactory.createDistributionSet("a");
targAssigned = assignDistributionSet(ds, targAssigned).getAssignedEntity();
targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity();
targInstalled = testdataFactory
.sendUpdateActionStatusToTargets(targInstalled, Status.FINISHED, Collections.singletonList("installed"))
.stream().map(Action::getTarget).collect(Collectors.toList());
final Slice<Target> result = targetManagement.findByFilterOrderByLinkedDistributionSet(PAGE, ds.getId(),
new FilterParams(null, Boolean.TRUE, null, null, Boolean.FALSE, new String[0]));
final Comparator<TenantAwareBaseEntity> byId = (e1, e2) -> Long.compare(e2.getId(), e1.getId());
assertThat(result.getNumberOfElements()).isEqualTo(9);
final List<Target> expected = new ArrayList<>();
expected.addAll(targInstalled.stream().sorted(byId)
.filter(item -> lastTargetQueryAlwaysOverdue.equals(item.getLastTargetQuery()))
.collect(Collectors.toList()));
expected.addAll(targAssigned.stream().sorted(byId)
.filter(item -> lastTargetQueryAlwaysOverdue.equals(item.getLastTargetQuery()))
.collect(Collectors.toList()));
expected.addAll(notAssigned.stream().sorted(byId)
.filter(item -> lastTargetQueryAlwaysOverdue.equals(item.getLastTargetQuery()))
.collect(Collectors.toList()));
assertThat(result.getContent()).containsExactly(expected.toArray(new Target[0]));
}
@Test
@Description("Verfies that targets with given assigned DS are returned from repository.")
public void findTargetByAssignedDistributionSet() {
final DistributionSet assignedSet = testdataFactory.createDistributionSet("");
testdataFactory.createTargets(10, "unassigned", "unassigned");
List<Target> assignedtargets = testdataFactory.createTargets(10, "assigned", "assigned");
assignDistributionSet(assignedSet, assignedtargets);
// get final updated version of targets
assignedtargets = targetManagement.getByControllerID(
assignedtargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()));
assertThat(targetManagement.findByAssignedDistributionSet(PAGE, assignedSet.getId()))
.as("Contains the assigned targets").containsAll(assignedtargets)
.as("and that means the following expected amount").hasSize(10);
}
@Test
@Description("Verifies that targets without given assigned DS are returned from repository.")
public void findTargetWithoutAssignedDistributionSet() {
final DistributionSet assignedSet = testdataFactory.createDistributionSet("");
final TargetFilterQuery tfq = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name("tfq").query("name==*"));
final List<Target> unassignedTargets = testdataFactory.createTargets(12, "unassigned", "unassigned");
final List<Target> assignedTargets = testdataFactory.createTargets(10, "assigned", "assigned");
assignDistributionSet(assignedSet, assignedTargets);
final List<Target> result = targetManagement
.findByTargetFilterQueryAndNonDS(PAGE, assignedSet.getId(), tfq.getQuery()).getContent();
assertThat(result).as("count of targets").hasSize(unassignedTargets.size()).as("contains all targets")
.containsAll(unassignedTargets);
}
@Test
@Description("Verfies that targets with given installed DS are returned from repository.")
public void findTargetByInstalledDistributionSet() {
final DistributionSet assignedSet = testdataFactory.createDistributionSet("");
final DistributionSet installedSet = testdataFactory.createDistributionSet("another");
testdataFactory.createTargets(10, "unassigned", "unassigned");
List<Target> installedtargets = testdataFactory.createTargets(10, "assigned", "assigned");
// set on installed and assign another one
assignDistributionSet(installedSet, installedtargets).getActions().forEach(actionId -> controllerManagement
.addUpdateActionStatus(entityFactory.actionStatus().create(actionId).status(Status.FINISHED)));
assignDistributionSet(assignedSet, installedtargets);
// get final updated version of targets
installedtargets = targetManagement
.getByControllerID(installedtargets.stream().map(Target::getControllerId).collect(Collectors.toList()));
assertThat(targetManagement.findByInstalledDistributionSet(PAGE, installedSet.getId()))
.as("Contains the assigned targets").containsAll(installedtargets)
.as("and that means the following expected amount").hasSize(10);
}
}
| epl-1.0 |
lhillah/pnmlframework | pnmlFw-SNNet/src/fr/lip6/move/pnml/symmetricnet/dots/impl/DotImpl.java | 6595 | /**
* Copyright 2009-2016 Université Paris Ouest and Sorbonne Universités,
Univ. Paris 06 - CNRS UMR 7606 (LIP6)
*
* 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
*
* Project leader / Initial Contributor:
* Lom Messan Hillah - <lom-messan.hillah@lip6.fr>
*
* Contributors:
* ${ocontributors} - <$oemails}>
*
* Mailing list:
* lom-messan.hillah@lip6.fr
*/
/**
* (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6/MoVe)
* 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:
* Lom HILLAH (LIP6) - Initial models and implementation
* Rachid Alahyane (UPMC) - Infrastructure and continuous integration
* Bastien Bouzerau (UPMC) - Architecture
* Guillaume Giffo (UPMC) - Code generation refactoring, High-level API
*/
package fr.lip6.move.pnml.symmetricnet.dots.impl;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.List;
import org.apache.axiom.om.OMElement;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.ecore.EClass;
import fr.lip6.move.pnml.framework.general.PnmlExport;
import fr.lip6.move.pnml.framework.utils.IdRefLinker;
import fr.lip6.move.pnml.framework.utils.ModelRepository;
import fr.lip6.move.pnml.framework.utils.PNMLEncoding;
import fr.lip6.move.pnml.framework.utils.PrettyPrintData;
import fr.lip6.move.pnml.framework.utils.exception.InnerBuildException;
import fr.lip6.move.pnml.framework.utils.exception.InvalidIDException;
import fr.lip6.move.pnml.framework.utils.exception.VoidRepositoryException;
import fr.lip6.move.pnml.symmetricnet.dots.Dot;
import fr.lip6.move.pnml.symmetricnet.dots.DotsFactory;
import fr.lip6.move.pnml.symmetricnet.dots.DotsPackage;
import fr.lip6.move.pnml.symmetricnet.terms.Sort;
import fr.lip6.move.pnml.symmetricnet.terms.impl.BuiltInSortImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Dot</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class DotImpl extends BuiltInSortImpl implements Dot {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DotImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return DotsPackage.Literals.DOT;
}
/**
* Return the string containing the pnml output
*/
@Override
public String toPNML() {
//id 0
//idref 0
//attributes 0
//sons 0
Boolean prettyPrintStatus = ModelRepository.getInstance().isPrettyPrintActive();
String retline = "";
String headline = "";
PrettyPrintData prpd = null;
if (prettyPrintStatus) {
retline = "\n";
prpd = ModelRepository.getInstance().getPrettyPrintData();
headline = prpd.getCurrentLineHeader();
}
StringBuilder sb = new StringBuilder();
sb.append(headline);
sb.append("<dot");
if (prettyPrintStatus) {
headline = prpd.increaseLineHeaderLevel();
}
//begin attributes, id and id ref processing
sb.append("/>");
sb.append(retline);
//sons, follow processing
/****/
if (prettyPrintStatus) {
headline = prpd.decreaseLineHeaderLevel();
}
return sb.toString();
}
@Override
@SuppressWarnings("unchecked")
public void fromPNML(OMElement locRoot, IdRefLinker idr) throws InnerBuildException, InvalidIDException,
VoidRepositoryException {
//0
//0
//0
//0
@SuppressWarnings("unused")
DotsFactory fact = DotsFactory.eINSTANCE;
//processing id
//processing idref
//processing attributes
//processing sons
}
/**
* Return the string containing the pnml output
*/
@Override
public void toPNML(FileChannel fc) {
//id 0
//idref 0
//attributes 0
//sons 0
final int bufferSizeKB = 8;
final int bufferSize = bufferSizeKB * 1024;
final ByteBuffer bytebuf = ByteBuffer.allocateDirect(bufferSize);
final String charsetEncoding = PNMLEncoding.UTF_8.getName();
Boolean prettyPrintStatus = ModelRepository.getInstance().isPrettyPrintActive();
String retline = "";
String headline = "";
PrettyPrintData prpd = null;
if (prettyPrintStatus) {
retline = "\n";
prpd = ModelRepository.getInstance().getPrettyPrintData();
headline = prpd.getCurrentLineHeader();
}
StringBuilder sb = new StringBuilder();
sb.append(headline);
sb.append("<dot");
if (prettyPrintStatus) {
headline = prpd.increaseLineHeaderLevel();
}
//begin attributes, id and id ref processing
sb.append("/>");
sb.append(retline);
//sons, follow processing
/****/
if (prettyPrintStatus) {
headline = prpd.decreaseLineHeaderLevel();
}
try {
writeIntoStream(bytebuf, fc, sb.toString().getBytes(Charset.forName(charsetEncoding)));
} catch (IOException io) {
io.printStackTrace();
// fail fast
return;
}
sb = null;
}
/**
* Writes buffer of a given max size into file channel.
*/
private static final void writeIntoStream(final ByteBuffer bytebuf, final FileChannel fc, final byte[] contents)
throws IOException {
final int chopSize = 6 * 1024;
if (contents.length >= bytebuf.capacity()) {
List<byte[]> chops = PnmlExport.chopBytes(contents, chopSize);
for (byte[] buf : chops) {
bytebuf.put(buf);
bytebuf.flip();
fc.write(bytebuf);
bytebuf.clear();
}
} else {
bytebuf.put(contents);
bytebuf.flip();
fc.write(bytebuf);
bytebuf.clear();
}
}
/**
* -
*/
@Override
public boolean validateOCL(DiagnosticChain diagnostics) {
//this package has no validator class
return true;
}
@Override
public boolean equalSorts(Sort sort) {
boolean isEqual = false;
if (this.eClass().getName().equalsIgnoreCase(sort.eClass().getName())) {
//by default they are the same sort, unless they have been named.
isEqual = true;
if (this.getContainerNamedSort() != null && sort.getContainerNamedSort() != null) {
// we test them if they have been explicitly named.
isEqual = this.getContainerNamedSort().getName()
.equalsIgnoreCase(sort.getContainerNamedSort().getName());
}// otherwise, keep the default.
}
return isEqual;
}
} //DotImpl
| epl-1.0 |
debabratahazra/OptimaLA | Optima/com.ose.cdt.launch/src/com/ose/cdt/launch/internal/DebugActionDelegate.java | 7388 | /* COPYRIGHT-ENEA-SRC-R2 *
**************************************************************************
* Copyright (C) 2005-2007 by Enea Software AB.
* All rights reserved.
*
* This Software is furnished under a software license agreement and
* may be used only in accordance with the terms of such agreement.
* Any other use or reproduction is prohibited. No title to and
* ownership of the Software is hereby transferred.
*
* PROPRIETARY NOTICE
* This Software consists of confidential information.
* Trade secret law and copyright law protect this Software.
* The above notice of copyright on this Software does not indicate
* any actual or intended publication of such Software.
**************************************************************************
* COPYRIGHT-END */
package com.ose.cdt.launch.internal;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.cdt.debug.mi.core.IMILaunchConfigurationConstants;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import com.ose.cdt.debug.mi.core.GDBDebugger;
import com.ose.cdt.debug.mi.core.IOSEMILaunchConfigurationConstants;
import com.ose.cdt.launch.internal.ui.LaunchUIPlugin;
import com.ose.launch.IOSELaunchConfigurationConstants;
import com.ose.system.Block;
import com.ose.system.Gate;
import com.ose.system.Process;
import com.ose.system.SystemModelNode;
import com.ose.system.Target;
public class DebugActionDelegate extends LaunchActionDelegate
{
private Process node;
public void selectionChanged(IAction action, ISelection selection)
{
Object obj = null;
if (selection instanceof IStructuredSelection)
{
obj = ((IStructuredSelection) selection).getFirstElement();
}
node = ((obj instanceof Process) ? ((Process) obj) : null);
}
protected SystemModelNode getSystemModelNode()
{
return node;
}
protected String getLaunchMode()
{
return ILaunchManager.DEBUG_MODE;
}
protected String getLaunchGroup()
{
return IDebugUIConstants.ID_DEBUG_LAUNCH_GROUP;
}
protected ILaunchConfigurationType getLaunchConfigurationType()
{
String configTypeId;
ILaunchConfigurationType configType;
if (node == null)
{
throw new IllegalStateException();
}
configTypeId = (node.getTarget().isPostMortemMonitor() ?
IOSELaunchConfigurationConstants.ID_LAUNCH_DUMP :
(node.getBlock().getSid() == 0) ?
IOSELaunchConfigurationConstants.ID_LAUNCH_CORE_MODULE :
IOSELaunchConfigurationConstants.ID_LAUNCH_LOAD_MODULE);
configType = DebugPlugin.getDefault().getLaunchManager()
.getLaunchConfigurationType(configTypeId);
return configType;
}
protected ILaunchConfiguration editLaunchConfiguration(
ILaunchConfigurationWorkingCopy wc,
String configTypeId,
SystemModelNode node)
{
ILaunchConfiguration config = null;
if (!(node instanceof Process))
{
return null;
}
try
{
Process process = (Process) node;
Block block = process.getBlock();
Target target = block.getTarget();
Gate gate = target.getGate();
wc.setAttribute(
IOSELaunchConfigurationConstants.ATTR_GATE_ADDRESS,
gate.getAddress().getHostAddress());
wc.setAttribute(
IOSELaunchConfigurationConstants.ATTR_GATE_PORT,
gate.getPort());
wc.setAttribute(
IOSELaunchConfigurationConstants.ATTR_TARGET_HUNT_PATH,
target.getHuntPath());
if (configTypeId.equals(IOSELaunchConfigurationConstants.ID_LAUNCH_CORE_MODULE))
{
wc.setAttribute(
IOSELaunchConfigurationConstants.ATTR_BOOT_DOWNLOAD,
false);
}
else if (configTypeId.equals(IOSELaunchConfigurationConstants.ID_LAUNCH_LOAD_MODULE))
{
wc.setAttribute(
IOSELaunchConfigurationConstants.ATTR_LM_DOWNLOAD,
false);
}
else if (configTypeId.equals(IOSELaunchConfigurationConstants.ID_LAUNCH_DUMP))
{
wc.setAttribute(
IOSELaunchConfigurationConstants.ATTR_DUMP_MONITOR_MANAGED,
false);
}
wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_ID,
IOSEMILaunchConfigurationConstants.OSE_DEBUGGER_ID);
if (target.isPostMortemMonitor())
{
wc.setAttribute(
ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_START_MODE,
ICDTLaunchConfigurationConstants.DEBUGGER_MODE_CORE);
}
else
{
wc.setAttribute(
ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_START_MODE,
ICDTLaunchConfigurationConstants.DEBUGGER_MODE_RUN);
}
wc.setAttribute(
ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN,
false);
wc.setAttribute(IMILaunchConfigurationConstants.ATTR_DEBUGGER_PROTOCOL,
"mi");
if (wc.getAttribute(IMILaunchConfigurationConstants.ATTR_DEBUG_NAME,
(String) null) == null)
{
wc.setAttribute(IMILaunchConfigurationConstants.ATTR_DEBUG_NAME,
getGDB(process));
}
wc.setAttribute(IOSEMILaunchConfigurationConstants.ATTR_DEBUG_SCOPE,
getDebugScope());
wc.setAttribute(IOSEMILaunchConfigurationConstants.ATTR_SEGMENT_ID,
"0x" + Integer.toHexString(block.getSid()).toUpperCase());
wc.setAttribute(IOSEMILaunchConfigurationConstants.ATTR_BLOCK_ID,
"0x" + Integer.toHexString(process.getBid()).toUpperCase());
wc.setAttribute(IOSEMILaunchConfigurationConstants.ATTR_PROCESS_ID,
"0x" + Integer.toHexString(process.getId()).toUpperCase());
config = wc.doSave();
}
catch (CoreException e)
{
LaunchUIPlugin.log(e);
}
return config;
}
private static String getGDB(Process process)
{
String gdbName;
String gdbPath;
switch (process.getTarget().getCpuType())
{
case Target.CPU_ARM:
gdbName = IOSEMILaunchConfigurationConstants.VALUE_DEBUG_NAME_ARM;
break;
case Target.CPU_MIPS:
gdbName = IOSEMILaunchConfigurationConstants.VALUE_DEBUG_NAME_MIPS;
break;
case Target.CPU_PPC:
gdbName = IOSEMILaunchConfigurationConstants.VALUE_DEBUG_NAME_POWERPC;
break;
default:
return IOSEMILaunchConfigurationConstants.VALUE_DEBUG_NAME_NATIVE;
}
gdbPath = GDBDebugger.findGDB(gdbName);
return ((gdbPath != null) ? gdbPath : gdbName);
}
}
| epl-1.0 |
theArchonius/gerrit-attachments | src/main/java/com/eclipsesource/gerrit/plugins/fileattachment/api/entities/JsonEntity.java | 308 | /**
*
*/
package com.eclipsesource.gerrit.plugins.fileattachment.api.entities;
/**
* Represents an JSON entity that is passed between the client and the server.
* This is the base interface that should be used for all JSON entities.
*
* @author Florian Zoubek
*
*/
public interface JsonEntity {
}
| epl-1.0 |
lincolnthree/windup | config/tests/src/test/java/org/jboss/windup/config/iteration/RuleIterationOverDefaultListVariableTest.java | 6208 | package org.jboss.windup.config.iteration;
import java.nio.file.Path;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.AddonDependencies;
import org.jboss.forge.arquillian.archive.AddonArchive;
import org.jboss.forge.furnace.util.OperatingSystemUtils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.windup.config.AbstractRuleProvider;
import org.jboss.windup.config.DefaultEvaluationContext;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.config.RuleSubset;
import org.jboss.windup.config.metadata.MetadataBuilder;
import org.jboss.windup.config.operation.GraphOperation;
import org.jboss.windup.config.operation.Iteration;
import org.jboss.windup.config.query.Query;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.GraphContextFactory;
import org.jboss.windup.graph.model.WindupConfigurationModel;
import org.jboss.windup.graph.service.FileService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ocpsoft.rewrite.config.Configuration;
import org.ocpsoft.rewrite.config.ConfigurationBuilder;
import org.ocpsoft.rewrite.context.EvaluationContext;
import org.ocpsoft.rewrite.param.DefaultParameterValueStore;
import org.ocpsoft.rewrite.param.ParameterValueStore;
/**
* Testing the Iteration.over() approach.
*
* @author <a href="mailto:mbriskar@gmail.com">Matej Briskar</a>
*
*/
@RunWith(Arquillian.class)
public class RuleIterationOverDefaultListVariableTest
{
public static int TestSimple2ModelCounter = 0;
public static int TestSimple1ModelCounter = 0;
@Deployment
@AddonDependencies({
@AddonDependency(name = "org.jboss.windup.config:windup-config"),
@AddonDependency(name = "org.jboss.windup.graph:windup-graph"),
@AddonDependency(name = "org.jboss.windup.rules.apps:windup-rules-java"),
@AddonDependency(name = "org.jboss.forge.furnace.container:cdi")
})
public static AddonArchive getDeployment()
{
final AddonArchive archive = ShrinkWrap.create(AddonArchive.class)
.addBeansXML()
.addClasses(
TestRuleIterationOverDefaultListVariableProvider.class,
TestSimple1Model.class,
TestSimple2Model.class);
return archive;
}
@Inject
private GraphContextFactory factory;
private DefaultEvaluationContext createEvalContext(GraphRewrite event)
{
final DefaultEvaluationContext evaluationContext = new DefaultEvaluationContext();
final DefaultParameterValueStore values = new DefaultParameterValueStore();
evaluationContext.put(ParameterValueStore.class, values);
return evaluationContext;
}
@Test
public void testTypeSelection() throws Exception
{
final Path folder = OperatingSystemUtils.createTempDir().toPath();
try (final GraphContext context = factory.create(folder))
{
TestSimple1Model vertex = context.getFramed().addVertex(null, TestSimple1Model.class);
context.getFramed().addVertex(null, TestSimple2Model.class);
context.getFramed().addVertex(null, TestSimple2Model.class);
GraphRewrite event = new GraphRewrite(context);
DefaultEvaluationContext evaluationContext = createEvalContext(event);
WindupConfigurationModel windupCfg = context.getFramed().addVertex(null, WindupConfigurationModel.class);
FileService fileModelService = new FileService(context);
windupCfg.setInputPath(fileModelService.createByFilePath(OperatingSystemUtils.createTempDir()
.getAbsolutePath()));
TestRuleIterationOverDefaultListVariableProvider provider = new TestRuleIterationOverDefaultListVariableProvider();
Configuration configuration = provider.getConfiguration(context);
// this should call perform()
RuleSubset.create(configuration).perform(event, evaluationContext);
Assert.assertEquals(TestSimple1ModelCounter, 1);
Assert.assertEquals(TestSimple2ModelCounter, 2);
vertex.asVertex().remove();
// this should call otherwise()
RuleSubset.create(configuration).perform(event, evaluationContext);
Assert.assertEquals(TestSimple1ModelCounter, 1);
Assert.assertEquals(TestSimple2ModelCounter, 4);
}
}
public class TestRuleIterationOverDefaultListVariableProvider extends AbstractRuleProvider
{
public TestRuleIterationOverDefaultListVariableProvider()
{
super(MetadataBuilder.forProvider(TestRuleIterationOverDefaultListVariableProvider.class));
}
// @formatter:off
@Override
public Configuration getConfiguration(GraphContext context)
{
Configuration configuration = ConfigurationBuilder.begin()
.addRule()
.when(Query.fromType(TestSimple2Model.class).as("abc"))
.perform(Iteration
.over()
.perform(new GraphOperation()
{
@Override
public void perform(GraphRewrite event, EvaluationContext context)
{
TestSimple2ModelCounter++;
}
})
.endIteration()
)
.addRule()
.when(Query.fromType(TestSimple1Model.class))
.perform(Iteration
.over()
.perform(new GraphOperation()
{
@Override
public void perform(GraphRewrite event, EvaluationContext context)
{
TestSimple1ModelCounter++;
}
})
.endIteration()
);
return configuration;
}
// @formatter:on
}
} | epl-1.0 |
sleshchenko/che | plugins/plugin-debugger/che-plugin-debugger-ide/src/main/java/org/eclipse/che/plugin/debugger/ide/configuration/DebugConfigurationsGroup.java | 2088 | /*
* Copyright (c) 2012-2018 Red Hat, 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:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.plugin.debugger.ide.configuration;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.ide.api.action.ActionManager;
import org.eclipse.che.ide.api.action.DefaultActionGroup;
import org.eclipse.che.ide.api.debug.DebugConfiguration;
import org.eclipse.che.ide.api.debug.DebugConfigurationsManager;
import org.eclipse.che.ide.api.debug.DebugConfigurationsManager.ConfigurationChangedListener;
/**
* Group of {@link DebugConfigurationAction}s.
*
* @author Artem Zatsarynnyi
*/
@Singleton
public class DebugConfigurationsGroup extends DefaultActionGroup
implements ConfigurationChangedListener {
private final DebugConfigurationsManager configurationsManager;
private final DebugConfigurationActionFactory debugConfigurationActionFactory;
@Inject
public DebugConfigurationsGroup(
ActionManager actionManager,
DebugConfigurationsManager debugConfigurationsManager,
DebugConfigurationActionFactory debugConfigurationActionFactory) {
super(actionManager);
configurationsManager = debugConfigurationsManager;
this.debugConfigurationActionFactory = debugConfigurationActionFactory;
debugConfigurationsManager.addConfigurationsChangedListener(this);
fillActions();
}
@Override
public void onConfigurationAdded(DebugConfiguration configuration) {
fillActions();
}
@Override
public void onConfigurationRemoved(DebugConfiguration configuration) {
fillActions();
}
private void fillActions() {
removeAll();
for (DebugConfiguration configuration : configurationsManager.getConfigurations()) {
add(debugConfigurationActionFactory.createAction(configuration));
}
}
}
| epl-1.0 |
cschwer/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee.console.ember/src/main/java/com/zsmartsystems/zigbee/console/ember/EmberConsoleNcpValueCommand.java | 4666 | /**
* Copyright (c) 2016-2019 by the respective copyright holders.
* 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 com.zsmartsystems.zigbee.console.ember;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import com.zsmartsystems.zigbee.ZigBeeNetworkManager;
import com.zsmartsystems.zigbee.dongle.ember.EmberNcp;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.structure.EzspStatus;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.structure.EzspValueId;
/**
* Reads or writes an NCP {@link EzspValueId}
*
* @author Chris Jackson
*
*/
public class EmberConsoleNcpValueCommand extends EmberConsoleAbstractCommand {
@Override
public String getCommand() {
return "ncpvalue";
}
@Override
public String getDescription() {
return "Read or write an NCP memory value";
}
@Override
public String getSyntax() {
return "[VALUEID] [VALUE]";
}
@Override
public String getHelp() {
return "VALUEID is the Ember NCP value enumeration\n" + "VALUE is the value to write\n"
+ "If VALUE is not defined, then the memory will be read.\n"
+ "If no arguments are supplied then all values will be displayed.";
}
@Override
public void process(ZigBeeNetworkManager networkManager, String[] args, PrintStream out)
throws IllegalArgumentException {
if (args.length > 3) {
throw new IllegalArgumentException("Incorrect number of arguments.");
}
EmberNcp ncp = getEmberNcp(networkManager);
if (args.length == 1) {
Map<EzspValueId, int[]> values = new TreeMap<>();
for (EzspValueId valueId : EzspValueId.values()) {
if (valueId == EzspValueId.UNKNOWN) {
continue;
}
values.put(valueId, ncp.getValue(valueId));
}
for (Entry<EzspValueId, int[]> value : values.entrySet()) {
out.print(String.format("%-50s", value.getKey()));
if (value.getValue() != null) {
out.print(displayValue(value.getKey(), value.getValue()));
}
out.println();
}
return;
}
EzspValueId valueId = EzspValueId.valueOf(args[1].toUpperCase());
if (args.length == 2) {
int[] value = ncp.getValue(valueId);
if (value == null) {
out.println("Error reading Ember NCP value " + valueId.toString());
} else {
out.println("Ember NCP value " + valueId.toString() + " is " + displayValue(valueId, value));
}
} else {
int[] value = parseInput(valueId, Arrays.copyOfRange(args, 2, args.length));
if (value == null) {
throw new IllegalArgumentException("Unable to convert data to value array");
}
EzspStatus response = ncp.setValue(valueId, value);
out.println("Writing Ember NCP value " + valueId.toString() + " was "
+ (response == EzspStatus.EZSP_SUCCESS ? "" : "un") + "successful.");
}
}
private String displayValue(EzspValueId valueId, int[] value) {
StringBuilder builder = new StringBuilder();
switch (valueId) {
default:
boolean first = true;
for (int intVal : value) {
if (!first) {
builder.append(' ');
}
first = false;
builder.append(String.format("%02X", intVal));
}
break;
}
return builder.toString();
}
private int[] parseInput(EzspValueId valueId, String[] args) {
int[] value = null;
switch (valueId) {
case EZSP_VALUE_APS_FRAME_COUNTER:
case EZSP_VALUE_NWK_FRAME_COUNTER:
Long longValue = Long.parseLong(args[0]);
value = new int[4];
value[0] = (int) (longValue & 0x000000FF);
value[1] = (int) (longValue & 0x0000FF00) >> 8;
value[2] = (int) (longValue & 0x00FF0000) >> 16;
value[3] = (int) (longValue & 0xFF000000) >> 24;
break;
default:
break;
}
return value;
}
}
| epl-1.0 |
BauhausLuftfahrt/PAXelerate | com.paxelerate.execution/src/com/paxelerate/execution/actions/ExportResultsAction.java | 2961 | /*******************************************************************************
* <copyright> Copyright (c) 2014 - 2021 Bauhaus Luftfahrt e.V.. All rights reserved. This program and the accompanying
* materials are made available under the terms of the GNU General Public License v3.0 which accompanies this distribution,
* and is available at https://www.gnu.org/licenses/gpl-3.0.html.en </copyright>
*******************************************************************************/
package com.paxelerate.execution.actions;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.paxelerate.core.simulation.astar.SimulationHandler;
import com.paxelerate.model.Deck;
import com.paxelerate.model.Model;
import com.paxelerate.model.ModelFactory;
import com.paxelerate.model.SimulationResult;
import com.paxelerate.model.agent.Passenger;
import net.bhl.opensource.toolbox.time.TimeHelper;
/**
* @author Michael.Schmidt, Marc.Engelmann
* @since 22.08.2019
*
*/
public class ExportResultsAction {
/**
*
* @param handler
* @param cabin
* @param boardingStatus
* @param time
* @param simulationTime
*/
static void setSimulationData(SimulationHandler handler, Model model, List<ArrayList<Integer>> boardingStatus,
double time, double simulationTime) {
Deck deck = model.getDeck();
SimulationResult result = ModelFactory.eINSTANCE.createSimulationResult();
model.getSimulationResults().add(result);
result.setPassengers(deck.getPassengers().size());
result.setBoardingTime(
handler.getMasterBoardingTime() * model.getSettings().getSimulationSpeedFactor() / 1000.0);
result.setSimulationTime(simulationTime);
result.setId(model.getSimulationResults().size() + 1);
result.setName(new SimpleDateFormat("dd.MM, HH:mm").format(new Date()));
result.setDate(new Date());
result.setBoardingTimeString(TimeHelper.toTimeOfDay(time));
result.setWaymakingCompleted(handler.getPassengersByState(null, true).stream()
.mapToInt(Passenger::getNumberOfMakeWayOperations).sum());
result.setLayoutConceptType(model.getSettings().getSeatType());
// result.setLuggageStorageFillingDegree(deck.getLuggageStorages().stream()
// .mapToDouble(s -> 100 - s.getFreeVolume() * 100 / s.getNetVolume()).average().orElse(0));
// TODO: WRONG!
// r.setTotalLargeBagsStowed(deck.getLuggageStorages().stream().mapToInt(l -> l.getMaximumLargeBags()).sum());
// result.setTotalStorageVolume(
// deck.getLuggageStorages().stream().mapToDouble(LuggageStorage::getNetVolume).sum());
result.setAverageNumberOfActivePassengers(
(int) boardingStatus.stream().mapToDouble(l -> l.get(2)).average().orElse(0));
result.setMaxNumberOfActivePassengers(boardingStatus.stream().mapToInt(l -> l.get(2)).max().orElse(0));
result.setAverageNumberOfBags(
deck.getPassengers().stream().mapToDouble(p -> p.getLuggage().size()).average().orElse(0));
}
}
| epl-1.0 |
gorindn/ice | src/org.eclipse.ice.datastructures/src/org/eclipse/ice/datastructures/form/MeshComponent.java | 13129 | /*******************************************************************************
* Copyright (c) 2014 UT-Battelle, LLC.
* 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:
* Initial API and implementation and/or initial documentation - Jay Jay Billings,
* Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson,
* Claire Saunders, Matthew Wang, Anna Wojtowicz
*******************************************************************************/
package org.eclipse.ice.datastructures.form;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.ice.datastructures.ICEObject.Component;
import org.eclipse.ice.datastructures.ICEObject.ICEObject;
import org.eclipse.ice.datastructures.componentVisitor.IComponentVisitor;
import org.eclipse.ice.viz.service.datastructures.IVizUpdateable;
import org.eclipse.ice.viz.service.datastructures.IVizUpdateableListener;
import org.eclipse.ice.viz.service.mesh.datastructures.Edge;
import org.eclipse.ice.viz.service.mesh.datastructures.IMeshPart;
import org.eclipse.ice.viz.service.mesh.datastructures.IMeshPartVisitor;
import org.eclipse.ice.viz.service.mesh.datastructures.Polygon;
import org.eclipse.ice.viz.service.mesh.datastructures.Vertex;
import org.eclipse.ice.viz.service.mesh.datastructures.VizMeshComponent;
/**
* <p>
* A wrapper class for a VizMeshComponent. It provides all the functionality of
* a VizMeshComponent, but delegates to a wrapped VizMeshComponent for all
* actual implementations.
* </p>
*
* @author Jordan H. Deyton
* @author Robert Smith
*/
@XmlRootElement(name = "MeshComponent")
@XmlAccessorType(XmlAccessType.FIELD)
public class MeshComponent extends ICEObject implements Component, IMeshPart,
IVizUpdateableListener {
/**
* The wrapped VizMeshComponent.
*/
private VizMeshComponent mesh;
/**
* <p>
* The default constructor for a MeshComponent. Initializes the list of
* polygons and any associated bookkeeping structures.
* </p>
*
*/
public MeshComponent() {
super();
mesh = new VizMeshComponent();
mesh.register(this);
return;
}
/**
* Getter method for the wrapped VizMeshComponent
*
* @return The wrapped VizMeshComponent
*/
public VizMeshComponent getMesh() {
return mesh;
}
/**
* Setter method for the wrapped VizMeshComponent
*
* @param newMesh
* The new mesh to hold
*/
public void setMesh(VizMeshComponent newMesh) {
mesh = newMesh;
}
/**
* <p>
* Adds a polygon to the MeshComponent. The polygon is expected to have a
* unique polygon ID. If the polygon can be added, a notification is sent to
* listeners. If the polygon uses equivalent vertices or edges with
* different references, then a new polygon is created with references to
* the vertices and edges already known by this MeshComponent.
* </p>
*
* @param polygon
* <p>
* The new polygon to add to the existing list.
* </p>
*/
public void addPolygon(Polygon polygon) {
mesh.addPolygon(polygon);
notifyListeners();
return;
}
/**
* <p>
* Removes a polygon from the MeshComponent. This will also remove any
* vertices and edges used only by this polygon. If a polygon was removed, a
* notification is sent to listeners.
* </p>
*
* @param id
* <p>
* The ID of the polygon to remove from the existing list.
* </p>
*/
public void removePolygon(int id) {
mesh.removePolygon(id);
notifyListeners();
return;
}
/**
* <p>
* Removes a list polygons from the MeshComponent. This will also remove any
* vertices and edges used by these polygons. If a polygon was removed, a
* notification is sent to listeners.
* </p>
*
* @param ids
* <p>
* An ArrayList containing the IDs of the polygons to remove from
* the MeshComponent.
* </p>
*/
public void removePolygons(ArrayList<Integer> ids) {
mesh.removePolygons(ids);
notifyListeners();
return;
}
/**
* <p>
* Gets a list of all polygons stored in the MeshComponent ordered by their
* IDs.
* </p>
*
* @return <p>
* A list of polygons contained in this MeshComponent.
* </p>
*/
public ArrayList<Polygon> getPolygons() {
return mesh.getPolygons();
}
/**
* <p>
* Gets a Polygon instance corresponding to an ID.
* </p>
*
* @param id
* <p>
* The ID of the polygon.
* </p>
* @return <p>
* The polygon referred to by the ID, or null if there is no polygon
* with the ID.
* </p>
*/
public Polygon getPolygon(int id) {
return mesh.getPolygon(id);
}
/**
* <p>
* Returns the next available ID for polygons.
* </p>
*
* @return <p>
* The greatest polygon ID (or zero) plus one.
* </p>
*/
public int getNextPolygonId() {
return mesh.getNextPolygonId();
}
/**
* <p>
* Sets the list of all polygons stored in the MeshComponent.
* </p>
*
* @param polygons
* <p>
* The list of polygons to replace the existing list of polygons
* in the MeshComponent.
* </p>
*/
public void setPolygons(ArrayList<Polygon> polygons) {
mesh.setPolygons(polygons);
}
/**
* <p>
* Gets a list of all vertices associated with this MeshComponent.
* </p>
*
* @return <p>
* All vertices managed by this MeshComponent.
* </p>
*/
public ArrayList<Vertex> getVertices() {
return mesh.getVertices();
}
/**
* <p>
* Gets a Vertex instance corresponding to an ID.
* </p>
*
* @param id
* <p>
* The ID of the vertex.
* </p>
* @return <p>
* The vertex referred to by the ID, or null if the ID is invalid.
* </p>
*/
public Vertex getVertex(int id) {
return mesh.getVertex(id);
}
/**
* <p>
* Returns the next available ID for vertices.
* </p>
*
* @return <p>
* The greatest vertex ID (or zero) plus one.
* </p>
*/
public int getNextVertexId() {
return mesh.getNextVertexId();
}
/**
* <p>
* Gets a list of all edges associated with this MeshComponent.
* </p>
*
* @return <p>
* All edges managed by this MeshComponent.
* </p>
*/
public ArrayList<Edge> getEdges() {
return mesh.getEdges();
}
/**
* <p>
* Gets an Edge instance corresponding to an ID.
* </p>
*
* @param id
* <p>
* The ID of the edge.
* </p>
* @return <p>
* The edge referred to by the ID, or null if the ID is invalid.
* </p>
*/
public Edge getEdge(int id) {
return mesh.getEdge(id);
}
/**
* <p>
* Returns the next available ID for edges.
* </p>
*
* @return <p>
* The greatest edge ID (or zero) plus one.
* </p>
*/
public int getNextEdgeId() {
return mesh.getNextEdgeId();
}
/**
* <p>
* Returns a list of Edges attached to the Vertex with the specified ID.
* </p>
*
* @param id
* <p>
* The ID of the vertex.
* </p>
* @return <p>
* An ArrayList of Edges that are attached to the vertex with the
* specified ID. If there are no such edges, e.g., if the vertex ID
* is invalid, the list will be empty.
* </p>
*/
public ArrayList<Edge> getEdgesFromVertex(int id) {
return getEdgesFromVertex(id);
}
/**
* <p>
* Returns a list of Polygons containing the Vertex with the specified ID.
* </p>
*
* @param id
* <p>
* The ID of the vertex.
* </p>
* @return <p>
* An ArrayList of Polygons that contain the vertex with the
* specified ID. If there are no such polygons, e.g., if the vertex
* ID is invalid, the list will be empty.
* </p>
*/
public ArrayList<Polygon> getPolygonsFromVertex(int id) {
return mesh.getPolygonsFromVertex(id);
}
/**
* <p>
* Returns a list of Polygons containing the Edge with the specified ID.
* </p>
*
* @param id
* <p>
* The ID of the edge.
* </p>
* @return <p>
* An ArrayList of Polygons that contain the edge with the specified
* ID. If there are no such polygons, e.g., if the edge ID is
* invalid, the list will be empty.
* </p>
*/
public ArrayList<Polygon> getPolygonsFromEdge(int id) {
return mesh.getPolygonsFromEdge(id);
}
/**
* <p>
* Returns an Edge that connects two specified vertices if one exists.
* </p>
*
* @param firstId
* <p>
* The ID of the first vertex.
* </p>
* @param secondId
* <p>
* The ID of the second vertex.
* </p>
*
* @return <p>
* An Edge instance that connects the first and second vertices, or
* null if no such edge exists.
* </p>
*/
public Edge getEdgeFromVertices(int firstId, int secondId) {
return mesh.getEdgeFromVertices(firstId, secondId);
}
/**
* <p>
* Returns a list containing all Polygons in the MeshComponent whose
* vertices are a subset of the supplied list of vertices.
* </p>
*
* @param vertices
* <p>
* A collection of vertices.
* </p>
* @return <p>
* An ArrayList of all Polygons in the MeshComponent that are
* composed of some subset of the specified vertices.
* </p>
*/
public ArrayList<Polygon> getPolygonsFromVertices(ArrayList<Vertex> vertices) {
return mesh.getPolygonsFromVertices(vertices);
}
/**
* <p>
* This operation returns the hash value of the MeshComponent.
* </p>
*
* @return <p>
* The hashcode of the ICEObject.
* </p>
*/
@Override
public int hashCode() {
return mesh.hashCode();
}
/**
* <p>
* This operation is used to check equality between this MeshComponent and
* another MeshComponent. It returns true if the MeshComponents are equal
* and false if they are not.
* </p>
*
* @param otherObject
* <p>
* The other ICEObject that should be compared with this one.
* </p>
* @return <p>
* True if the ICEObjects are equal, false otherwise.
* </p>
*/
@Override
public boolean equals(Object otherObject) {
// By default, the objects are not equivalent.
boolean equals = false;
// Check the reference.
if (this == otherObject) {
equals = true;
}
// Check the information stored in the other object.
else if (otherObject != null && otherObject instanceof MeshComponent) {
// We can now cast the other object.
MeshComponent component = (MeshComponent) otherObject;
// Compare the values between the two objects.
equals = (super.equals(otherObject) && mesh.equals(component.mesh));
// The polygons are the only defining feature of the MeshComponent
// (aside from the super properties). If the polygon lists are
// equivalent, we can safely expect the other bookkeeping structures
// are identical.
}
return equals;
}
/**
* <p>
* This operation copies the contents of a MeshComponent into the current
* object using a deep copy.
* </p>
*
* @param component
* <p>
* The ICEObject from which the values should be copied
* </p>
*/
public void copy(MeshComponent component) {
// Check the parameters.
if (component != null) {
super.copy(component);
mesh.copy(component.mesh);
notifyListeners();
}
return;
}
/**
* <p>
* This operation returns a clone of the MeshComponent using a deep copy.
* </p>
*
* @return <p>
* The new clone
* </p>
*/
@Override
public Object clone() {
// Initialize a new object.
MeshComponent object = new MeshComponent();
// Copy the contents from this one.
object.copy(this);
// Return the newly instantiated object.
return object;
}
/**
* (non-Javadoc)
*
* @see Component#accept(IComponentVisitor visitor)
*/
@Override
public void accept(IComponentVisitor visitor) {
// Call the visitor's visit(MeshComponent) method.
if (visitor != null) {
visitor.visit(this);
}
return;
}
/**
* <p>
* This method calls the {@link IMeshPartVisitor}'s visit method.
* </p>
*
* @param visitor
* <p>
* The {@link IMeshPartVisitor} that is visiting this
* {@link IMeshPart}.
* </p>
*/
@Override
public void acceptMeshVisitor(IMeshPartVisitor visitor) {
if (visitor != null) {
visitor.visit(this);
}
return;
}
@Override
public void update(IVizUpdateable component) {
notifyListeners();
}
} | epl-1.0 |
ot4i/service-facade-mq-request-response-pattern | src/com.ibm.etools.mft.pattern.sen/jet2java/org/eclipse/jet/compiled/_jet_Erroresql_0.java | 18882 | package org.eclipse.jet.compiled;
import org.eclipse.jet.JET2Context;
import org.eclipse.jet.JET2Template;
import org.eclipse.jet.JET2Writer;
import org.eclipse.jet.taglib.RuntimeTagElement;
import org.eclipse.jet.taglib.TagInfo;
public class _jet_Erroresql_0 implements JET2Template {
private static final String _jetns_c = "org.eclipse.jet.controlTags"; //$NON-NLS-1$
public _jet_Erroresql_0() {
super();
}
private static final String NL = System.getProperty("line.separator"); //$NON-NLS-1$
private static final TagInfo _td_c_if_5_1 = new TagInfo("c:if", //$NON-NLS-1$
5, 1,
new String[] {
"test", //$NON-NLS-1$
},
new String[] {
"boolean($root/brokerSchema)", //$NON-NLS-1$
} );
private static final TagInfo _td_c_if_7_1 = new TagInfo("c:if", //$NON-NLS-1$
7, 1,
new String[] {
"test", //$NON-NLS-1$
},
new String[] {
"string-length($root/brokerSchema) > 0", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_9_15 = new TagInfo("c:get", //$NON-NLS-1$
9, 15,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/brokerSchema", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_12_18 = new TagInfo("c:get", //$NON-NLS-1$
12, 18,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/@patternName", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_12_63 = new TagInfo("c:get", //$NON-NLS-1$
12, 63,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/@patternVersion", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_13_23 = new TagInfo("c:get", //$NON-NLS-1$
13, 23,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/@patternName", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_14_26 = new TagInfo("c:get", //$NON-NLS-1$
14, 26,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/@patternVersion", //$NON-NLS-1$
} );
public void generate(final JET2Context context, final JET2Writer __out) {
JET2Writer out = __out;
com.ibm.etools.mft.pattern.sen.plugin.PatternPlugin pattern = com.ibm.etools.mft.pattern.sen.plugin.PatternPlugin.getInstance();
com.ibm.etools.mft.pattern.sen.sf.onewayackmq.PatternMessages messages = new com.ibm.etools.mft.pattern.sen.sf.onewayackmq.PatternMessages();
RuntimeTagElement _jettag_c_if_5_1 = context.getTagFactory().createRuntimeTag(_jetns_c, "if", "c:if", _td_c_if_5_1); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_if_5_1.setRuntimeParent(null);
_jettag_c_if_5_1.setTagInfo(_td_c_if_5_1);
_jettag_c_if_5_1.doStart(context, out);
while (_jettag_c_if_5_1.okToProcessBody()) {
// Tag exists
RuntimeTagElement _jettag_c_if_7_1 = context.getTagFactory().createRuntimeTag(_jetns_c, "if", "c:if", _td_c_if_7_1); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_if_7_1.setRuntimeParent(_jettag_c_if_5_1);
_jettag_c_if_7_1.setTagInfo(_td_c_if_7_1);
_jettag_c_if_7_1.doStart(context, out);
while (_jettag_c_if_7_1.okToProcessBody()) {
// and has a value
out.write("BROKER SCHEMA "); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_9_15 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_9_15); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_9_15.setRuntimeParent(_jettag_c_if_7_1);
_jettag_c_get_9_15.setTagInfo(_td_c_get_9_15);
_jettag_c_get_9_15.doStart(context, out);
_jettag_c_get_9_15.doEnd();
out.write(NL);
_jettag_c_if_7_1.handleBodyContent(out);
}
_jettag_c_if_7_1.doEnd();
_jettag_c_if_5_1.handleBodyContent(out);
}
_jettag_c_if_5_1.doEnd();
out.write("-- Generated by "); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_12_18 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_12_18); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_12_18.setRuntimeParent(null);
_jettag_c_get_12_18.setTagInfo(_td_c_get_12_18);
_jettag_c_get_12_18.doStart(context, out);
_jettag_c_get_12_18.doEnd();
out.write(" Version "); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_12_63 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_12_63); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_12_63.setRuntimeParent(null);
_jettag_c_get_12_63.setTagInfo(_td_c_get_12_63);
_jettag_c_get_12_63.doStart(context, out);
_jettag_c_get_12_63.doEnd();
out.write(NL);
out.write("-- $MQSI patternName="); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_13_23 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_13_23); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_13_23.setRuntimeParent(null);
_jettag_c_get_13_23.setTagInfo(_td_c_get_13_23);
_jettag_c_get_13_23.doStart(context, out);
_jettag_c_get_13_23.doEnd();
out.write(" MQSI$"); //$NON-NLS-1$
out.write(NL);
out.write("-- $MQSI patternVersion="); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_14_26 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_14_26); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_14_26.setRuntimeParent(null);
_jettag_c_get_14_26.setTagInfo(_td_c_get_14_26);
_jettag_c_get_14_26.doStart(context, out);
_jettag_c_get_14_26.doEnd();
out.write(" MQSI$"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("DECLARE ErrorLoggingOn EXTERNAL BOOLEAN TRUE;"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("CREATE COMPUTE MODULE SF_Build_Error_Message"); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$
out.write(NL);
out.write("\tBEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET OutputRoot.Properties = NULL;"); //$NON-NLS-1$
out.write(NL);
out.write("\t-- No MQMD header so create domain "); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FIRSTCHILD OF OutputRoot DOMAIN ('MQMD') NAME 'MQMD';"); //$NON-NLS-1$
out.write(NL);
out.write("\tDECLARE MQMDRef REFERENCE TO OutputRoot.MQMD;"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET MQMDRef.Version = MQMD_CURRENT_VERSION;"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET MQMDRef.ApplIdentityData = SQL.BrokerName;"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET MQMDRef.CodedCharSetId = InputRoot.Properties.CodedCharSetId;"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET MQMDRef.Encoding = InputRoot.Properties.Encoding;"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("\tCREATE NEXTSIBLING OF MQMDRef DOMAIN('XMLNSC') NAME 'XMLNSC';"); //$NON-NLS-1$
out.write(NL);
out.write("\tDECLARE OutRef REFERENCE TO OutputRoot.XMLNSC;"); //$NON-NLS-1$
out.write(NL);
out.write("\t-- Create error data\t"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET OutRef.Error.BrokerName = SQL.BrokerName;"); //$NON-NLS-1$
out.write(NL);
out.write("\tMOVE OutRef TO OutputRoot.XMLNSC.Error;"); //$NON-NLS-1$
out.write(NL);
out.write(" SET OutRef.MessageFlowLabel = SQL.MessageFlowLabel; "); //$NON-NLS-1$
out.write(NL);
out.write(" SET OutRef.DTSTAMP = CURRENT_TIMESTAMP; "); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("\tCall AddExceptionData();"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND;"); //$NON-NLS-1$
out.write(NL);
out.write(" "); //$NON-NLS-1$
out.write(NL);
out.write("CREATE PROCEDURE AddExceptionData() BEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE ERef REFERENCE TO OutputRoot.XMLNSC.Error; "); //$NON-NLS-1$
out.write(NL);
out.write("\t -- Add some exception data for error and fault"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE Error INTEGER;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE Text CHARACTER;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE Label CHARACTER;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDeclare FaultText CHARACTER '"); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.1") );
out.write("';"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE I INTEGER 1;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE K INTEGER;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE start REFERENCE TO InputExceptionList.*[1];"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("\t\tWHILE start.Number IS NOT NULL DO "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tSET Label = start.Label;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tSET Error = start.Number;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tIF Error = 3001 THEN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET Text = start.Insert.Text;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tELSE"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET Text = start.Text;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tEND IF;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t-- Don't include the \"Caught exception and rethrowing message\""); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tIF Error <> 2230 THEN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t-- Process inserts"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tDECLARE Inserts Character;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tDECLARE INS Integer;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSet Inserts = '';"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t-- Are there any inserts for this exception"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tIF EXISTS (start.Insert[]) THEN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t-- If YES add them to inserts string"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t \tSET Inserts = Inserts || COALESCE(start.Insert[1].Text,'NULL')|| ' / ';"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t \tSET K = 1;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t \tINSERTS: LOOP"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\tIF CARDINALITY(start.Insert[])> K "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\tTHEN "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\t\tSET Inserts = Inserts || COALESCE(start.Insert[K+1].Text,'NULL')|| ' / ';"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\t-- No more inserts to process"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\tELSE LEAVE INSERTS;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\tEND IF;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\tSET K = K+1;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\tEND LOOP INSERTS;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tEND IF;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET ERef.Exception[I].Label = Label;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET ERef.Exception[I].Error = Error;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET ERef.Exception[I].Text = Text;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSet ERef.Exception[I].Inserts = COALESCE(Inserts, '');"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.2") );
out.write(" ' || COALESCE(Label, ''); "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.3") );
out.write(" ' || COALESCE(CAST(Error AS CHARACTER), '');"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.4") );
out.write(" ' || COALESCE(Text, '');"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.8") );
out.write(" ' || COALESCE(Inserts, '');"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET I = I+1; "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tEND IF;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t-- Move start to the last child of the field to which it currently points"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tMOVE start LASTCHILD;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tEND WHILE;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET Environment.PatternVariables.FaultText = FaultText;"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND; "); //$NON-NLS-1$
out.write(NL);
out.write(" "); //$NON-NLS-1$
out.write(NL);
out.write(" "); //$NON-NLS-1$
out.write(NL);
out.write("END MODULE;"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("CREATE FILTER MODULE CheckifMessageSent"); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$
out.write(NL);
out.write("\tBEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tRETURN Environment.PatternVariables.Complete = 'Complete';"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("\tEND;"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND MODULE;"); //$NON-NLS-1$
out.write(NL);
out.write("CREATE FILTER MODULE CheckErrorLogging"); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$
out.write(NL);
out.write("\tBEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tRETURN ErrorLoggingOn;"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND;"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND MODULE;"); //$NON-NLS-1$
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("CREATE DATABASE MODULE Throw"); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$
out.write(NL);
out.write("\tBEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\tTHROW USER EXCEPTION SEVERITY 3 MESSAGE 2372 VALUES(Environment.PatternVariables.FaultText);"); //$NON-NLS-1$
out.write(NL);
out.write("END;"); //$NON-NLS-1$
out.write(NL);
out.write("END MODULE;"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
}
}
| epl-1.0 |
qqbbyq/controller | opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/SnapshotManagerTest.java | 27087 | /*
* Copyright (c) 2015 Cisco Systems, Inc. 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.opendaylight.controller.cluster.raft;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import akka.actor.ActorRef;
import akka.persistence.SnapshotSelectionCriteria;
import akka.testkit.TestActorRef;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.cluster.DataPersistenceProvider;
import org.opendaylight.controller.cluster.raft.SnapshotManager.LastAppliedTermInformationReader;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
import org.slf4j.LoggerFactory;
public class SnapshotManagerTest extends AbstractActorTest {
@Mock
private RaftActorContext mockRaftActorContext;
@Mock
private ConfigParams mockConfigParams;
@Mock
private ReplicatedLog mockReplicatedLog;
@Mock
private DataPersistenceProvider mockDataPersistenceProvider;
@Mock
private RaftActorBehavior mockRaftActorBehavior;
@Mock
private Runnable mockProcedure;
@Mock
private ElectionTerm mockElectionTerm;
private SnapshotManager snapshotManager;
private TestActorFactory factory;
private TestActorRef<MessageCollectorActor> actorRef;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
doReturn(false).when(mockRaftActorContext).hasFollowers();
doReturn(mockConfigParams).when(mockRaftActorContext).getConfigParams();
doReturn(10L).when(mockConfigParams).getSnapshotBatchCount();
doReturn(70).when(mockConfigParams).getSnapshotDataThresholdPercentage();
doReturn(mockReplicatedLog).when(mockRaftActorContext).getReplicatedLog();
doReturn("123").when(mockRaftActorContext).getId();
doReturn(mockDataPersistenceProvider).when(mockRaftActorContext).getPersistenceProvider();
doReturn(mockRaftActorBehavior).when(mockRaftActorContext).getCurrentBehavior();
doReturn("123").when(mockRaftActorBehavior).getLeaderId();
doReturn(mockElectionTerm).when(mockRaftActorContext).getTermInformation();
doReturn(5L).when(mockElectionTerm).getCurrentTerm();
doReturn("member5").when(mockElectionTerm).getVotedFor();
snapshotManager = new SnapshotManager(mockRaftActorContext, LoggerFactory.getLogger(this.getClass()));
factory = new TestActorFactory(getSystem());
actorRef = factory.createTestActor(MessageCollectorActor.props(), factory.generateActorId("test-"));
doReturn(actorRef).when(mockRaftActorContext).getActor();
snapshotManager.setCreateSnapshotRunnable(mockProcedure);
}
@After
public void tearDown(){
factory.close();
}
@Test
public void testConstruction(){
assertEquals(false, snapshotManager.isCapturing());
}
@Test
public void testCaptureToInstall() throws Exception {
// Force capturing toInstall = true
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(1, 0,
new MockRaftActorContext.MockPayload()), 0, "follower-1");
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(0L, captureSnapshot.getLastIndex());
assertEquals(1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(0L, captureSnapshot.getLastAppliedIndex());
assertEquals(1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCapture() throws Exception {
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(9L, captureSnapshot.getLastIndex());
assertEquals(1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(9L, captureSnapshot.getLastAppliedIndex());
assertEquals(1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCaptureWithNullLastLogEntry() throws Exception {
boolean capture = snapshotManager.capture(null, 1);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
System.out.println(captureSnapshot);
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(-1L, captureSnapshot.getLastIndex());
assertEquals(-1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(-1L, captureSnapshot.getLastAppliedIndex());
assertEquals(-1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCaptureWithCreateProcedureError () throws Exception {
doThrow(new RuntimeException("mock")).when(mockProcedure).run();
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertFalse(capture);
assertEquals(false, snapshotManager.isCapturing());
verify(mockProcedure).run();
}
@Test
public void testIllegalCapture() throws Exception {
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
verify(mockProcedure).run();
reset(mockProcedure);
// This will not cause snapshot capture to start again
capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertFalse(capture);
verify(mockProcedure, never()).run();
}
@Test
public void testPersistWhenReplicatedToAllIndexMinusOne(){
doReturn(7L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(1L).when(mockReplicatedLog).getSnapshotTerm();
doReturn(true).when(mockRaftActorContext).hasFollowers();
doReturn(8L).when(mockRaftActorContext).getLastApplied();
MockRaftActorContext.MockReplicatedLogEntry lastLogEntry = new MockRaftActorContext.MockReplicatedLogEntry(
3L, 9L, new MockRaftActorContext.MockPayload());
MockRaftActorContext.MockReplicatedLogEntry lastAppliedEntry = new MockRaftActorContext.MockReplicatedLogEntry(
2L, 8L, new MockRaftActorContext.MockPayload());
doReturn(lastAppliedEntry).when(mockReplicatedLog).get(8L);
doReturn(Arrays.asList(lastLogEntry)).when(mockReplicatedLog).getFrom(9L);
// when replicatedToAllIndex = -1
snapshotManager.capture(lastLogEntry, -1);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
ArgumentCaptor<Snapshot> snapshotArgumentCaptor = ArgumentCaptor.forClass(Snapshot.class);
verify(mockDataPersistenceProvider).saveSnapshot(snapshotArgumentCaptor.capture());
Snapshot snapshot = snapshotArgumentCaptor.getValue();
assertEquals("getLastTerm", 3L, snapshot.getLastTerm());
assertEquals("getLastIndex", 9L, snapshot.getLastIndex());
assertEquals("getLastAppliedTerm", 2L, snapshot.getLastAppliedTerm());
assertEquals("getLastAppliedIndex", 8L, snapshot.getLastAppliedIndex());
assertArrayEquals("getState", bytes, snapshot.getState());
assertEquals("getUnAppliedEntries", Arrays.asList(lastLogEntry), snapshot.getUnAppliedEntries());
assertEquals("electionTerm", mockElectionTerm.getCurrentTerm(), snapshot.getElectionTerm());
assertEquals("electionVotedFor", mockElectionTerm.getVotedFor(), snapshot.getElectionVotedFor());
verify(mockReplicatedLog).snapshotPreCommit(7L, 1L);
}
@Test
public void testPersistWhenReplicatedToAllIndexNotMinus(){
doReturn(45L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(6L).when(mockReplicatedLog).getSnapshotTerm();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(replicatedLogEntry).when(mockReplicatedLog).get(9);
doReturn(6L).when(replicatedLogEntry).getTerm();
doReturn(9L).when(replicatedLogEntry).getIndex();
// when replicatedToAllIndex != -1
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6,9,
new MockRaftActorContext.MockPayload()), 9);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
ArgumentCaptor<Snapshot> snapshotArgumentCaptor = ArgumentCaptor.forClass(Snapshot.class);
verify(mockDataPersistenceProvider).saveSnapshot(snapshotArgumentCaptor.capture());
Snapshot snapshot = snapshotArgumentCaptor.getValue();
assertEquals("getLastTerm", 6L, snapshot.getLastTerm());
assertEquals("getLastIndex", 9L, snapshot.getLastIndex());
assertEquals("getLastAppliedTerm", 6L, snapshot.getLastAppliedTerm());
assertEquals("getLastAppliedIndex", 9L, snapshot.getLastAppliedIndex());
assertArrayEquals("getState", bytes, snapshot.getState());
assertEquals("getUnAppliedEntries size", 0, snapshot.getUnAppliedEntries().size());
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).setReplicatedToAllIndex(9);
}
@Test
public void testPersistWhenReplicatedLogDataSizeGreaterThanThreshold(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6,9,
new MockRaftActorContext.MockPayload()), -1);
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testPersistWhenReplicatedLogSizeExceedsSnapshotBatchCount() {
doReturn(10L).when(mockReplicatedLog).size(); // matches snapshotBatchCount
doReturn(100).when(mockReplicatedLog).dataSize();
doReturn(5L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(5L).when(mockReplicatedLog).getSnapshotTerm();
long replicatedToAllIndex = 1;
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(replicatedLogEntry).when(mockReplicatedLog).get(replicatedToAllIndex);
doReturn(6L).when(replicatedLogEntry).getTerm();
doReturn(replicatedToAllIndex).when(replicatedLogEntry).getIndex();
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), replicatedToAllIndex);
snapshotManager.persist(new byte[]{}, 2000000L);
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).setReplicatedToAllIndex(replicatedToAllIndex);
}
@Test
public void testPersistSendInstallSnapshot(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
boolean capture = snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
assertTrue(capture);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
assertEquals(true, snapshotManager.isCapturing());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
ArgumentCaptor<SendInstallSnapshot> sendInstallSnapshotArgumentCaptor
= ArgumentCaptor.forClass(SendInstallSnapshot.class);
verify(mockRaftActorBehavior).handleMessage(any(ActorRef.class), sendInstallSnapshotArgumentCaptor.capture());
SendInstallSnapshot sendInstallSnapshot = sendInstallSnapshotArgumentCaptor.getValue();
assertTrue(Arrays.equals(bytes, sendInstallSnapshot.getSnapshot().getState()));
}
@Test
public void testCallingPersistWithoutCaptureWillDoNothing(){
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider, never()).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog, never()).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior, never()).handleMessage(any(ActorRef.class), any(SendInstallSnapshot.class));
}
@Test
public void testCallingPersistTwiceWillDoNoHarm(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).handleMessage(any(ActorRef.class), any(SendInstallSnapshot.class));
}
@Test
public void testCommit(){
doReturn(50L).when(mockDataPersistenceProvider).getLastSequenceNumber();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
assertEquals(true, snapshotManager.isCapturing());
snapshotManager.commit(100L, 1234L);
assertEquals(false, snapshotManager.isCapturing());
verify(mockReplicatedLog).snapshotCommit();
verify(mockDataPersistenceProvider).deleteMessages(50L);
ArgumentCaptor<SnapshotSelectionCriteria> criteriaCaptor = ArgumentCaptor.forClass(SnapshotSelectionCriteria.class);
verify(mockDataPersistenceProvider).deleteSnapshots(criteriaCaptor.capture());
assertEquals(100L, criteriaCaptor.getValue().maxSequenceNr());
assertEquals(1233L, criteriaCaptor.getValue().maxTimestamp());
MessageCollectorActor.expectFirstMatching(actorRef, SnapshotComplete.class);
}
@Test
public void testCommitBeforePersist(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockDataPersistenceProvider, never()).deleteMessages(100L);
verify(mockDataPersistenceProvider, never()).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testCommitBeforeCapture(){
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockDataPersistenceProvider, never()).deleteMessages(anyLong());
verify(mockDataPersistenceProvider, never()).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testCallingCommitMultipleTimesCausesNoHarm(){
doReturn(50L).when(mockDataPersistenceProvider).getLastSequenceNumber();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.commit(100L, 0);
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, times(1)).snapshotCommit();
verify(mockDataPersistenceProvider, times(1)).deleteMessages(50L);
verify(mockDataPersistenceProvider, times(1)).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testRollback(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.rollback();
verify(mockReplicatedLog).snapshotRollback();
MessageCollectorActor.expectFirstMatching(actorRef, SnapshotComplete.class);
}
@Test
public void testRollbackBeforePersist(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.rollback();
verify(mockReplicatedLog, never()).snapshotRollback();
}
@Test
public void testRollbackBeforeCapture(){
snapshotManager.rollback();
verify(mockReplicatedLog, never()).snapshotRollback();
}
@Test
public void testCallingRollbackMultipleTimesCausesNoHarm(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.rollback();
snapshotManager.rollback();
verify(mockReplicatedLog, times(1)).snapshotRollback();
}
@Test
public void testTrimLogWhenTrimIndexLessThanLastApplied() {
doReturn(20L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", 10L, retIndex);
verify(mockReplicatedLog).snapshotPreCommit(10, 5);
verify(mockReplicatedLog).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenLastAppliedNotSet() {
doReturn(-1L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenLastAppliedZero() {
doReturn(0L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenTrimIndexNotPresent() {
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(false).when(mockReplicatedLog).isPresent(10);
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
// Trim index is greater than replicatedToAllIndex so should update it.
verify(mockRaftActorBehavior).setReplicatedToAllIndex(10L);
}
@Test
public void testTrimLogAfterCapture(){
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
snapshotManager.trimLog(10);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
}
@Test
public void testTrimLogAfterCaptureToInstall(){
boolean capture = snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9, "follower-1");
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
snapshotManager.trimLog(10);
verify(mockReplicatedLog, never()).snapshotPreCommit(10, 5);
verify(mockReplicatedLog, never()).snapshotCommit();
}
@Test
public void testLastAppliedTermInformationReader() {
LastAppliedTermInformationReader reader = new LastAppliedTermInformationReader();
doReturn(4L).when(mockReplicatedLog).getSnapshotTerm();
doReturn(7L).when(mockReplicatedLog).getSnapshotIndex();
ReplicatedLogEntry lastLogEntry = new MockRaftActorContext.MockReplicatedLogEntry(6L, 9L,
new MockRaftActorContext.MockPayload());
// No followers and valid lastLogEntry
reader.init(mockReplicatedLog, 1L, lastLogEntry, false);
assertEquals("getTerm", 6L, reader.getTerm());
assertEquals("getIndex", 9L, reader.getIndex());
// No followers and null lastLogEntry
reader.init(mockReplicatedLog, 1L, null, false);
assertEquals("getTerm", -1L, reader.getTerm());
assertEquals("getIndex", -1L, reader.getIndex());
// Followers and valid originalIndex entry
doReturn(new MockRaftActorContext.MockReplicatedLogEntry(5L, 8L,
new MockRaftActorContext.MockPayload())).when(mockReplicatedLog).get(8L);
reader.init(mockReplicatedLog, 8L, lastLogEntry, true);
assertEquals("getTerm", 5L, reader.getTerm());
assertEquals("getIndex", 8L, reader.getIndex());
// Followers and null originalIndex entry and valid snapshot index
reader.init(mockReplicatedLog, 7L, lastLogEntry, true);
assertEquals("getTerm", 4L, reader.getTerm());
assertEquals("getIndex", 7L, reader.getIndex());
// Followers and null originalIndex entry and invalid snapshot index
doReturn(-1L).when(mockReplicatedLog).getSnapshotIndex();
reader.init(mockReplicatedLog, 7L, lastLogEntry, true);
assertEquals("getTerm", -1L, reader.getTerm());
assertEquals("getIndex", -1L, reader.getIndex());
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | sdo/eclipselink.sdo.test/src/org/eclipse/persistence/testing/sdo/model/dataobject/SDODataObjectGetDataObjectConversionTest.java | 5453 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.sdo.model.dataobject;
import commonj.sdo.Property;
import junit.textui.TestRunner;
import org.eclipse.persistence.sdo.SDOConstants;
import org.eclipse.persistence.sdo.SDODataObject;
import org.eclipse.persistence.sdo.SDOProperty;
import org.eclipse.persistence.sdo.SDOType;
import org.eclipse.persistence.exceptions.SDOException;
public class SDODataObjectGetDataObjectConversionTest extends SDODataObjectConversionTestCases {
public SDODataObjectGetDataObjectConversionTest(String name) {
super(name);
}
public static void main(String[] args) {
String[] arguments = { "-c", "org.eclipse.persistence.testing.sdo.model.dataobject.SDODataObjectGetDataObjectConversionTest" };
TestRunner.main(arguments);
}
public void testGetDataObjectConversionFromDefinedProperty() {
SDOType dataObjectType = (SDOType) typeHelper.getType(SDOConstants.SDO_URL, SDOConstants.DATAOBJECT);
SDOProperty property = ((SDOProperty)dataObject.getInstanceProperty(PROPERTY_NAME));
property.setType(dataObjectType);
SDODataObject b = new SDODataObject();
dataObject.setDataObject(property, b);// add it to instance list
this.assertEquals(b, dataObject.getDataObject(property));
}
public void testGetDataObjectConversionFromDefinedPropertyWithPath() {
SDOType dataObjectType = (SDOType) typeHelper.getType(SDOConstants.SDO_URL, SDOConstants.DATAOBJECT);
// dataObject's type add boolean property
SDOProperty property = ((SDOProperty)dataObject.getInstanceProperty(PROPERTY_NAME));
property.setType(dataObjectType);
SDODataObject b = new SDODataObject();
dataObject.setDataObject(PROPERTY_NAME, b);// add it to instance list
this.assertEquals(b, dataObject.getDataObject(property));
}
//2. purpose: getDataObject with Undefined Boolean Property
public void testGetDataObjectConversionFromUndefinedProperty() {
SDOType dataObjectType = (SDOType) typeHelper.getType(SDOConstants.SDO_URL, SDOConstants.DATAOBJECT);
SDOProperty property = new SDOProperty(aHelperContext);
property.setName(PROPERTY_NAME);
property.setType(dataObjectType);
try {
dataObject.getDataObject(property);
fail("IllegalArgumentException should be thrown.");
} catch (IllegalArgumentException e) {
}
}
//3. purpose: getDataObject with property set to boolean value
public void testGetDataObjectConversionFromProperty() {
SDOType dataObjectType = (SDOType) typeHelper.getType(SDOConstants.SDO_URL, SDOConstants.DATAOBJECT);
// dataObject's type add boolean property
SDOProperty property = ((SDOProperty)dataObject.getInstanceProperty(PROPERTY_NAME));
property.setType(dataObjectType);
type.setOpen(true);
boolean b = true;
dataObject.set(property, b);// add it to instance list
try {
dataObject.getDataObject(property);
fail("ClassCastException should be thrown.");
} catch (ClassCastException e) {
}
}
//purpose: getDataObject with nul value
public void testGetDataObjectConversionWithNullArgument() {
try {
Property p = null;
dataObject.getDataObject(p);
fail("IllegalArgumentException should be thrown.");
} catch (IllegalArgumentException e) {
}
}
//purpose: getBoolean with Defined Boolean Property
public void testGetDataObjectConversionFromPropertyIndex() {
SDOType dataObjectType = (SDOType) typeHelper.getType(SDOConstants.SDO_URL, SDOConstants.DATAOBJECT);
// dataObject's type add boolean property
SDOProperty property = ((SDOProperty)dataObject.getInstanceProperty(PROPERTY_NAME));
property.setType(dataObjectType);
type.addDeclaredProperty(property);
type.setOpen(true);
SDODataObject b = new SDODataObject();
dataObject.setDataObject(PROPERTY_INDEX, b);// add it to instance list
this.assertEquals(b, dataObject.getDataObject(PROPERTY_INDEX));
}
//purpose: getDouble with nul value
public void testGetDataObjectWithInvalidIndex() {
try {
int p = -1;
dataObject.getDataObject(p);
} catch (SDOException e) {
assertEquals(SDOException.PROPERTY_NOT_FOUND_AT_INDEX ,e.getErrorCode());
return;
}
fail("an SDOException should have occurred.");
}
}
| epl-1.0 |
kostajaitachi/Pearl-14 | Pearl'14/src/org/bitspilani/pearl/TillDeaf.java | 623 | package org.bitspilani.pearl;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
public class TillDeaf extends Activity {
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().hide();
setContentView(R.layout.event1);
TextView tv = (TextView)findViewById(R.id.title);
tv.setText(R.string.tillDeaf);
TextView tv1 = (TextView)findViewById(R.id.description);
tv1.setText(R.string.tilldeaf_ds);
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | utils/eclipselink.utils.workbench/utility/source/org/eclipse/persistence/tools/workbench/utility/events/AWTChangeNotifier.java | 8323 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.utility.events;
import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
/**
* AWT-aware implementation of ChangeNotifier interface:
* If we are executing on the AWT event-dispatch thread,
* simply forward the change notification directly to the listener.
* If we are executing on some other thread, queue up the
* notification on the AWT event queue so it can be executed
* on the event-dispatch thread (after the pending events have
* been dispatched).
*/
public final class AWTChangeNotifier
implements ChangeNotifier, Serializable
{
// singleton
private static ChangeNotifier INSTANCE;
private static final long serialVersionUID = 1L;
/**
* Return the singleton.
*/
public synchronized static ChangeNotifier instance() {
if (INSTANCE == null) {
INSTANCE = new AWTChangeNotifier();
}
return INSTANCE;
}
/**
* Ensure non-instantiability.
*/
private AWTChangeNotifier() {
super();
}
/**
* @see ChangeNotifier#stateChanged(StateChangeListener, StateChangeEvent)
*/
public void stateChanged(final StateChangeListener listener, final StateChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.stateChanged(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.stateChanged(event);
}
public String toString() {
return "stateChanged";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#propertyChange(java.beans.PropertyChangeListener, java.beans.PropertyChangeEvent)
*/
public void propertyChange(final PropertyChangeListener listener, final PropertyChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.propertyChange(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.propertyChange(event);
}
public String toString() {
return "propertyChange";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsAdded(CollectionChangeListener, CollectionChangeEvent)
*/
public void itemsAdded(final CollectionChangeListener listener, final CollectionChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsAdded(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsAdded(event);
}
public String toString() {
return "itemsAdded (Collection)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsRemoved(CollectionChangeListener, CollectionChangeEvent)
*/
public void itemsRemoved(final CollectionChangeListener listener, final CollectionChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsRemoved(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsRemoved(event);
}
public String toString() {
return "itemsRemoved (Collection)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#collectionChanged(CollectionChangeListener, CollectionChangeEvent)
*/
public void collectionChanged(final CollectionChangeListener listener, final CollectionChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.collectionChanged(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.collectionChanged(event);
}
public String toString() {
return "collectionChanged";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsAdded(ListChangeListener, ListChangeEvent)
*/
public void itemsAdded(final ListChangeListener listener, final ListChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsAdded(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsAdded(event);
}
public String toString() {
return "itemsAdded (List)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsRemoved(ListChangeListener, ListChangeEvent)
*/
public void itemsRemoved(final ListChangeListener listener, final ListChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsRemoved(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsRemoved(event);
}
public String toString() {
return "itemsRemoved (List)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsReplaced(ListChangeListener, ListChangeEvent)
*/
public void itemsReplaced(final ListChangeListener listener, final ListChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsReplaced(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsReplaced(event);
}
public String toString() {
return "itemsReplaced (List)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#listChanged(ListChangeListener, ListChangeEvent)
*/
public void listChanged(final ListChangeListener listener, final ListChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.listChanged(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.listChanged(event);
}
public String toString() {
return "listChanged";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#nodeAdded(TreeChangeListener, TreeChangeEvent)
*/
public void nodeAdded(final TreeChangeListener listener, final TreeChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.nodeAdded(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.nodeAdded(event);
}
public String toString() {
return "nodeAdded";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#nodeRemoved(TreeChangeListener, TreeChangeEvent)
*/
public void nodeRemoved(final TreeChangeListener listener, final TreeChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.nodeRemoved(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.nodeRemoved(event);
}
public String toString() {
return "nodeRemoved";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#treeChanged(TreeChangeListener, TreeChangeEvent)
*/
public void treeChanged(final TreeChangeListener listener, final TreeChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.treeChanged(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.treeChanged(event);
}
public String toString() {
return "treeChanged";
}
}
);
}
}
/**
* EventQueue.invokeLater(Runnable) seems to work OK;
* but using #invokeAndWait() can somtimes make things
* more predictable when debugging.
*/
private void invoke(Runnable r) {
EventQueue.invokeLater(r);
// try {
// EventQueue.invokeAndWait(r);
// } catch (InterruptedException ex) {
// throw new RuntimeException(ex);
// } catch (java.lang.reflect.InvocationTargetException ex) {
// throw new RuntimeException(ex);
// }
}
/**
* Serializable singleton support
*/
private Object readResolve() {
return instance();
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/domain/core/com.odcgroup.mdf.integration/src/main/java/com/odcgroup/mdf/integration/Activator.java | 1113 | package com.odcgroup.mdf.integration;
import org.osgi.framework.BundleContext;
import com.odcgroup.workbench.core.AbstractActivator;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractActivator {
// The plug-in ID
public static final String PLUGIN_ID = "com.odcgroup.mdf.integration";
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
@Override
protected String getResourceBundleName() {
return null;
}
}
| epl-1.0 |
lunifera/lunifera-ecview | org.lunifera.ecview.core.extension.editparts/src/org/lunifera/ecview/core/ui/core/editparts/extension/IEnumOptionsGroupEditpart.java | 653 | /**
* Copyright (c) 2011 - 2015, Lunifera GmbH (Gross Enzersdorf), Loetz KG (Heidelberg)
* 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:
* Florian Pirchner - Initial implementation
*/
package org.lunifera.ecview.core.ui.core.editparts.extension;
import org.lunifera.ecview.core.common.editpart.IFieldEditpart;
/**
* An edit part for optionGroup.
*/
public interface IEnumOptionsGroupEditpart extends IFieldEditpart {
}
| epl-1.0 |
Orjuwan-alwadeai/mondo-hawk | plugins-server/org.hawk.service.api/src-gen/org/hawk/service/api/InvalidQuery.java | 11697 | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.hawk.service.api;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-08-17")
public class InvalidQuery extends TException implements org.apache.thrift.TBase<InvalidQuery, InvalidQuery._Fields>, java.io.Serializable, Cloneable, Comparable<InvalidQuery> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvalidQuery");
private static final org.apache.thrift.protocol.TField REASON_FIELD_DESC = new org.apache.thrift.protocol.TField("reason", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new InvalidQueryStandardSchemeFactory());
schemes.put(TupleScheme.class, new InvalidQueryTupleSchemeFactory());
}
public String reason; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
REASON((short)1, "reason");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // REASON
return REASON;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.REASON, new org.apache.thrift.meta_data.FieldMetaData("reason", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(InvalidQuery.class, metaDataMap);
}
public InvalidQuery() {
}
public InvalidQuery(
String reason)
{
this();
this.reason = reason;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public InvalidQuery(InvalidQuery other) {
if (other.isSetReason()) {
this.reason = other.reason;
}
}
public InvalidQuery deepCopy() {
return new InvalidQuery(this);
}
@Override
public void clear() {
this.reason = null;
}
public String getReason() {
return this.reason;
}
public InvalidQuery setReason(String reason) {
this.reason = reason;
return this;
}
public void unsetReason() {
this.reason = null;
}
/** Returns true if field reason is set (has been assigned a value) and false otherwise */
public boolean isSetReason() {
return this.reason != null;
}
public void setReasonIsSet(boolean value) {
if (!value) {
this.reason = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case REASON:
if (value == null) {
unsetReason();
} else {
setReason((String)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case REASON:
return getReason();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case REASON:
return isSetReason();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof InvalidQuery)
return this.equals((InvalidQuery)that);
return false;
}
public boolean equals(InvalidQuery that) {
if (that == null)
return false;
boolean this_present_reason = true && this.isSetReason();
boolean that_present_reason = true && that.isSetReason();
if (this_present_reason || that_present_reason) {
if (!(this_present_reason && that_present_reason))
return false;
if (!this.reason.equals(that.reason))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_reason = true && (isSetReason());
list.add(present_reason);
if (present_reason)
list.add(reason);
return list.hashCode();
}
@Override
public int compareTo(InvalidQuery other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetReason()).compareTo(other.isSetReason());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetReason()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.reason, other.reason);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("InvalidQuery(");
boolean first = true;
sb.append("reason:");
if (this.reason == null) {
sb.append("null");
} else {
sb.append(this.reason);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (reason == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'reason' was not present! Struct: " + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class InvalidQueryStandardSchemeFactory implements SchemeFactory {
public InvalidQueryStandardScheme getScheme() {
return new InvalidQueryStandardScheme();
}
}
private static class InvalidQueryStandardScheme extends StandardScheme<InvalidQuery> {
public void read(org.apache.thrift.protocol.TProtocol iprot, InvalidQuery struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // REASON
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.reason = iprot.readString();
struct.setReasonIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, InvalidQuery struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.reason != null) {
oprot.writeFieldBegin(REASON_FIELD_DESC);
oprot.writeString(struct.reason);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class InvalidQueryTupleSchemeFactory implements SchemeFactory {
public InvalidQueryTupleScheme getScheme() {
return new InvalidQueryTupleScheme();
}
}
private static class InvalidQueryTupleScheme extends TupleScheme<InvalidQuery> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, InvalidQuery struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
oprot.writeString(struct.reason);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, InvalidQuery struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
struct.reason = iprot.readString();
struct.setReasonIsSet(true);
}
}
}
| epl-1.0 |
Tocea/Architecture-Designer | com.tocea.scertify.architecture.mm/src/com/tocea/codewatch/architecture/Method.java | 343 | /**
*/
package com.tocea.codewatch.architecture;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Method</b></em>'.
* <!-- end-user-doc -->
*
*
* @see com.tocea.codewatch.architecture.ArchitecturePackage#getMethod()
* @model
* @generated
*/
public interface Method extends AnalysedElement {
} // Method
| epl-1.0 |
fmselab/fmautorepair | fmautorepair.mutation/src/fmautorepair/mutationoperators/features/AndToOr.java | 883 | package fmautorepair.mutationoperators.features;
import org.apache.log4j.Logger;
import de.ovgu.featureide.fm.core.Feature;
import de.ovgu.featureide.fm.core.FeatureModel;
import fmautorepair.mutationoperators.FMMutator;
/** transform And to or */
public class AndToOr extends FeatureMutator {
private static Logger logger = Logger.getLogger(AndToOr.class.getName());
public static FMMutator instance = new AndToOr();
@Override
String mutate(FeatureModel fm, Feature tobemutated) {
// if has more than one child or one child but optional
tobemutated.changeToOr();
logger.info("mutating feature " + tobemutated.getName() + " from AND TO OR");
return (tobemutated.getName() + " from AND TO OR");
}
@Override
boolean isMutable(FeatureModel fm, Feature tobemutated) {
int size = tobemutated.getChildren().size();
return (tobemutated.isAnd() && size >0);
}
}
| epl-1.0 |
ObeoNetwork/EAST-ADL-Designer | plugins/org.obeonetwork.dsl.eastadl/src/org/obeonetwork/dsl/east_adl/structure/functional_analysis_architecture/impl/FunctionalAnalysisArchitectureImpl.java | 25068 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
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.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.obeonetwork.dsl.east_adl.core.impl.EASTADLArtifactImpl;
import org.obeonetwork.dsl.east_adl.structure.common.ConnectorSignal;
import org.obeonetwork.dsl.east_adl.structure.common.DesignDataType;
import org.obeonetwork.dsl.east_adl.structure.common.ImplementationDataType;
import org.obeonetwork.dsl.east_adl.structure.common.OperationCall;
import org.obeonetwork.dsl.east_adl.structure.common.TypeAssociation;
import org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.AnalysisFunction;
import org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.FunctionalAnalysisArchitecture;
import org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.FunctionalDevice;
import org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.Functional_analysis_architecturePackage;
import org.obeonetwork.dsl.east_adl.structure.functional_design_architecture.FunctionalDesignArchitecture;
import org.obeonetwork.dsl.east_adl.structure.functional_design_architecture.Functional_design_architecturePackage;
import org.obeonetwork.dsl.east_adl.structure.vehicle_feature_model.VehicleFeatureModel;
import org.obeonetwork.dsl.east_adl.structure.vehicle_feature_model.Vehicle_feature_modelPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Functional Analysis Architecture</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getAnalysisFunctions <em>Analysis Functions</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getFunctionalDevices <em>Functional Devices</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getVehicleModel <em>Vehicle Model</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getDesignArchitecture <em>Design Architecture</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getDesignDataTypes <em>Design Data Types</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getConnectorSignals <em>Connector Signals</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getOperationCalls <em>Operation Calls</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getTypeAssociations <em>Type Associations</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getImplementationDataTypes <em>Implementation Data Types</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class FunctionalAnalysisArchitectureImpl extends EASTADLArtifactImpl implements FunctionalAnalysisArchitecture {
/**
* The cached value of the '{@link #getAnalysisFunctions() <em>Analysis Functions</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAnalysisFunctions()
* @generated
* @ordered
*/
protected EList<AnalysisFunction> analysisFunctions;
/**
* The cached value of the '{@link #getFunctionalDevices() <em>Functional Devices</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFunctionalDevices()
* @generated
* @ordered
*/
protected EList<FunctionalDevice> functionalDevices;
/**
* The cached value of the '{@link #getVehicleModel() <em>Vehicle Model</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getVehicleModel()
* @generated
* @ordered
*/
protected VehicleFeatureModel vehicleModel;
/**
* The cached value of the '{@link #getDesignArchitecture() <em>Design Architecture</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDesignArchitecture()
* @generated
* @ordered
*/
protected FunctionalDesignArchitecture designArchitecture;
/**
* The cached value of the '{@link #getDesignDataTypes() <em>Design Data Types</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDesignDataTypes()
* @generated
* @ordered
*/
protected EList<DesignDataType> designDataTypes;
/**
* The cached value of the '{@link #getConnectorSignals() <em>Connector Signals</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getConnectorSignals()
* @generated
* @ordered
*/
protected EList<ConnectorSignal> connectorSignals;
/**
* The cached value of the '{@link #getOperationCalls() <em>Operation Calls</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOperationCalls()
* @generated
* @ordered
*/
protected EList<OperationCall> operationCalls;
/**
* The cached value of the '{@link #getTypeAssociations() <em>Type Associations</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTypeAssociations()
* @generated
* @ordered
*/
protected EList<TypeAssociation> typeAssociations;
/**
* The cached value of the '{@link #getImplementationDataTypes() <em>Implementation Data Types</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImplementationDataTypes()
* @generated
* @ordered
*/
protected EList<ImplementationDataType> implementationDataTypes;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected FunctionalAnalysisArchitectureImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Functional_analysis_architecturePackage.Literals.FUNCTIONAL_ANALYSIS_ARCHITECTURE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<AnalysisFunction> getAnalysisFunctions() {
if (analysisFunctions == null) {
analysisFunctions = new EObjectContainmentEList<AnalysisFunction>(AnalysisFunction.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS);
}
return analysisFunctions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<FunctionalDevice> getFunctionalDevices() {
if (functionalDevices == null) {
functionalDevices = new EObjectContainmentWithInverseEList<FunctionalDevice>(FunctionalDevice.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES, Functional_analysis_architecturePackage.FUNCTIONAL_DEVICE__OWNING_ARTIFACT);
}
return functionalDevices;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VehicleFeatureModel getVehicleModel() {
if (vehicleModel != null && vehicleModel.eIsProxy()) {
InternalEObject oldVehicleModel = (InternalEObject)vehicleModel;
vehicleModel = (VehicleFeatureModel)eResolveProxy(oldVehicleModel);
if (vehicleModel != oldVehicleModel) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL, oldVehicleModel, vehicleModel));
}
}
return vehicleModel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VehicleFeatureModel basicGetVehicleModel() {
return vehicleModel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetVehicleModel(VehicleFeatureModel newVehicleModel, NotificationChain msgs) {
VehicleFeatureModel oldVehicleModel = vehicleModel;
vehicleModel = newVehicleModel;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL, oldVehicleModel, newVehicleModel);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setVehicleModel(VehicleFeatureModel newVehicleModel) {
if (newVehicleModel != vehicleModel) {
NotificationChain msgs = null;
if (vehicleModel != null)
msgs = ((InternalEObject)vehicleModel).eInverseRemove(this, Vehicle_feature_modelPackage.VEHICLE_FEATURE_MODEL__ANALYSIS_ARCHITECTURE, VehicleFeatureModel.class, msgs);
if (newVehicleModel != null)
msgs = ((InternalEObject)newVehicleModel).eInverseAdd(this, Vehicle_feature_modelPackage.VEHICLE_FEATURE_MODEL__ANALYSIS_ARCHITECTURE, VehicleFeatureModel.class, msgs);
msgs = basicSetVehicleModel(newVehicleModel, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL, newVehicleModel, newVehicleModel));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FunctionalDesignArchitecture getDesignArchitecture() {
if (designArchitecture != null && designArchitecture.eIsProxy()) {
InternalEObject oldDesignArchitecture = (InternalEObject)designArchitecture;
designArchitecture = (FunctionalDesignArchitecture)eResolveProxy(oldDesignArchitecture);
if (designArchitecture != oldDesignArchitecture) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE, oldDesignArchitecture, designArchitecture));
}
}
return designArchitecture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FunctionalDesignArchitecture basicGetDesignArchitecture() {
return designArchitecture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDesignArchitecture(FunctionalDesignArchitecture newDesignArchitecture, NotificationChain msgs) {
FunctionalDesignArchitecture oldDesignArchitecture = designArchitecture;
designArchitecture = newDesignArchitecture;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE, oldDesignArchitecture, newDesignArchitecture);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDesignArchitecture(FunctionalDesignArchitecture newDesignArchitecture) {
if (newDesignArchitecture != designArchitecture) {
NotificationChain msgs = null;
if (designArchitecture != null)
msgs = ((InternalEObject)designArchitecture).eInverseRemove(this, Functional_design_architecturePackage.FUNCTIONAL_DESIGN_ARCHITECTURE__ANALYSIS_ARCHITECTURE, FunctionalDesignArchitecture.class, msgs);
if (newDesignArchitecture != null)
msgs = ((InternalEObject)newDesignArchitecture).eInverseAdd(this, Functional_design_architecturePackage.FUNCTIONAL_DESIGN_ARCHITECTURE__ANALYSIS_ARCHITECTURE, FunctionalDesignArchitecture.class, msgs);
msgs = basicSetDesignArchitecture(newDesignArchitecture, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE, newDesignArchitecture, newDesignArchitecture));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<DesignDataType> getDesignDataTypes() {
if (designDataTypes == null) {
designDataTypes = new EObjectContainmentEList<DesignDataType>(DesignDataType.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES);
}
return designDataTypes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ConnectorSignal> getConnectorSignals() {
if (connectorSignals == null) {
connectorSignals = new EObjectContainmentEList<ConnectorSignal>(ConnectorSignal.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS);
}
return connectorSignals;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<OperationCall> getOperationCalls() {
if (operationCalls == null) {
operationCalls = new EObjectContainmentEList<OperationCall>(OperationCall.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS);
}
return operationCalls;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TypeAssociation> getTypeAssociations() {
if (typeAssociations == null) {
typeAssociations = new EObjectContainmentEList<TypeAssociation>(TypeAssociation.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS);
}
return typeAssociations;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ImplementationDataType> getImplementationDataTypes() {
if (implementationDataTypes == null) {
implementationDataTypes = new EObjectContainmentEList<ImplementationDataType>(ImplementationDataType.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES);
}
return implementationDataTypes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getFunctionalDevices()).basicAdd(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
if (vehicleModel != null)
msgs = ((InternalEObject)vehicleModel).eInverseRemove(this, Vehicle_feature_modelPackage.VEHICLE_FEATURE_MODEL__ANALYSIS_ARCHITECTURE, VehicleFeatureModel.class, msgs);
return basicSetVehicleModel((VehicleFeatureModel)otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
if (designArchitecture != null)
msgs = ((InternalEObject)designArchitecture).eInverseRemove(this, Functional_design_architecturePackage.FUNCTIONAL_DESIGN_ARCHITECTURE__ANALYSIS_ARCHITECTURE, FunctionalDesignArchitecture.class, msgs);
return basicSetDesignArchitecture((FunctionalDesignArchitecture)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
return ((InternalEList<?>)getAnalysisFunctions()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
return ((InternalEList<?>)getFunctionalDevices()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
return basicSetVehicleModel(null, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
return basicSetDesignArchitecture(null, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
return ((InternalEList<?>)getDesignDataTypes()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
return ((InternalEList<?>)getConnectorSignals()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
return ((InternalEList<?>)getOperationCalls()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
return ((InternalEList<?>)getTypeAssociations()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
return ((InternalEList<?>)getImplementationDataTypes()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
return getAnalysisFunctions();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
return getFunctionalDevices();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
if (resolve) return getVehicleModel();
return basicGetVehicleModel();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
if (resolve) return getDesignArchitecture();
return basicGetDesignArchitecture();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
return getDesignDataTypes();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
return getConnectorSignals();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
return getOperationCalls();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
return getTypeAssociations();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
return getImplementationDataTypes();
}
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 Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
getAnalysisFunctions().clear();
getAnalysisFunctions().addAll((Collection<? extends AnalysisFunction>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
getFunctionalDevices().clear();
getFunctionalDevices().addAll((Collection<? extends FunctionalDevice>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
setVehicleModel((VehicleFeatureModel)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
setDesignArchitecture((FunctionalDesignArchitecture)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
getDesignDataTypes().clear();
getDesignDataTypes().addAll((Collection<? extends DesignDataType>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
getConnectorSignals().clear();
getConnectorSignals().addAll((Collection<? extends ConnectorSignal>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
getOperationCalls().clear();
getOperationCalls().addAll((Collection<? extends OperationCall>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
getTypeAssociations().clear();
getTypeAssociations().addAll((Collection<? extends TypeAssociation>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
getImplementationDataTypes().clear();
getImplementationDataTypes().addAll((Collection<? extends ImplementationDataType>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
getAnalysisFunctions().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
getFunctionalDevices().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
setVehicleModel((VehicleFeatureModel)null);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
setDesignArchitecture((FunctionalDesignArchitecture)null);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
getDesignDataTypes().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
getConnectorSignals().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
getOperationCalls().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
getTypeAssociations().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
getImplementationDataTypes().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
return analysisFunctions != null && !analysisFunctions.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
return functionalDevices != null && !functionalDevices.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
return vehicleModel != null;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
return designArchitecture != null;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
return designDataTypes != null && !designDataTypes.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
return connectorSignals != null && !connectorSignals.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
return operationCalls != null && !operationCalls.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
return typeAssociations != null && !typeAssociations.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
return implementationDataTypes != null && !implementationDataTypes.isEmpty();
}
return super.eIsSet(featureID);
}
} //FunctionalAnalysisArchitectureImpl
| epl-1.0 |
zsmartsystems/com.zsmartsystems.zwave | com.zsmartsystems.zwave/src/main/java/com/zsmartsystems/zwave/commandclass/impl/CommandClassHumidityControlSetpointV1.java | 39425 | /**
* Copyright (c) 2016-2017 by the respective copyright holders.
*
* 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 com.zsmartsystems.zwave.commandclass.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class to implement the Z-Wave command class <b>COMMAND_CLASS_HUMIDITY_CONTROL_SETPOINT</b> version <b>1</b>.
* <p>
* Command Class Humidity Control Setpoint
* <p>
* This class provides static methods for processing received messages (message handler) and
* methods to get a message to send on the Z-Wave network.
* <p>
* Command class key is 0x64.
* <p>
* Note that this code is autogenerated. Manual changes may be overwritten.
*
* @author Chris Jackson - Initial contribution of Java code generator
*/
public class CommandClassHumidityControlSetpointV1 {
private static final Logger logger = LoggerFactory.getLogger(CommandClassHumidityControlSetpointV1.class);
/**
* Integer command class key for COMMAND_CLASS_HUMIDITY_CONTROL_SETPOINT
*/
public final static int COMMAND_CLASS_KEY = 0x64;
/**
* Humidity Control Setpoint Set Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SET = 0x01;
/**
* Humidity Control Setpoint Get Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_GET = 0x02;
/**
* Humidity Control Setpoint Report Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_REPORT = 0x03;
/**
* Humidity Control Setpoint Supported Get Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET = 0x04;
/**
* Humidity Control Setpoint Supported Report Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT = 0x05;
/**
* Humidity Control Setpoint Scale Supported Get Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET = 0x06;
/**
* Humidity Control Setpoint Scale Supported Report Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT = 0x07;
/**
* Humidity Control Setpoint Capabilities Get Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET = 0x08;
/**
* Humidity Control Setpoint Capabilities Report Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT = 0x09;
/**
* Map holding constants for HumidityControlSetpointGetSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointGetSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointCapabilitiesGetSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointCapabilitiesGetSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointSupportedReportBitMask
*/
private static Map<Integer, String> constantHumidityControlSetpointSupportedReportBitMask = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointScaleSupportedGetSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointScaleSupportedGetSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointSetSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointSetSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointReportScale
*/
private static Map<Integer, String> constantHumidityControlSetpointReportScale = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointCapabilitiesReportSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointCapabilitiesReportSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointReportSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointReportSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointCapabilitiesReportScale2
*/
private static Map<Integer, String> constantHumidityControlSetpointCapabilitiesReportScale2 = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointCapabilitiesReportScale1
*/
private static Map<Integer, String> constantHumidityControlSetpointCapabilitiesReportScale1 = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointScaleSupportedReportScaleBitMask
*/
private static Map<Integer, String> constantHumidityControlSetpointScaleSupportedReportScaleBitMask = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointSetScale
*/
private static Map<Integer, String> constantHumidityControlSetpointSetScale = new HashMap<Integer, String>();
static {
// Constants for HumidityControlSetpointGetSetpointType
constantHumidityControlSetpointGetSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointGetSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointCapabilitiesGetSetpointType
constantHumidityControlSetpointCapabilitiesGetSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointCapabilitiesGetSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointSupportedReportBitMask
constantHumidityControlSetpointSupportedReportBitMask.put(0x01, "HUMIDIFIER");
constantHumidityControlSetpointSupportedReportBitMask.put(0x02, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointScaleSupportedGetSetpointType
constantHumidityControlSetpointScaleSupportedGetSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointScaleSupportedGetSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointSetSetpointType
constantHumidityControlSetpointSetSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointSetSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointReportScale
constantHumidityControlSetpointReportScale.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointReportScale.put(0x01, "ABSOLUTE");
// Constants for HumidityControlSetpointCapabilitiesReportSetpointType
constantHumidityControlSetpointCapabilitiesReportSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointCapabilitiesReportSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointReportSetpointType
constantHumidityControlSetpointReportSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointReportSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointCapabilitiesReportScale2
constantHumidityControlSetpointCapabilitiesReportScale2.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointCapabilitiesReportScale2.put(0x01, "ABSOLUTE");
// Constants for HumidityControlSetpointCapabilitiesReportScale1
constantHumidityControlSetpointCapabilitiesReportScale1.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointCapabilitiesReportScale1.put(0x01, "ABSOLUTE");
// Constants for HumidityControlSetpointScaleSupportedReportScaleBitMask
constantHumidityControlSetpointScaleSupportedReportScaleBitMask.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointScaleSupportedReportScaleBitMask.put(0x01, "ABSOLUTE");
// Constants for HumidityControlSetpointSetScale
constantHumidityControlSetpointSetScale.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointSetScale.put(0x01, "ABSOLUTE");
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SET command.
* <p>
* Humidity Control Setpoint Set
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @param scale {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @param precision {@link Integer}
* @param value {@link byte[]}
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointSet(String setpointType, String scale, Integer precision,
byte[] value) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SET);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointSetSetpointType.keySet()) {
if (constantHumidityControlSetpointSetSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
// Process 'Properties2'
// Size is used by 'Value'
int size = value.length;
int valProperties2 = 0;
valProperties2 |= size & 0x07;
int varScale = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointSetScale.keySet()) {
if (constantHumidityControlSetpointSetScale.get(entry).equals(scale)) {
varScale = entry;
break;
}
}
if (varScale == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scale + "' for scale");
}
valProperties2 |= varScale << 3 & 0x18;
valProperties2 |= ((precision << 5) & 0xE0);
outputData.write(valProperties2);
// Process 'Value'
if (value != null) {
try {
outputData.write(value);
} catch (IOException e) {
}
}
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SET command.
* <p>
* Humidity Control Setpoint Set
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* <li>SCALE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* <li>PRECISION {@link Integer}
* <li>VALUE {@link byte[]}
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointSet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// We're using variable length fields, so track the offset
int msgOffset = 2;
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointSetSetpointType.get(payload[msgOffset] & 0x0F));
msgOffset += 1;
// Process 'Properties2'
// Size is used by 'Value'
int varSize = payload[msgOffset] & 0x07;
response.put("SCALE", constantHumidityControlSetpointSetScale.get((payload[msgOffset] & 0x18) >> 3));
response.put("PRECISION", Integer.valueOf(payload[msgOffset] & 0xE0 >> 5));
msgOffset += 1;
// Process 'Value'
ByteArrayOutputStream valValue = new ByteArrayOutputStream();
for (int cntValue = 0; cntValue < varSize; cntValue++) {
valValue.write(payload[msgOffset + cntValue]);
}
response.put("VALUE", valValue.toByteArray());
msgOffset += varSize;
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_GET command.
* <p>
* Humidity Control Setpoint Get
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointGet(String setpointType) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_GET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_GET);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointGetSetpointType.keySet()) {
if (constantHumidityControlSetpointGetSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_GET command.
* <p>
* Humidity Control Setpoint Get
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointGet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointGetSetpointType.get(payload[2] & 0x0F));
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_REPORT command.
* <p>
* Humidity Control Setpoint Report
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @param scale {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @param precision {@link Integer}
* @param value {@link byte[]}
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointReport(String setpointType, String scale, Integer precision,
byte[] value) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_REPORT version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_REPORT);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointReportSetpointType.keySet()) {
if (constantHumidityControlSetpointReportSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
// Process 'Properties2'
// Size is used by 'Value'
int size = value.length;
int valProperties2 = 0;
valProperties2 |= size & 0x07;
int varScale = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointReportScale.keySet()) {
if (constantHumidityControlSetpointReportScale.get(entry).equals(scale)) {
varScale = entry;
break;
}
}
if (varScale == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scale + "' for scale");
}
valProperties2 |= varScale << 3 & 0x18;
valProperties2 |= ((precision << 5) & 0xE0);
outputData.write(valProperties2);
// Process 'Value'
if (value != null) {
try {
outputData.write(value);
} catch (IOException e) {
}
}
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_REPORT command.
* <p>
* Humidity Control Setpoint Report
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* <li>SCALE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* <li>PRECISION {@link Integer}
* <li>VALUE {@link byte[]}
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointReport(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// We're using variable length fields, so track the offset
int msgOffset = 2;
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointReportSetpointType.get(payload[msgOffset] & 0x0F));
msgOffset += 1;
// Process 'Properties2'
// Size is used by 'Value'
int varSize = payload[msgOffset] & 0x07;
response.put("SCALE", constantHumidityControlSetpointReportScale.get((payload[msgOffset] & 0x18) >> 3));
response.put("PRECISION", Integer.valueOf(payload[msgOffset] & 0xE0 >> 5));
msgOffset += 1;
// Process 'Value'
ByteArrayOutputStream valValue = new ByteArrayOutputStream();
for (int cntValue = 0; cntValue < varSize; cntValue++) {
valValue.write(payload[msgOffset + cntValue]);
}
response.put("VALUE", valValue.toByteArray());
msgOffset += varSize;
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET command.
* <p>
* Humidity Control Setpoint Supported Get
*
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointSupportedGet() {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET command.
* <p>
* Humidity Control Setpoint Supported Get
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointSupportedGet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT command.
* <p>
* Humidity Control Setpoint Supported Report
*
* @param bitMask {@link List<String>}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointSupportedReport(List<String> bitMask) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT);
// Process 'Bit Mask'
int valBitMask = 0;
for (String value : bitMask) {
boolean foundBitMask = false;
for (Integer entry : constantHumidityControlSetpointSupportedReportBitMask.keySet()) {
if (constantHumidityControlSetpointSupportedReportBitMask.get(entry).equals(value)) {
foundBitMask = true;
valBitMask += entry;
break;
}
}
if (!foundBitMask) {
throw new IllegalArgumentException("Unknown constant value '" + bitMask + "' for bitMask");
}
}
outputData.write(valBitMask);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT command.
* <p>
* Humidity Control Setpoint Supported Report
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>BIT_MASK {@link List}<{@link String}>
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointSupportedReport(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Bit Mask'
List<String> responseBitMask = new ArrayList<String>();
int lenBitMask = 1;
for (int cntBitMask = 0; cntBitMask < lenBitMask; cntBitMask++) {
if ((payload[2 + (cntBitMask / 8)] & (1 << cntBitMask % 8)) == 0) {
continue;
}
responseBitMask.add(constantHumidityControlSetpointSupportedReportBitMask.get(cntBitMask));
}
response.put("BIT_MASK", responseBitMask);
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET command.
* <p>
* Humidity Control Setpoint Scale Supported Get
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointScaleSupportedGet(String setpointType) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointScaleSupportedGetSetpointType.keySet()) {
if (constantHumidityControlSetpointScaleSupportedGetSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET command.
* <p>
* Humidity Control Setpoint Scale Supported Get
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointScaleSupportedGet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointScaleSupportedGetSetpointType.get(payload[2] & 0x0F));
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT command.
* <p>
* Humidity Control Setpoint Scale Supported Report
*
* @param scaleBitMask {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointScaleSupportedReport(String scaleBitMask) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT);
// Process 'Properties1'
int varScaleBitMask = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointScaleSupportedReportScaleBitMask.keySet()) {
if (constantHumidityControlSetpointScaleSupportedReportScaleBitMask.get(entry).equals(scaleBitMask)) {
varScaleBitMask = entry;
break;
}
}
if (varScaleBitMask == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scaleBitMask + "' for scaleBitMask");
}
outputData.write(varScaleBitMask & 0x0F);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT command.
* <p>
* Humidity Control Setpoint Scale Supported Report
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SCALE_BIT_MASK {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointScaleSupportedReport(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Properties1'
response.put("SCALE_BIT_MASK", constantHumidityControlSetpointScaleSupportedReportScaleBitMask.get(payload[2] & 0x0F));
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET command.
* <p>
* Humidity Control Setpoint Capabilities Get
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointCapabilitiesGet(String setpointType) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointCapabilitiesGetSetpointType.keySet()) {
if (constantHumidityControlSetpointCapabilitiesGetSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET command.
* <p>
* Humidity Control Setpoint Capabilities Get
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointCapabilitiesGet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointCapabilitiesGetSetpointType.get(payload[2] & 0x0F));
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT command.
* <p>
* Humidity Control Setpoint Capabilities Report
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @param scale1 {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @param precision1 {@link Integer}
* @param minimumValue {@link byte[]}
* @param scale2 {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @param precision2 {@link Integer}
* @param maximumValue {@link byte[]}
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointCapabilitiesReport(String setpointType, String scale1,
Integer precision1, byte[] minimumValue, String scale2, Integer precision2, byte[] maximumValue) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointCapabilitiesReportSetpointType.keySet()) {
if (constantHumidityControlSetpointCapabilitiesReportSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
// Process 'Properties2'
// Size1 is used by 'Minimum Value'
int size1 = minimumValue.length;
int valProperties2 = 0;
valProperties2 |= size1 & 0x07;
int varScale1 = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointCapabilitiesReportScale1.keySet()) {
if (constantHumidityControlSetpointCapabilitiesReportScale1.get(entry).equals(scale1)) {
varScale1 = entry;
break;
}
}
if (varScale1 == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scale1 + "' for scale1");
}
valProperties2 |= varScale1 << 3 & 0x18;
valProperties2 |= ((precision1 << 5) & 0xE0);
outputData.write(valProperties2);
// Process 'Minimum Value'
if (minimumValue != null) {
try {
outputData.write(minimumValue);
} catch (IOException e) {
}
}
// Process 'Properties3'
// Size2 is used by 'Maximum Value'
int size2 = maximumValue.length;
int valProperties3 = 0;
valProperties3 |= size2 & 0x07;
int varScale2 = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointCapabilitiesReportScale2.keySet()) {
if (constantHumidityControlSetpointCapabilitiesReportScale2.get(entry).equals(scale2)) {
varScale2 = entry;
break;
}
}
if (varScale2 == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scale2 + "' for scale2");
}
valProperties3 |= varScale2 << 3 & 0x18;
valProperties3 |= ((precision2 << 5) & 0xE0);
outputData.write(valProperties3);
// Process 'Maximum Value'
if (maximumValue != null) {
try {
outputData.write(maximumValue);
} catch (IOException e) {
}
}
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT command.
* <p>
* Humidity Control Setpoint Capabilities Report
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* <li>SCALE1 {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* <li>PRECISION1 {@link Integer}
* <li>MINIMUM_VALUE {@link byte[]}
* <li>SCALE2 {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* <li>PRECISION2 {@link Integer}
* <li>MAXIMUM_VALUE {@link byte[]}
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointCapabilitiesReport(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// We're using variable length fields, so track the offset
int msgOffset = 2;
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointCapabilitiesReportSetpointType.get(payload[msgOffset] & 0x0F));
msgOffset += 1;
// Process 'Properties2'
// Size1 is used by 'Minimum Value'
int varSize1 = payload[msgOffset] & 0x07;
response.put("SCALE1", constantHumidityControlSetpointCapabilitiesReportScale1.get((payload[msgOffset] & 0x18) >> 3));
response.put("PRECISION1", Integer.valueOf(payload[msgOffset] & 0xE0 >> 5));
msgOffset += 1;
// Process 'Minimum Value'
ByteArrayOutputStream valMinimumValue = new ByteArrayOutputStream();
for (int cntMinimumValue = 0; cntMinimumValue < varSize1; cntMinimumValue++) {
valMinimumValue.write(payload[msgOffset + cntMinimumValue]);
}
response.put("MINIMUM_VALUE", valMinimumValue.toByteArray());
msgOffset += varSize1;
// Process 'Properties3'
// Size2 is used by 'Maximum Value'
int varSize2 = payload[msgOffset] & 0x07;
response.put("SCALE2", constantHumidityControlSetpointCapabilitiesReportScale2.get((payload[msgOffset] & 0x18) >> 3));
response.put("PRECISION2", Integer.valueOf(payload[msgOffset] & 0xE0 >> 5));
msgOffset += 1;
// Process 'Maximum Value'
ByteArrayOutputStream valMaximumValue = new ByteArrayOutputStream();
for (int cntMaximumValue = 0; cntMaximumValue < varSize2; cntMaximumValue++) {
valMaximumValue.write(payload[msgOffset + cntMaximumValue]);
}
response.put("MAXIMUM_VALUE", valMaximumValue.toByteArray());
msgOffset += varSize2;
// Return the map of processed response data;
return response;
}
}
| epl-1.0 |
jmchilton/TINT | projects/TropixStorageCore/src/api/edu/umn/msi/tropix/storage/core/StorageManager.java | 2764 | /*******************************************************************************
* Copyright 2009 Regents of the University of Minnesota. All rights
* reserved.
* Copyright 2009 Mayo Foundation for Medical Education and Research.
* All rights reserved.
*
* This program is 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
*
* 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 INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS
* OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
* PARTICULAR PURPOSE. See the License for the specific language
* governing permissions and limitations under the License.
*
* Contributors:
* Minnesota Supercomputing Institute - initial API and implementation
******************************************************************************/
package edu.umn.msi.tropix.storage.core;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import edu.umn.msi.tropix.common.io.HasStreamInputContext;
public interface StorageManager {
static interface UploadCallback {
void onUpload(InputStream inputStream);
}
static class FileMetadata {
private final long dateModified;
private final long length;
public FileMetadata(final long dateModified, final long length) {
this.dateModified = dateModified;
this.length = length;
}
public long getDateModified() {
return dateModified;
}
public long getLength() {
return length;
}
}
@Deprecated
long getDateModified(final String id, final String gridId);
boolean setDateModified(final String id, final String gridId, final long dataModified);
@Deprecated
long getLength(final String id, final String gridId);
FileMetadata getFileMetadata(final String id, final String gridId);
List<FileMetadata> getFileMetadata(final List<String> ids, final String gridId);
HasStreamInputContext download(String id, String gridId);
// Allow batch pre-checking to avoid extra database hits
HasStreamInputContext download(final String id, final String gridId, final boolean checkAccess);
UploadCallback upload(String id, String gridId);
OutputStream prepareUploadStream(final String id, final String gridId);
boolean delete(String id, String gridId);
boolean exists(String id);
boolean canDelete(String id, String callerIdentity);
boolean canDownload(String id, String callerIdentity);
boolean canUpload(String id, String callerIdentity);
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | utils/eclipselink.utils.workbench/mappingsmodel/source/org/eclipse/persistence/tools/workbench/mappingsmodel/handles/MWAttributeHandle.java | 5578 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.mappingsmodel.handles;
import org.eclipse.persistence.tools.workbench.mappingsmodel.MWModel;
import org.eclipse.persistence.tools.workbench.mappingsmodel.meta.MWClass;
import org.eclipse.persistence.tools.workbench.mappingsmodel.meta.MWClassAttribute;
import org.eclipse.persistence.tools.workbench.utility.node.Node;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.mappings.OneToOneMapping;
import org.eclipse.persistence.oxm.XMLDescriptor;
/**
* MWAttributeHandle is used to isolate the painful bits of code
* necessary to correctly handle references to MWClassAttributes.
*
* Since a MWClassAttribute is nested within the XML file
* for a MWClass, we need to store a reference to a particular
* attribute as a pair of instance variables:
* - the name of the declaring MWClass
* - the name of the attribute
*
* This causes no end of pain when dealing with TopLink, property
* change listeners, backward-compatibility, etc.
*/
public final class MWAttributeHandle extends MWHandle {
/**
* This is the actual attribute.
* It is built from the declaring type and attribute names, below.
*/
private volatile MWClassAttribute attribute;
/**
* The declaring type and attribute names are transient. They
* are used only to hold their values until postProjectBuild()
* is called and we can resolve the actual attribute.
* We do not keep these in synch with the attribute itself because
* we cannot know when the attribute has been renamed etc.
*/
private volatile String attributeDeclaringTypeName;
private volatile String attributeName;
// ********** constructors **********
/**
* default constructor - for TopLink use only
*/
private MWAttributeHandle() {
super();
}
public MWAttributeHandle(MWModel parent, NodeReferenceScrubber scrubber) {
super(parent, scrubber);
}
public MWAttributeHandle(MWModel parent, MWClassAttribute attribute, NodeReferenceScrubber scrubber) {
super(parent, scrubber);
this.attribute = attribute;
}
// ********** instance methods **********
public MWClassAttribute getAttribute() {
return this.attribute;
}
public void setAttribute(MWClassAttribute attribute) {
this.attribute = attribute;
}
protected Node node() {
return getAttribute();
}
public MWAttributeHandle setScrubber(NodeReferenceScrubber scrubber) {
this.setScrubberInternal(scrubber);
return this;
}
public void postProjectBuild() {
super.postProjectBuild();
if (this.attributeDeclaringTypeName != null && this.attributeName != null) {
// the type will never be null - the repository will auto-generate one if necessary
this.attribute = this.typeNamed(this.attributeDeclaringTypeName).attributeNamedFromCombinedAll(this.attributeName);
}
// Ensure attributeDeclaringTypeName and attributeName are not
// used by setting them to null....
// If the XML is corrupt and only one of these attributes is populated,
// this will cause the populated attribute to be cleared out if the
// objects are rewritten.
this.attributeDeclaringTypeName = null;
this.attributeName = null;
}
/**
* Override to delegate comparison to the attribute itself.
* If the handles being compared are in a collection that is being sorted,
* NEITHER attribute should be null.
*/
public int compareTo(Object o) {
return this.attribute.compareTo(((MWAttributeHandle) o).attribute);
}
public void toString(StringBuffer sb) {
if (this.attribute == null) {
sb.append("null");
} else {
this.attribute.toString(sb);
}
}
// ********** TopLink methods **********
public static XMLDescriptor buildDescriptor(){
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setJavaClass(MWAttributeHandle.class);
descriptor.addDirectMapping("attributeDeclaringTypeName", "getAttributeDeclaringTypeNameForTopLink", "setAttributeDeclaringTypeNameForTopLink", "attribute-declaring-type-name/text()");
descriptor.addDirectMapping("attributeName", "getAttributeNameForTopLink", "setAttributeNameForTopLink", "attribute-name/text()");
return descriptor;
}
private String getAttributeDeclaringTypeNameForTopLink(){
return (this.attribute == null) ? null : this.attribute.getDeclaringType().getName();
}
private void setAttributeDeclaringTypeNameForTopLink(String attributeDeclaringTypeName){
this.attributeDeclaringTypeName = attributeDeclaringTypeName;
}
private String getAttributeNameForTopLink() {
return (this.attribute == null) ? null : attribute.getName();
}
private void setAttributeNameForTopLink(String attributeName) {
this.attributeName = attributeName;
}
}
| epl-1.0 |
happyspace/goclipse | plugin_ide.ui/src-lang/melnorme/util/swt/components/fields/SpinnerNumberField.java | 2850 | /*******************************************************************************
* Copyright (c) 2014 Bruno Medeiros and other Contributors.
* 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:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.util.swt.components.fields;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Spinner;
import melnorme.util.swt.SWTLayoutUtil;
import melnorme.util.swt.SWTUtil;
import melnorme.util.swt.components.FieldComponent;
import melnorme.util.swt.components.LabelledFieldComponent;
public class SpinnerNumberField extends LabelledFieldComponent<Integer> {
protected Spinner spinner;
public SpinnerNumberField(String labelText) {
super(labelText, Option_AllowNull.NO, 0);
}
@Override
public int getPreferredLayoutColumns() {
return 2;
}
@Override
protected void createContents_all(Composite topControl) {
createContents_Label(topControl);
createContents_Spinner(topControl);
}
@Override
protected void createContents_layout() {
SWTLayoutUtil.layout2Controls_spanLast(label, spinner);
}
protected void createContents_Spinner(Composite parent) {
spinner = createFieldSpinner(this, parent, SWT.BORDER);
}
public Spinner getSpinner() {
return spinner;
}
@Override
public Spinner getFieldControl() {
return spinner;
}
@Override
protected void doUpdateComponentFromValue() {
spinner.setSelection(getFieldValue());
}
public SpinnerNumberField setValueMinimum(int minimum) {
spinner.setMinimum(minimum);
return this;
}
public SpinnerNumberField setValueMaximum(int maximum) {
spinner.setMaximum(maximum);
return this;
}
public SpinnerNumberField setValueIncrement(int increment) {
spinner.setIncrement(increment);
return this;
}
@Override
public void setEnabled(boolean enabled) {
SWTUtil.setEnabledIfOk(label, enabled);
SWTUtil.setEnabledIfOk(spinner, enabled);
}
/* ----------------- ----------------- */
public static Spinner createFieldSpinner(FieldComponent<Integer> field, Composite parent, int style) {
final Spinner spinner = new Spinner(parent, style);
spinner.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
field.setFieldValueFromControl(spinner.getSelection());
}
});
return spinner;
}
} | epl-1.0 |
gmussbacher/seg.jUCMNav | src/ucm/map/UCMmap.java | 2263 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package ucm.map;
import core.COREModel;
import org.eclipse.emf.common.util.EList;
import urncore.IURNDiagram;
import urncore.UCMmodelElement;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>UC Mmap</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link ucm.map.UCMmap#isSingleton <em>Singleton</em>}</li>
* <li>{@link ucm.map.UCMmap#getParentStub <em>Parent Stub</em>}</li>
* </ul>
* </p>
*
* @see ucm.map.MapPackage#getUCMmap()
* @model
* @generated
*/
public interface UCMmap extends UCMmodelElement, IURNDiagram, COREModel {
/**
* Returns the value of the '<em><b>Singleton</b></em>' attribute.
* The default value is <code>"true"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Singleton</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Singleton</em>' attribute.
* @see #setSingleton(boolean)
* @see ucm.map.MapPackage#getUCMmap_Singleton()
* @model default="true"
* @generated
*/
boolean isSingleton();
/**
* Sets the value of the '{@link ucm.map.UCMmap#isSingleton <em>Singleton</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Singleton</em>' attribute.
* @see #isSingleton()
* @generated
*/
void setSingleton(boolean value);
/**
* Returns the value of the '<em><b>Parent Stub</b></em>' reference list.
* The list contents are of type {@link ucm.map.PluginBinding}.
* It is bidirectional and its opposite is '{@link ucm.map.PluginBinding#getPlugin <em>Plugin</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Parent Stub</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Parent Stub</em>' reference list.
* @see ucm.map.MapPackage#getUCMmap_ParentStub()
* @see ucm.map.PluginBinding#getPlugin
* @model type="ucm.map.PluginBinding" opposite="plugin"
* @generated
*/
EList getParentStub();
} // UCMmap
| epl-1.0 |
theArchonius/gerrit-attachments | src/test/java/com/eclipsesource/gerrit/plugins/fileattachment/api/test/converter/BaseAttachmentTargetResponseEntityReaderTest.java | 12234 | /**
*
*/
package com.eclipsesource.gerrit.plugins.fileattachment.api.test.converter;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTarget;
import com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.FileDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetEntity.TargetType;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetResponseEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.FileDescriptionEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.OperationResultEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.OperationResultEntity.ResultStatus;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.converter.BaseAttachmentTargetResponseEntityReader;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.ChangeTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.GenericFileDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchSetTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchTarget;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchTargetDescription;
/**
* @author Florian Zoubek
*
*/
public class BaseAttachmentTargetResponseEntityReaderTest {
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles Success responses with file descriptions.
*/
@Test
public void testSuccessConversionWithFiles() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build expected result
PatchTargetDescription patchTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
List<FileDescription> expectedFileDescriptions =
new ArrayList<FileDescription>(2);
expectedFileDescriptions.add(new GenericFileDescription("/subdir/",
"file1.txt"));
expectedFileDescriptions.add(new GenericFileDescription("/subdir/",
"file2.txt"));
AttachmentTarget expectedAttachmentTarget =
new PatchTarget(patchTargetDescription, expectedFileDescriptions);
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
// build input parameters
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, patchTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(expectedAttachmentTarget));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles Success responses without file descriptions.
*/
@Test
public void testSuccessConversionWithoutFiles() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build expected result
PatchTargetDescription patchTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
List<FileDescription> expectedFileDescriptions =
new ArrayList<FileDescription>(0);
AttachmentTarget expectedAttachmentTarget =
new PatchTarget(patchTargetDescription, expectedFileDescriptions);
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
// build input parameters
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[0];
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, patchTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(expectedAttachmentTarget));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles unsupported attachment targets correctly.
*/
@Test
public void testInvalidAttachmentTargetConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build input parameters
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[0];
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
// PatchSetTargetDescription
AttachmentTargetDescription attachmentTargetDescription =
new PatchSetTargetDescription(new ChangeTargetDescription(
"I0000000000000000"), 0);
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, attachmentTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// ChangeTargetDescription
attachmentTargetDescription =
new ChangeTargetDescription("I0000000000000000");
Assert.assertThat(attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles responses containing a failed operation result.
*/
@Test
public void testFailedOperationConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.FAILED, "Some error occured");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
for (TargetType targetType : TargetType.values()) {
// build input parameters
AttachmentTargetEntity attachmentTargetEntityWithFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithFiles =
new AttachmentTargetResponseEntity(attachmentTargetEntityWithFiles,
operationResultEntity);
AttachmentTargetEntity attachmentTargetEntityWithoutFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithoutFiles =
new AttachmentTargetResponseEntity(
attachmentTargetEntityWithoutFiles, operationResultEntity);
AttachmentTargetDescription attachmentTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
// begin testing
// without files
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntityWithoutFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithoutFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// with files
attachmentTarget =
entityReader.toObject(jsonEntityWithFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles responses containing a "not permitted" operation result.
*/
@Test
public void testNotPermittedOperationConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.NOTPERMITTED, "Some error occured");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
for (TargetType targetType : TargetType.values()) {
// build input parameters
AttachmentTargetEntity attachmentTargetEntityWithFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithFiles =
new AttachmentTargetResponseEntity(attachmentTargetEntityWithFiles,
operationResultEntity);
AttachmentTargetEntity attachmentTargetEntityWithoutFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithoutFiles =
new AttachmentTargetResponseEntity(
attachmentTargetEntityWithoutFiles, operationResultEntity);
AttachmentTargetDescription attachmentTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
// begin testing
// without files
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntityWithoutFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithoutFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// with files
attachmentTarget =
entityReader.toObject(jsonEntityWithFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/dynamic/DynamicJAXBFromXSDTestCases.java | 51899 | /*******************************************************************************
* Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* rbarkhouse - 2.1 - initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.dynamic;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.UndeclaredThrowableException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import junit.framework.TestCase;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.internal.helper.ClassConstants;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
import org.eclipse.persistence.testing.jaxb.dynamic.util.NoExtensionEntityResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class DynamicJAXBFromXSDTestCases extends TestCase {
DynamicJAXBContext jaxbContext;
static {
try {
// Disable XJC's schema correctness check. XSD imports do not seem to work if this is left on.
System.setProperty("com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.noCorrectnessCheck", "true");
} catch (Exception e) {
// Ignore
}
}
public DynamicJAXBFromXSDTestCases(String name) throws Exception {
super(name);
}
public String getName() {
return "Dynamic JAXB: XSD: " + super.getName();
}
public void testEclipseLinkSchema() throws Exception {
// Bootstrapping from eclipselink_oxm_2_4.xsd will trigger a JAXB 2.2 API (javax.xml.bind.annotation.XmlElementRef.required())
// so only run this test in Java 7
if (System.getProperty("java.version").contains("1.7")) {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(ECLIPSELINK_SCHEMA);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
}
}
// ====================================================================
public void testXmlSchemaQualified() throws Exception {
// <xs:schema targetNamespace="myNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"
// attributeFormDefault="qualified" elementFormDefault="qualified">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_QUALIFIED);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Make sure "targetNamespace" was interpreted properly.
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Target Namespace was not set as expected.", "myNamespace", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// elementFormDefault=qualified, so the root node, the
// root node's attribute, and the child node should all have a prefix.
assertNotNull("Root node did not have namespace prefix as expected.", node.getPrefix());
Node attr = node.getAttributes().item(0);
assertNotNull("Attribute did not have namespace prefix as expected.", attr.getPrefix());
Node childNode = node.getChildNodes().item(0);
assertNotNull("Child node did not have namespace prefix as expected.", childNode.getPrefix());
}
public void testXmlSchemaUnqualified() throws Exception {
// <xs:schema targetNamespace="myNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema"
// attributeFormDefault="unqualified" elementFormDefault="unqualified">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_UNQUALIFIED);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Make sure "targetNamespace" was interpreted properly.
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Target Namespace was not set as expected.", "myNamespace", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// elementFormDefault=unqualified, so the root node should have a prefix
// but the root node's attribute and child node should not.
assertNotNull("Root node did not have namespace prefix as expected.", node.getPrefix());
// Do not test attribute prefix with the Oracle xmlparserv2, it qualifies attributes by default.
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
if (builderFactory.getClass().getPackage().getName().contains("oracle")) {
return;
} else {
Node attr = node.getAttributes().item(0);
assertNull("Attribute should not have namespace prefix (" + attr.getPrefix() + ").", attr.getPrefix());
}
Node childNode = node.getChildNodes().item(0);
assertNull("Child node should not have namespace prefix.", childNode.getPrefix());
}
public void testXmlSchemaDefaults() throws Exception {
// <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_DEFAULTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(DEF_PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// "targetNamespace" should be null by default
Node node = marshalDoc.getChildNodes().item(0);
assertNull("Target Namespace was not null as expected.", node.getNamespaceURI());
// Make sure "elementFormDefault" was interpreted properly.
// When unset, no namespace qualification is done.
assertNull("Root node should not have namespace prefix.", node.getPrefix());
Node attr = node.getAttributes().item(0);
assertNull("Attribute should not have namespace prefix.", attr.getPrefix());
Node childNode = node.getChildNodes().item(0);
assertNull("Child node should not have namespace prefix.", childNode.getPrefix());
}
public void testXmlSchemaImport() throws Exception {
// <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
// <xs:import schemaLocation="xmlschema-currency" namespace="bankNamespace"/>
// Do not run this test if we are not using JDK 1.6
String javaVersion = System.getProperty("java.version");
if (!(javaVersion.startsWith("1.6"))) {
return;
}
// Do not run this test with the Oracle xmlparserv2, it will not properly hit the EntityResolver
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
if (builderFactory.getClass().getPackage().getName().contains("oracle")) {
return;
}
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_IMPORT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, new NoExtensionEntityResolver(), null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity salary = jaxbContext.newDynamicEntity(BANK_PACKAGE + "." + CDN_CURRENCY);
assertNotNull("Could not create Dynamic Entity.", salary);
salary.set("value", new BigDecimal(75425.75));
person.set("name", "Bob Dobbs");
person.set("salary", salary);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person);
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
// Nothing to really test, if the import failed we couldn't have created the salary.
}
public void testXmlSeeAlso() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSEEALSO);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + EMPLOYEE);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
person.set("employeeId", "CA2472");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
// Nothing to really test, XmlSeeAlso isn't represented in an instance doc.
}
public void testXmlRootElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLROOTELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + INDIVIDUO);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Root element was not 'individuo' as expected.", "individuo", node.getLocalName());
}
public void testXmlType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLTYPE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("email", "bdobbs@subgenius.com");
person.set("lastName", "Dobbs");
person.set("id", 678);
person.set("phoneNumber", "212-555-8282");
person.set("firstName", "Bob");
JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
// Test that XmlType.propOrder was interpreted properly
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "id", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(1);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "first-name", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(2);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "last-name", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(3);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "phone-number", node.getLocalName());
node = marshalDoc.getDocumentElement().getChildNodes().item(4);
assertNotNull("Node was null.", node);
assertEquals("Unexpected node.", "email", node.getLocalName());
}
public void testXmlAttribute() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLATTRIBUTE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 777);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person);
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
if (node.getAttributes() == null || node.getAttributes().getNamedItem("id") == null) {
fail("Attribute not present.");
}
}
public void testXmlElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("type", "O+");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person);
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
String elemName = node.getChildNodes().item(0).getNodeName();
assertEquals("Element not present.", "type", elemName);
}
public void testXmlElementCollection() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTCOLLECTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList nicknames = new ArrayList();
nicknames.add("Bobby");
nicknames.add("Dobsy");
nicknames.add("Big Kahuna");
person.set("nickname", nicknames);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person);
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
assertEquals("Unexpected number of child nodes present.", 3, node.getChildNodes().getLength());
}
public void testXmlElementCustomized() throws Exception {
// Customize the EclipseLink mapping generation by providing an eclipselink-oxm.xml
String metadataFile = RESOURCE_DIR + "eclipselink-oxm.xml";
InputStream iStream = ClassLoader.getSystemResourceAsStream(metadataFile);
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put(CONTEXT_PATH, new StreamSource(iStream));
Map<String, Object> props = new HashMap<String, Object>();
props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, props);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("type", "O+");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertNotNull("Element not present.", node.getChildNodes());
String elemName = node.getChildNodes().item(0).getNodeName();
// 'type' was renamed to 'bloodType' in the OXM bindings file
assertEquals("Element not present.", "bloodType", elemName);
}
public void testXmlList() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLLIST);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList<String> codes = new ArrayList<String>(3);
codes.add("D1182");
codes.add("D1716");
codes.add("G7212");
person.set("name", "Bob Dobbs");
person.set("codes", codes);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertEquals("Unexpected number of nodes in document.", 2, node.getChildNodes().getLength());
String value = node.getChildNodes().item(1).getTextContent();
assertEquals("Unexpected element contents.", "D1182 D1716 G7212", value);
}
public void testXmlValue() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLVALUE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity salary = jaxbContext.newDynamicEntity(PACKAGE + "." + CDN_CURRENCY);
assertNotNull("Could not create Dynamic Entity.", salary);
salary.set("value", new BigDecimal(75100));
person.set("name", "Bob Dobbs");
person.set("salary", salary);
JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
// Nothing to really test, XmlValue isn't represented in an instance doc.
}
public void testXmlAnyElement() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLANYELEMENT);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
person.set("any", "StringValue");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertTrue("Any element not found.", node.getChildNodes().item(1).getNodeType() == Node.TEXT_NODE);
}
public void testXmlAnyAttribute() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLANYATTRIBUTE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
Map<QName, Object> otherAttributes = new HashMap<QName, Object>();
otherAttributes.put(new QName("foo"), new BigDecimal(1234));
otherAttributes.put(new QName("bar"), Boolean.FALSE);
person.set("name", "Bob Dobbs");
person.set("otherAttributes", otherAttributes);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
Node otherAttributesNode = node.getAttributes().getNamedItem("foo");
assertNotNull("'foo' attribute not found.", otherAttributesNode);
otherAttributesNode = node.getAttributes().getNamedItem("bar");
assertNotNull("'bar' attribute not found.", otherAttributesNode);
}
public void testXmlMixed() throws Exception {
// Also tests XmlElementRef / XmlElementRefs
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLMIXED);
try {
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList();
list.add("Hello");
list.add(new JAXBElement<String>(new QName("myNamespace", "title"), String.class, person.getClass(), "MR"));
list.add(new JAXBElement<String>(new QName("myNamespace", "name"), String.class, person.getClass(), "Bob Dobbs"));
list.add(", your point balance is");
list.add(new JAXBElement<BigInteger>(new QName("myNamespace", "rewardPoints"), BigInteger.class, person.getClass(), BigInteger.valueOf(175)));
list.add("Visit www.rewards.com!");
person.set("content", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement();
assertTrue("Unexpected number of elements.", node.getChildNodes().getLength() == 6);
}
public void testXmlId() throws Exception {
// Tests both XmlId and XmlIdRef
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLID);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity data = jaxbContext.newDynamicEntity(PACKAGE + "." + DATA);
assertNotNull("Could not create Dynamic Entity.", data);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
DynamicEntity company = jaxbContext.newDynamicEntity(PACKAGE + "." + COMPANY);
assertNotNull("Could not create Dynamic Entity.", company);
company.set("name", "ACME International");
company.set("address", "165 Main St, Anytown US, 93012");
company.set("id", "882");
person.set("name", "Bob Dobbs");
person.set("company", company);
data.set("person", person);
data.set("company", company);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(data, marshalDoc);
// 'person' node
Node pNode = marshalDoc.getDocumentElement().getChildNodes().item(0);
// 'company' node
Node cNode = pNode.getChildNodes().item(1);
// If IDREF worked properly, the company element should only contain the id of the company object
assertEquals("'company' has unexpected number of child nodes.", 1, cNode.getChildNodes().getLength());
}
public void testXmlElements() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList(1);
list.add("BOB");
person.set("nameOrReferenceNumber", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "name", node.getNodeName());
person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
list = new ArrayList(1);
list.add(328763);
person.set("nameOrReferenceNumber", list);
marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "reference-number", node.getNodeName());
}
public void testXmlElementRef() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTREF);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
ArrayList list = new ArrayList(1);
list.add("BOB");
person.set("nameOrReferenceNumber", list);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "name", node.getNodeName());
person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
list = new ArrayList(1);
list.add(328763);
person.set("nameOrReferenceNumber", list);
marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected element name.", "reference-number", node.getNodeName());
}
public void testXmlSchemaType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMATYPE);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("dateOfBirth", DatatypeFactory.newInstance().newXMLGregorianCalendarDate(1976, 02, 17, DatatypeConstants.FIELD_UNDEFINED));
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
Node node = marshalDoc.getDocumentElement().getChildNodes().item(0);
assertEquals("Unexpected date value.", "1976-02-17", node.getTextContent());
}
public void testXmlEnum() throws Exception {
// Tests XmlEnum and XmlEnumValue
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
Object NORTH = jaxbContext.getEnumConstant(PACKAGE + "." + COMPASS_DIRECTION, NORTH_CONSTANT);
assertNotNull("Could not find enum constant.", NORTH);
person.set("quadrant", NORTH);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testXmlEnumBig() throws Exception {
// Tests XmlEnum and XmlEnumValue
// This test schema contains >128 enum values to test an ASM boundary case
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM_BIG);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
Object EST = jaxbContext.getEnumConstant(DEF_PACKAGE + "." + TIME_ZONE, EST_CONSTANT);
assertNotNull("Could not find enum constant.", EST);
}
public void testXmlEnumError() throws Exception {
// Tests XmlEnum and XmlEnumValue
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
Exception caughtException = null;
try {
Object NORTHWEST = jaxbContext.getEnumConstant(PACKAGE + "." + COMPASS_DIRECTION, "NORTHWEST");
} catch (Exception e) {
caughtException = e;
}
assertNotNull("Expected exception was not thrown.", caughtException);
}
public void testXmlElementDecl() throws Exception {
// Also tests XmlRegistry
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTDECL);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXBElement jbe = new JAXBElement(new QName("individuo"), DynamicEntity.class, person);
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
Node node = marshalDoc.getChildNodes().item(0);
assertEquals("Root element was not 'individuo' as expected.", "individuo", node.getLocalName());
}
public void testSchemaWithJAXBBindings() throws Exception {
// jaxbcustom.xsd specifies that the generated package name should be "foo.bar" and
// the person type will be named MyPersonType in Java
InputStream inputStream = ClassLoader.getSystemResourceAsStream(JAXBCUSTOM);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity("foo.bar.MyPersonType");
assertNotNull("Could not create Dynamic Entity.", person);
person.set("name", "Bob Dobbs");
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testSubstitutionGroupsUnmarshal() throws Exception {
try {
InputStream xsdStream = ClassLoader.getSystemResourceAsStream(SUBSTITUTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(xsdStream, null, null, null);
InputStream xmlStream = ClassLoader.getSystemResourceAsStream(PERSON_XML);
JAXBElement person = (JAXBElement) jaxbContext.createUnmarshaller().unmarshal(xmlStream);
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "person"), person.getName());
JAXBElement name = (JAXBElement) ((DynamicEntity) person.getValue()).get("name");
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "name"), name.getName());
// ====================================================================
InputStream xmlStream2 = ClassLoader.getSystemResourceAsStream(PERSONNE_XML);
JAXBElement person2 = (JAXBElement) jaxbContext.createUnmarshaller().unmarshal(xmlStream2);
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "personne"), person2.getName());
JAXBElement name2 = (JAXBElement) ((DynamicEntity) person2.getValue()).get("name");
assertEquals("Element was not substituted properly: ", new QName("myNamespace", "nom"), name2.getName());
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
public void testSubstitutionGroupsMarshal() throws Exception {
try {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(SUBSTITUTION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
QName personQName = new QName("myNamespace", "person");
DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
JAXBElement<DynamicEntity> personElement = new JAXBElement<DynamicEntity>(personQName, DynamicEntity.class, person);
personElement.setValue(person);
QName nameQName = new QName("myNamespace", "name");
JAXBElement<String> nameElement = new JAXBElement<String>(nameQName, String.class, "Marty Friedman");
person.set("name", nameElement);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(personElement, marshalDoc);
Node node1 = marshalDoc.getDocumentElement();
assertEquals("Incorrect element name: ", "person", node1.getLocalName());
Node node2 = node1.getFirstChild();
assertEquals("Incorrect element name: ", "name", node2.getLocalName());
// ====================================================================
QName personneQName = new QName("myNamespace", "personne");
DynamicEntity personne = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON);
JAXBElement<DynamicEntity> personneElement = new JAXBElement<DynamicEntity>(personneQName, DynamicEntity.class, personne);
personneElement.setValue(personne);
QName nomQName = new QName("myNamespace", "nom");
JAXBElement<String> nomElement = new JAXBElement<String>(nomQName, String.class, "Marty Friedman");
personne.set("name", nomElement);
Document marshalDoc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(personneElement, marshalDoc2);
Node node3 = marshalDoc2.getDocumentElement();
assertEquals("Incorrect element name: ", "personne", node3.getLocalName());
Node node4 = node3.getFirstChild();
assertEquals("Incorrect element name: ", "nom", node4.getLocalName());
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
// ====================================================================
public void testTypePreservation() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_DEFAULTS);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity(DEF_PACKAGE + "." + PERSON);
assertNotNull("Could not create Dynamic Entity.", person);
person.set("id", 456);
person.set("name", "Bob Dobbs");
person.set("salary", 45000.00);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
DynamicEntity readPerson = (DynamicEntity) jaxbContext.createUnmarshaller().unmarshal(marshalDoc);
assertEquals("Property type was not preserved during unmarshal.", Double.class, readPerson.<Object>get("salary").getClass());
assertEquals("Property type was not preserved during unmarshal.", Integer.class, readPerson.<Object>get("id").getClass());
}
public void testNestedInnerClasses() throws Exception {
// Tests multiple levels of inner classes, eg. mynamespace.Person.RelatedResource.Link
InputStream inputStream = ClassLoader.getSystemResourceAsStream(NESTEDINNERCLASSES);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
DynamicEntity resource = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource");
DynamicEntity link = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource.Link");
DynamicEntity link2 = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource.Link");
link.set("linkName", "LINKFOO");
link2.set("linkName", "LINKFOO2");
resource.set("resourceName", "RESBAR");
ArrayList<DynamicEntity> links = new ArrayList<DynamicEntity>();
links.add(link);
links.add(link2);
resource.set("link", links);
person.set("name", "Bob Smith");
person.set("relatedResource", resource);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person);
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
}
public void testBinary() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(BINARY);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
byte[] byteArray = new byte[] {30,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
person.set("name", "B. Nary");
person.set("abyte", (byte) 30);
person.set("base64", byteArray);
person.set("hex", byteArray);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
jaxbContext.createMarshaller().marshal(person, marshalDoc);
}
public void testBinaryGlobalType() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(BINARY2);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
byte[] byteArray = new byte[] {30,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person");
person.set("name", "B. Nary");
person.set("abyte", (byte) 30);
person.set("base64", byteArray);
person.set("hex", byteArray);
Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person);
jaxbContext.createMarshaller().marshal(jbe, marshalDoc);
}
public void testXMLSchemaSchema() throws Exception {
try {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMASCHEMA);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
DynamicEntity schema = jaxbContext.newDynamicEntity("org.w3._2001.xmlschema.Schema");
schema.set("targetNamespace", "myNamespace");
Object QUALIFIED = jaxbContext.getEnumConstant("org.w3._2001.xmlschema.FormChoice", "QUALIFIED");
schema.set("attributeFormDefault", QUALIFIED);
DynamicEntity complexType = jaxbContext.newDynamicEntity("org.w3._2001.xmlschema.TopLevelComplexType");
complexType.set("name", "myComplexType");
List<DynamicEntity> complexTypes = new ArrayList<DynamicEntity>(1);
complexTypes.add(complexType);
schema.set("simpleTypeOrComplexTypeOrGroup", complexTypes);
List<Object> blocks = new ArrayList<Object>();
blocks.add("FOOBAR");
schema.set("blockDefault", blocks);
File f = new File("myschema.xsd");
jaxbContext.createMarshaller().marshal(schema, f);
} catch (JAXBException e) {
// If running in a non-JAXB 2.2 environment, we will get this error because the required() method
// on @XmlElementRef is missing. Just ignore this and pass the test.
if (e.getLinkedException() instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
} catch (Exception e) {
if (e instanceof UndeclaredThrowableException) {
return;
} else {
throw e;
}
}
}
public void testGetByXPathPosition() throws Exception {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(XPATH_POSITION);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
InputStream xmlStream = ClassLoader.getSystemResourceAsStream(XPATH_POSITION_XML);
JAXBElement<DynamicEntity> jelem = (JAXBElement<DynamicEntity>) jaxbContext.createUnmarshaller().unmarshal(xmlStream);
DynamicEntity testBean = jelem.getValue();
Object o = jaxbContext.getValueByXPath(testBean, "array[1]/text()", null, Object.class);
assertNotNull("XPath: 'array[1]/text()' returned null.", o);
o = jaxbContext.getValueByXPath(testBean, "array[2]/text()", null, Object.class);
assertNull("XPath: 'array[2]/text()' did not return null.", o);
o = jaxbContext.getValueByXPath(testBean, "map/entry[1]/value/text()", null, Object.class);
assertEquals("foo", o);
o = jaxbContext.getValueByXPath(testBean, "sub-bean[1]/map/entry[1]/value/text()", null, Object.class);
assertEquals("foo2", o);
}
public void testDateTimeArray() throws Exception {
// Tests to ensure that XSD dateTime is always unmarshalled as XMLGregorianCalendar, and never
// as GregorianCalendar. This can fail intermittently so is tested in a loop.
HashSet<Class> elemClasses = new HashSet<Class>();
for (int i = 0; i < 50; i++) {
InputStream inputStream = ClassLoader.getSystemResourceAsStream(DATETIME_ARRAY);
jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null);
InputStream xmlStream = ClassLoader.getSystemResourceAsStream(DATETIME_ARRAY_XML);
JAXBElement<DynamicEntity> jelem = (JAXBElement<DynamicEntity>) jaxbContext.createUnmarshaller().unmarshal(xmlStream);
DynamicEntity testBean = jelem.getValue();
ArrayList array = testBean.get("array");
elemClasses.add(array.get(0).getClass());
}
assertEquals("dateTime was not consistently unmarshalled as XMLGregorianCalendar " + elemClasses, 1, elemClasses.size());
Class elemClass = (Class) elemClasses.toArray()[0];
boolean isXmlGregorianCalendar = ClassConstants.XML_GREGORIAN_CALENDAR.isAssignableFrom(elemClass);
assertTrue("dateTime was not unmarshalled as XMLGregorianCalendar", isXmlGregorianCalendar);
}
// ====================================================================
private void print(Object o) throws Exception {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(o, System.err);
}
// ====================================================================
private static final String RESOURCE_DIR = "org/eclipse/persistence/testing/jaxb/dynamic/";
private static final String CONTEXT_PATH = "mynamespace";
// Schema files used to test each annotation
private static final String XMLSCHEMA_QUALIFIED = RESOURCE_DIR + "xmlschema-qualified.xsd";
private static final String XMLSCHEMA_UNQUALIFIED = RESOURCE_DIR + "xmlschema-unqualified.xsd";
private static final String XMLSCHEMA_DEFAULTS = RESOURCE_DIR + "xmlschema-defaults.xsd";
private static final String XMLSCHEMA_IMPORT = RESOURCE_DIR + "xmlschema-import.xsd";
private static final String XMLSCHEMA_CURRENCY = RESOURCE_DIR + "xmlschema-currency.xsd";
private static final String XMLSEEALSO = RESOURCE_DIR + "xmlseealso.xsd";
private static final String XMLROOTELEMENT = RESOURCE_DIR + "xmlrootelement.xsd";
private static final String XMLTYPE = RESOURCE_DIR + "xmltype.xsd";
private static final String XMLATTRIBUTE = RESOURCE_DIR + "xmlattribute.xsd";
private static final String XMLELEMENT = RESOURCE_DIR + "xmlelement.xsd";
private static final String XMLLIST = RESOURCE_DIR + "xmllist.xsd";
private static final String XMLVALUE = RESOURCE_DIR + "xmlvalue.xsd";
private static final String XMLANYELEMENT = RESOURCE_DIR + "xmlanyelement.xsd";
private static final String XMLANYATTRIBUTE = RESOURCE_DIR + "xmlanyattribute.xsd";
private static final String XMLMIXED = RESOURCE_DIR + "xmlmixed.xsd";
private static final String XMLID = RESOURCE_DIR + "xmlid.xsd";
private static final String XMLELEMENTS = RESOURCE_DIR + "xmlelements.xsd";
private static final String XMLELEMENTREF = RESOURCE_DIR + "xmlelementref.xsd";
private static final String XMLSCHEMATYPE = RESOURCE_DIR + "xmlschematype.xsd";
private static final String XMLENUM = RESOURCE_DIR + "xmlenum.xsd";
private static final String XMLENUM_BIG = RESOURCE_DIR + "xmlenum-big.xsd";
private static final String XMLELEMENTDECL = RESOURCE_DIR + "xmlelementdecl.xsd";
private static final String XMLELEMENTCOLLECTION = RESOURCE_DIR + "xmlelement-collection.xsd";
private static final String JAXBCUSTOM = RESOURCE_DIR + "jaxbcustom.xsd";
private static final String SUBSTITUTION = RESOURCE_DIR + "substitution.xsd";
private static final String NESTEDINNERCLASSES = RESOURCE_DIR + "nestedinnerclasses.xsd";
private static final String BINARY = RESOURCE_DIR + "binary.xsd";
private static final String BINARY2 = RESOURCE_DIR + "binary2.xsd";
private static final String XMLSCHEMASCHEMA = RESOURCE_DIR + "XMLSchema.xsd";
private static final String XPATH_POSITION = RESOURCE_DIR + "xpathposition.xsd";
private static final String DATETIME_ARRAY = RESOURCE_DIR + "dateTimeArray.xsd";
private static final String ECLIPSELINK_SCHEMA = "org/eclipse/persistence/jaxb/eclipselink_oxm_2_5.xsd";
// Test Instance Docs
private static final String PERSON_XML = RESOURCE_DIR + "sub-person-en.xml";
private static final String PERSONNE_XML = RESOURCE_DIR + "sub-personne-fr.xml";
private static final String XPATH_POSITION_XML = RESOURCE_DIR + "xpathposition.xml";
private static final String DATETIME_ARRAY_XML = RESOURCE_DIR + "dateTimeArray.xml";
// Names of types to instantiate
private static final String PACKAGE = "mynamespace";
private static final String DEF_PACKAGE = "generated";
private static final String BANK_PACKAGE = "banknamespace";
private static final String PERSON = "Person";
private static final String EMPLOYEE = "Employee";
private static final String INDIVIDUO = "Individuo";
private static final String CDN_CURRENCY = "CdnCurrency";
private static final String DATA = "Data";
private static final String COMPANY = "Company";
private static final String COMPASS_DIRECTION = "CompassDirection";
private static final String TIME_ZONE = "Timezone";
private static final String NORTH_CONSTANT = "NORTH";
private static final String EST_CONSTANT = "EST";
} | epl-1.0 |
rondiplomatico/texlipse | source/net/sourceforge/texlipse/properties/BibColoringPreferencePage.java | 2392 | /*
* $Id$
*
* Copyright (c) 2004-2005 by the TeXlapse Team.
* 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 net.sourceforge.texlipse.properties;
import net.sourceforge.texlipse.TexlipsePlugin;
import net.sourceforge.texlipse.bibeditor.BibColorProvider;
import org.eclipse.jface.preference.ColorFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* The page to set syntax highlighting colors.
*
* @author kimmo
*/
public class BibColoringPreferencePage
extends FieldEditorPreferencePage
implements IWorkbenchPreferencePage {
/**
* Creates an instance of the "syntax highlighting colors" -preference page.
*/
public BibColoringPreferencePage() {
super(GRID);
setPreferenceStore(TexlipsePlugin.getDefault().getPreferenceStore());
setDescription(TexlipsePlugin.getResourceString("preferenceBibColorPageDescription"));
}
/**
* Creates the property editing UI components of this page.
*/
protected void createFieldEditors() {
addField(new ColorFieldEditor(BibColorProvider.DEFAULT, TexlipsePlugin.getResourceString("preferenceBibColorTextLabel"), getFieldEditorParent()));
addField(new ColorFieldEditor(BibColorProvider.TYPE, TexlipsePlugin.getResourceString("preferenceBibColorTypeLabel"), getFieldEditorParent()));
addField(new ColorFieldEditor(BibColorProvider.KEYWORD, TexlipsePlugin.getResourceString("preferenceBibColorKeywordLabel"), getFieldEditorParent()));
addField(new ColorFieldEditor(BibColorProvider.STRING, TexlipsePlugin.getResourceString("preferenceBibColorStringLabel"), getFieldEditorParent()));
// addField(new ColorFieldEditor(BibColorProvider.MULTI_LINE_COMMENT, TexlipsePlugin.getResourceString("preferenceBibColorMLCommentLabel"), getFieldEditorParent()));
addField(new ColorFieldEditor(BibColorProvider.SINGLE_LINE_COMMENT, TexlipsePlugin.getResourceString("preferenceBibColorCommentLabel"), getFieldEditorParent()));
}
/**
* Nothing to do.
*/
public void init(IWorkbench workbench) {
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/helper/Helper.java | 92748 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
* dminsky - added countOccurrencesOf(Object, List) API
* 08/23/2010-2.2 Michael O'Brien
* - 323043: application.xml module ordering may cause weaving not to occur causing an NPE.
* warn if expected "_persistence_*_vh" method not found
* instead of throwing NPE during deploy validation.
******************************************************************************/
package org.eclipse.persistence.internal.helper;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.eclipse.persistence.config.SystemProperties;
import org.eclipse.persistence.exceptions.ConversionException;
import org.eclipse.persistence.exceptions.EclipseLinkException;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.internal.core.helper.CoreHelper;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedClassForName;
import org.eclipse.persistence.internal.security.PrivilegedGetField;
import org.eclipse.persistence.internal.security.PrivilegedGetMethod;
import org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass;
import org.eclipse.persistence.logging.AbstractSessionLog;
import org.eclipse.persistence.logging.SessionLog;
/**
* INTERNAL:
* <p>
* <b>Purpose</b>: Define any useful methods that are missing from the base Java.
*/
public class Helper extends CoreHelper implements Serializable {
/** Used to configure JDBC level date optimization. */
public static boolean shouldOptimizeDates = false;
/** Used to store null values in hashtables, is helper because need to be serializable. */
public static final Object NULL_VALUE = new Helper();
/** PERF: Used to cache a set of calendars for conversion/printing purposes. */
protected static Queue<Calendar> calendarCache = initCalendarCache();
/** PERF: Cache default timezone for calendar conversion. */
protected static TimeZone defaultTimeZone = TimeZone.getDefault();
// Changed static initialization to lazy initialization for bug 2756643
/** Store CR string, for some reason \n is not platform independent. */
protected static String CR = null;
/** formatting strings for indenting */
public static String SPACE = " ";
public static String INDENT = " ";
/** Store newline string */
public static String NL = "\n";
/** Prime the platform-dependent path separator */
protected static String PATH_SEPARATOR = null;
/** Prime the platform-dependent file separator */
protected static String FILE_SEPARATOR = null;
/** Prime the platform-dependent current working directory */
protected static String CURRENT_WORKING_DIRECTORY = null;
/** Prime the platform-dependent temporary directory */
protected static String TEMP_DIRECTORY = null;
/** Backdoor to allow 0 to be used in primary keys.
* @deprecated
* Instead of setting the flag to true use:
* session.getProject().setDefaultIdValidation(IdValidation.NULL)
**/
public static boolean isZeroValidPrimaryKey = false;
// settings to allow ascertaining attribute names from method names
public static final String IS_PROPERTY_METHOD_PREFIX = "is";
public static final String GET_PROPERTY_METHOD_PREFIX = "get";
public static final String SET_PROPERTY_METHOD_PREFIX = "set";
public static final String SET_IS_PROPERTY_METHOD_PREFIX = "setIs";
public static final int POSITION_AFTER_IS_PREFIX = IS_PROPERTY_METHOD_PREFIX.length();
public static final int POSITION_AFTER_GET_PREFIX = GET_PROPERTY_METHOD_PREFIX.length();
public static final String DEFAULT_DATABASE_DELIMITER = "\"";
public static final String PERSISTENCE_SET = "_persistence_set_";
public static final String PERSISTENCE_GET = "_persistence_get_";
// 323403: These constants are used to search for missing weaved functions - this is a copy is of the jpa project under ClassWeaver
public static final String PERSISTENCE_FIELDNAME_PREFIX = "_persistence_";
public static final String PERSISTENCE_FIELDNAME_POSTFIX = "_vh";
private static String defaultStartDatabaseDelimiter = null;
private static String defaultEndDatabaseDelimiter = null;
/**
* Return if JDBC date access should be optimized.
*/
public static boolean shouldOptimizeDates() {
return shouldOptimizeDates;
}
/**
* Return if JDBC date access should be optimized.
*/
public static void setShouldOptimizeDates(boolean value) {
shouldOptimizeDates = value;
}
/**
* PERF:
* Return the calendar cache use to avoid calendar creation for processing java.sql/util.Date/Time/Timestamp objects.
*/
public static Queue<Calendar> getCalendarCache() {
return calendarCache;
}
/**
* PERF:
* Init the calendar cache use to avoid calendar creation for processing java.sql/util.Date/Time/Timestamp objects.
*/
public static Queue initCalendarCache() {
Queue calendarCache = new ConcurrentLinkedQueue();
for (int index = 0; index < 10; index++) {
calendarCache.add(Calendar.getInstance());
}
return calendarCache;
}
/**
* PERF: This is used to optimize Calendar conversion/printing.
* This should only be used when a calendar is temporarily required,
* when finished it must be released back.
*/
public static Calendar allocateCalendar() {
Calendar calendar = getCalendarCache().poll();
if (calendar == null) {
calendar = Calendar.getInstance();
}
return calendar;
}
/**
* PERF: Return the cached default platform.
* Used for ensuring Calendar are in the local timezone.
* The JDK method clones the timezone, so cache it locally.
*/
public static TimeZone getDefaultTimeZone() {
return defaultTimeZone;
}
/**
* PERF: This is used to optimize Calendar conversion/printing.
* This should only be used when a calendar is temporarily required,
* when finished it must be released back.
*/
public static void releaseCalendar(Calendar calendar) {
getCalendarCache().offer(calendar);
}
public static void addAllToVector(Vector theVector, Vector elementsToAdd) {
for (Enumeration stream = elementsToAdd.elements(); stream.hasMoreElements();) {
theVector.addElement(stream.nextElement());
}
}
public static Vector addAllUniqueToVector(Vector objects, List objectsToAdd) {
if (objectsToAdd == null) {
return objects;
}
int size = objectsToAdd.size();
for (int index = 0; index < size; index++) {
Object element = objectsToAdd.get(index);
if (!objects.contains(element)) {
objects.add(element);
}
}
return objects;
}
public static List addAllUniqueToList(List objects, List objectsToAdd) {
if (objectsToAdd == null) {
return objects;
}
int size = objectsToAdd.size();
for (int index = 0; index < size; index++) {
Object element = objectsToAdd.get(index);
if (!objects.contains(element)) {
objects.add(element);
}
}
return objects;
}
/**
* Convert the specified vector into an array.
*/
public static Object[] arrayFromVector(Vector vector) {
Object[] result = new Object[vector.size()];
for (int i = 0; i < vector.size(); i++) {
result[i] = vector.elementAt(i);
}
return result;
}
/**
* Convert the HEX string to a byte array.
* HEX allows for binary data to be printed.
*/
public static byte[] buildBytesFromHexString(String hex) {
String tmpString = hex;
if ((tmpString.length() % 2) != 0) {
throw ConversionException.couldNotConvertToByteArray(hex);
}
byte[] bytes = new byte[tmpString.length() / 2];
int byteIndex;
int strIndex;
byte digit1;
byte digit2;
for (byteIndex = bytes.length - 1, strIndex = tmpString.length() - 2; byteIndex >= 0;
byteIndex--, strIndex -= 2) {
digit1 = (byte)Character.digit(tmpString.charAt(strIndex), 16);
digit2 = (byte)Character.digit(tmpString.charAt(strIndex + 1), 16);
if ((digit1 == -1) || (digit2 == -1)) {
throw ConversionException.couldNotBeConverted(hex, ClassConstants.APBYTE);
}
bytes[byteIndex] = (byte)((digit1 * 16) + digit2);
}
return bytes;
}
/**
* Convert the byte array to a HEX string.
* HEX allows for binary data to be printed.
*/
public static String buildHexStringFromBytes(byte[] bytes) {
char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
StringBuffer stringBuffer = new StringBuffer();
int tempByte;
for (int byteIndex = 0; byteIndex < (bytes).length; byteIndex++) {
tempByte = (bytes)[byteIndex];
if (tempByte < 0) {
tempByte = tempByte + 256;//compensate for the fact that byte is signed in Java
}
tempByte = (byte)(tempByte / 16);//get the first digit
if (tempByte > 16) {
throw ConversionException.couldNotBeConverted(bytes, ClassConstants.STRING);
}
stringBuffer.append(hexArray[tempByte]);
tempByte = (bytes)[byteIndex];
if (tempByte < 0) {
tempByte = tempByte + 256;
}
tempByte = (byte)(tempByte % 16);//get the second digit
if (tempByte > 16) {
throw ConversionException.couldNotBeConverted(bytes, ClassConstants.STRING);
}
stringBuffer.append(hexArray[tempByte]);
}
return stringBuffer.toString();
}
/**
* Create a new Vector containing all of the map elements.
*/
public static Vector buildVectorFromMapElements(Map map) {
Vector vector = new Vector(map.size());
Iterator iterator = map.values().iterator();
while (iterator.hasNext()) {
vector.addElement(iterator.next());
}
return vector;
}
/**
* Answer a Calendar from a date.
*/
public static Calendar calendarFromUtilDate(java.util.Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
//In jdk1.3, millisecond is missing
if (date instanceof Timestamp) {
calendar.set(Calendar.MILLISECOND, ((Timestamp)date).getNanos() / 1000000);
}
return calendar;
}
/**
* INTERNAL:
* Return whether a Class implements a specific interface, either directly or indirectly
* (through interface or implementation inheritance).
* @return boolean
*/
public static boolean classImplementsInterface(Class aClass, Class anInterface) {
// quick check
if (aClass == anInterface) {
return true;
}
Class[] interfaces = aClass.getInterfaces();
// loop through the "directly declared" interfaces
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i] == anInterface) {
return true;
}
}
// recurse through the interfaces
for (int i = 0; i < interfaces.length; i++) {
if (classImplementsInterface(interfaces[i], anInterface)) {
return true;
}
}
// finally, recurse up through the superclasses to Object
Class superClass = aClass.getSuperclass();
if (superClass == null) {
return false;
}
return classImplementsInterface(superClass, anInterface);
}
/**
* INTERNAL:
* Return whether a Class is a subclass of, or the same as, another Class.
* @return boolean
*/
public static boolean classIsSubclass(Class subClass, Class superClass) {
Class temp = subClass;
if (superClass == null) {
return false;
}
while (temp != null) {
if (temp == superClass) {
return true;
}
temp = temp.getSuperclass();
}
return false;
}
/**
* INTERNAL:
* Compares two version in num.num.num.num.num*** format.
* -1, 0, 1 means the version1 is less than, equal, greater than version2.
* Example: compareVersions("11.1.0.6.0-Production", "11.1.0.7") == -1
* Example: compareVersions("WebLogic Server 10.3.4", "10.3.3.0") == 1
*/
public static int compareVersions(String version1, String version2) {
return compareVersions(version(version1), version(version2));
}
/**
* INTERNAL:
* Expects version in ***num.num.num.num.num*** format, converts it to a List of Integers.
* Example: "11.1.0.6.0_Production" -> {11, 1, 0, 6, 0}
* Example: "WebLogic Server 10.3.3.0" -> {10, 3, 3, 0}
*/
static protected List<Integer> version(String version) {
ArrayList<Integer> list = new ArrayList<Integer>(5);
// first char - a digit - in the string corresponding to the current list index
int iBegin = -1;
// used to remove a non-digital prefix
boolean isPrefix = true;
for(int i=0; i<version.length(); i++) {
char ch = version.charAt(i);
if('0' <= ch && ch <= '9') {
isPrefix = false;
// it's a digit
if(iBegin == -1) {
iBegin = i;
}
} else {
// it's not a digit - try to create a number ending on the previous char - unless it's still part of the non-digital prefix.
if(iBegin == -1) {
if(!isPrefix) {
break;
}
} else {
isPrefix = false;
String strNum = version.substring(iBegin, i);
int num = Integer.parseInt(strNum, 10);
list.add(num);
iBegin = -1;
if(ch != '.') {
break;
}
}
}
}
if(iBegin >= 0) {
String strNum = version.substring(iBegin, version.length());
int num = Integer.parseInt(strNum, 10);
list.add(num);
}
return list;
}
/**
* INTERNAL:
* Compares two lists of Integers
* -1, 0, 1 means the first list is less than, equal, greater than the second list.
* Example: {11, 1, 0, 6, 0} < {11, 1, 0, 7}
*/
static protected int compareVersions(List<Integer> list1, List<Integer>list2) {
int n = Math.max(list1.size(), list2.size());
int res = 0;
for(int i=0; i<n; i++) {
int l1 = 0;
if(i < list1.size()) {
l1 = list1.get(i);
}
int l2 = 0;
if(i < list2.size()) {
l2 = list2.get(i);
}
if(l1 < l2) {
res =-1;
break;
} else if(l1 > l2) {
res = 1;
break;
}
}
return res;
}
public static Class getClassFromClasseName(String className, ClassLoader classLoader){
Class convertedClass = null;
if(className==null){
return null;
}
try{
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
convertedClass = (Class)AccessController.doPrivileged(new PrivilegedClassForName(className, true, classLoader));
} catch (PrivilegedActionException exception) {
throw ValidationException.classNotFoundWhileConvertingClassNames(className, exception.getException());
}
} else {
convertedClass = org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(className, true, classLoader);
}
return convertedClass;
} catch (ClassNotFoundException exc){
throw ValidationException.classNotFoundWhileConvertingClassNames(className, exc);
}
}
public static String getComponentTypeNameFromArrayString(String aString) {
if (aString == null || aString.length() == 0) {
return null;
}
// complex array component type case
if (aString.length() > 3 && (aString.startsWith("[L") & aString.endsWith(";"))) {
return aString.substring(2, aString.length() - 1);
} else if (aString.startsWith("[")){
Class primitiveClass = null;
try {
primitiveClass = Class.forName(aString);
} catch (ClassNotFoundException cnf) {
// invalid name specified - do not rethrow exception
primitiveClass = null;
}
if (primitiveClass != null) {
return primitiveClass.getComponentType().getName();
}
}
return null;
}
public static boolean compareArrays(Object[] array1, Object[] array2) {
if (array1.length != array2.length) {
return false;
}
for (int index = 0; index < array1.length; index++) {
//Related to Bug#3128838 fix. ! is added to correct the logic.
if(array1[index] != null) {
if (!array1[index].equals(array2[index])) {
return false;
}
} else {
if(array2[index] != null) {
return false;
}
}
}
return true;
}
/**
* Compare two BigDecimals.
* This is required because the .equals method of java.math.BigDecimal ensures that
* the scale of the two numbers are equal. Therefore 0.0 != 0.00.
* @see java.math.BigDecimal#equals(Object)
*/
public static boolean compareBigDecimals(java.math.BigDecimal one, java.math.BigDecimal two) {
if (one.scale() != two.scale()) {
double doubleOne = (one).doubleValue();
double doubleTwo = (two).doubleValue();
if ((doubleOne != Double.POSITIVE_INFINITY) && (doubleOne != Double.NEGATIVE_INFINITY) && (doubleTwo != Double.POSITIVE_INFINITY) && (doubleTwo != Double.NEGATIVE_INFINITY)) {
return doubleOne == doubleTwo;
}
}
return one.equals(two);
}
public static boolean compareByteArrays(byte[] array1, byte[] array2) {
if (array1.length != array2.length) {
return false;
}
for (int index = 0; index < array1.length; index++) {
if (array1[index] != array2[index]) {
return false;
}
}
return true;
}
public static boolean compareCharArrays(char[] array1, char[] array2) {
if (array1.length != array2.length) {
return false;
}
for (int index = 0; index < array1.length; index++) {
if (array1[index] != array2[index]) {
return false;
}
}
return true;
}
/**
* PUBLIC:
*
* Compare two vectors of types. Return true if the size of the vectors is the
* same and each of the types in the first Vector are assignable from the types
* in the corresponding objects in the second Vector.
*/
public static boolean areTypesAssignable(List types1, List types2) {
if ((types1 == null) || (types2 == null)) {
return false;
}
if (types1.size() == types2.size()) {
for (int i = 0; i < types1.size(); i++) {
Class type1 = (Class)types1.get(i);
Class type2 = (Class)types2.get(i);
// if either are null then we assume assignability.
if ((type1 != null) && (type2 != null)) {
if (!type1.isAssignableFrom(type2)) {
return false;
}
}
}
return true;
}
return false;
}
/**
* PUBLIC:
* Compare the elements in 2 hashtables to see if they are equal
*
* Added Nov 9, 2000 JED Patch 2.5.1.8
*/
public static boolean compareHashtables(Hashtable hashtable1, Hashtable hashtable2) {
Enumeration enumtr;
Object element;
Hashtable clonedHashtable;
if (hashtable1.size() != hashtable2.size()) {
return false;
}
clonedHashtable = (Hashtable)hashtable2.clone();
enumtr = hashtable1.elements();
while (enumtr.hasMoreElements()) {
element = enumtr.nextElement();
if (clonedHashtable.remove(element) == null) {
return false;
}
}
return clonedHashtable.isEmpty();
}
/**
* Compare two potential arrays and return true if they are the same. Will
* check for BigDecimals as well.
*/
public static boolean comparePotentialArrays(Object firstValue, Object secondValue) {
Class firstClass = firstValue.getClass();
Class secondClass = secondValue.getClass();
// Arrays must be checked for equality because default does identity
if ((firstClass == ClassConstants.APBYTE) && (secondClass == ClassConstants.APBYTE)) {
return compareByteArrays((byte[])firstValue, (byte[])secondValue);
} else if ((firstClass == ClassConstants.APCHAR) && (secondClass == ClassConstants.APCHAR)) {
return compareCharArrays((char[])firstValue, (char[])secondValue);
} else if ((firstClass.isArray()) && (secondClass.isArray())) {
return compareArrays((Object[])firstValue, (Object[])secondValue);
} else if (firstValue instanceof java.math.BigDecimal && secondValue instanceof java.math.BigDecimal) {
// BigDecimals equals does not consider the precision correctly
return compareBigDecimals((java.math.BigDecimal)firstValue, (java.math.BigDecimal)secondValue);
}
return false;
}
/**
* Merge the two Maps into a new HashMap.
*/
public static Map concatenateMaps(Map first, Map second) {
Map concatenation = new HashMap(first.size() + second.size() + 4);
for (Iterator keys = first.keySet().iterator(); keys.hasNext();) {
Object key = keys.next();
Object value = first.get(key);
concatenation.put(key, value);
}
for (Iterator keys = second.keySet().iterator(); keys.hasNext();) {
Object key = keys.next();
Object value = second.get(key);
concatenation.put(key, value);
}
return concatenation;
}
/**
* Return a new vector with no duplicated values.
*/
public static Vector concatenateUniqueVectors(Vector first, Vector second) {
Vector concatenation;
Object element;
concatenation = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
for (Enumeration stream = first.elements(); stream.hasMoreElements();) {
concatenation.addElement(stream.nextElement());
}
for (Enumeration stream = second.elements(); stream.hasMoreElements();) {
element = stream.nextElement();
if (!concatenation.contains(element)) {
concatenation.addElement(element);
}
}
return concatenation;
}
/**
* Return a new List with no duplicated values.
*/
public static List concatenateUniqueLists(List first, List second) {
List concatenation = new ArrayList(first.size() + second.size());
concatenation.addAll(first);
for (Object element : second) {
if (!concatenation.contains(element)) {
concatenation.add(element);
}
}
return concatenation;
}
public static Vector concatenateVectors(Vector first, Vector second) {
Vector concatenation;
concatenation = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
for (Enumeration stream = first.elements(); stream.hasMoreElements();) {
concatenation.addElement(stream.nextElement());
}
for (Enumeration stream = second.elements(); stream.hasMoreElements();) {
concatenation.addElement(stream.nextElement());
}
return concatenation;
}
/** Return a copy of the vector containing a subset starting at startIndex
* and ending at stopIndex.
* @param vector - original vector
* @param startIndex - starting position in vector
* @param stopIndex - ending position in vector
* @exception EclipseLinkException
*/
public static Vector copyVector(List originalVector, int startIndex, int stopIndex) throws ValidationException {
Vector newVector;
if (stopIndex < startIndex) {
return NonSynchronizedVector.newInstance();
}
newVector = NonSynchronizedVector.newInstance(stopIndex - startIndex);
for (int index = startIndex; index < stopIndex; index++) {
newVector.add(originalVector.get(index));
}
return newVector;
}
/**
* Copy an array of strings to a new array
* avoids the use of Arrays.copy() because it is not supported in JDK 1.5
* @param original
* @return
*/
public static String[] copyStringArray(String[] original){
if (original == null){
return null;
}
String[] copy = new String[original.length];
for (int i=0;i<original.length;i++){
copy[i] = original[i];
}
return copy;
}
/**
* Copy an array of int to a new array
* avoids the use of Arrays.copy() because it is not supported in JDK 1.5
* @param original
* @return
*/
public static int[] copyIntArray(int[] original){
if (original == null){
return null;
}
int[] copy = new int[original.length];
for (int i=0;i<original.length;i++){
copy[i] = original[i];
}
return copy;
}
/**
* Return a string containing the platform-appropriate
* characters for carriage return.
*/
public static String cr() {
// bug 2756643
if (CR == null) {
CR = System.getProperty("line.separator");
}
return CR;
}
/**
* Return the name of the "current working directory".
*/
public static String currentWorkingDirectory() {
// bug 2756643
if (CURRENT_WORKING_DIRECTORY == null) {
CURRENT_WORKING_DIRECTORY = System.getProperty("user.dir");
}
return CURRENT_WORKING_DIRECTORY;
}
/**
* Return the name of the "temporary directory".
*/
public static String tempDirectory() {
// Bug 2756643
if (TEMP_DIRECTORY == null) {
TEMP_DIRECTORY = System.getProperty("java.io.tmpdir");
}
return TEMP_DIRECTORY;
}
/**
* Answer a Date from a long
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.sql.Date dateFromLong(Long longObject) {
return new java.sql.Date(longObject.longValue());
}
/**
* Answer a Date with the year, month, date.
* This builds a date avoiding the deprecated, inefficient and concurrency bottleneck date constructors.
* This implementation is based on the java.sql.Date class, not java.util.Date.
* The year, month, day are the values calendar uses,
* i.e. year is from 0, month is 0-11, date is 1-31.
*/
public static java.sql.Date dateFromYearMonthDate(int year, int month, int day) {
// Use a calendar to compute the correct millis for the date.
Calendar localCalendar = allocateCalendar();
localCalendar.clear();
localCalendar.set(year, month, day, 0, 0, 0);
long millis = localCalendar.getTimeInMillis();
java.sql.Date date = new java.sql.Date(millis);
releaseCalendar(localCalendar);
return date;
}
/**
* Answer a Date from a string representation.
* The string MUST be a valid date and in one of the following
* formats: YYYY/MM/DD, YYYY-MM-DD, YY/MM/DD, YY-MM-DD.
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
*
* The Date class contains some minor gotchas that you have to watch out for.
* @param dateString - string representation of date
* @return - date representation of string
*/
public static java.sql.Date dateFromString(String dateString) throws ConversionException {
int year;
int month;
int day;
StringTokenizer dateStringTokenizer;
if (dateString.indexOf('/') != -1) {
dateStringTokenizer = new StringTokenizer(dateString, "/");
} else if (dateString.indexOf('-') != -1) {
dateStringTokenizer = new StringTokenizer(dateString, "- ");
} else {
throw ConversionException.incorrectDateFormat(dateString);
}
try {
year = Integer.parseInt(dateStringTokenizer.nextToken());
month = Integer.parseInt(dateStringTokenizer.nextToken());
day = Integer.parseInt(dateStringTokenizer.nextToken());
} catch (NumberFormatException exception) {
throw ConversionException.incorrectDateFormat(dateString);
}
// Java returns the month in terms of 0 - 11 instead of 1 - 12.
month = month - 1;
return dateFromYearMonthDate(year, month, day);
}
/**
* Answer a Date from a timestamp
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
* @param timestampObject - timestamp representation of date
* @return - date representation of timestampObject
*/
public static java.sql.Date dateFromTimestamp(java.sql.Timestamp timestamp) {
return sqlDateFromUtilDate(timestamp);
}
/**
* Returns true if the file of this name does indeed exist
*/
public static boolean doesFileExist(String fileName) {
FileReader reader = null;
try {
reader = new FileReader(fileName);
} catch (FileNotFoundException fnfException) {
return false;
} finally {
Helper.close(reader);
}
return true;
}
/**
* Double up \ to allow printing of directories for source code generation.
*/
public static String doubleSlashes(String path) {
StringBuffer buffer = new StringBuffer(path.length() + 5);
for (int index = 0; index < path.length(); index++) {
char charater = path.charAt(index);
buffer.append(charater);
if (charater == '\\') {
buffer.append('\\');
}
}
return buffer.toString();
}
/**
* Extracts the actual path to the jar file.
*/
public static String extractJarNameFromURL(java.net.URL url) {
String tempName = url.getFile();
int start = tempName.indexOf("file:") + 5;
int end = tempName.indexOf("!/");
return tempName.substring(start, end);
}
/**
* Return a string containing the platform-appropriate
* characters for separating directory and file names.
*/
public static String fileSeparator() {
//Bug 2756643
if (FILE_SEPARATOR == null) {
FILE_SEPARATOR = System.getProperty("file.separator");
}
return FILE_SEPARATOR;
}
/**
* INTERNAL:
* Returns a Field for the specified Class and field name.
* Uses Class.getDeclaredField(String) to find the field.
* If the field is not found on the specified class
* the superclass is checked, and so on, recursively.
* Set accessible to true, so we can access private/package/protected fields.
*/
public static Field getField(Class javaClass, String fieldName) throws NoSuchFieldException {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
return (Field)AccessController.doPrivileged(new PrivilegedGetField(javaClass, fieldName, true));
} catch (PrivilegedActionException exception) {
throw (NoSuchFieldException)exception.getException();
}
} else {
return PrivilegedAccessHelper.getField(javaClass, fieldName, true);
}
}
/**
* INTERNAL:
* Returns a Method for the specified Class, method name, and that has no
* parameters. Uses Class.getDeclaredMethod(String Class[]) to find the
* method. If the method is not found on the specified class the superclass
* is checked, and so on, recursively. Set accessible to true, so we can
* access private/package/protected methods.
*/
public static Method getDeclaredMethod(Class javaClass, String methodName) throws NoSuchMethodException {
return getDeclaredMethod(javaClass, methodName, (Class[]) null);
}
/**
* INTERNAL:
* Returns a Method for the specified Class, method name, and formal
* parameter types. Uses Class.getDeclaredMethod(String Class[]) to find
* the method. If the method is not found on the specified class the
* superclass is checked, and so on, recursively. Set accessible to true,
* so we can access private/package/protected methods.
*/
public static Method getDeclaredMethod(Class javaClass, String methodName, Class[] methodParameterTypes) throws NoSuchMethodException {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
return AccessController.doPrivileged(
new PrivilegedGetMethod(javaClass, methodName, methodParameterTypes, true));
}
catch (PrivilegedActionException pae){
if (pae.getCause() instanceof NoSuchMethodException){
throw (NoSuchMethodException)pae.getCause();
}
else {
// really shouldn't happen
throw (RuntimeException)pae.getCause();
}
}
} else {
return PrivilegedAccessHelper.getMethod(javaClass, methodName, methodParameterTypes, true);
}
}
/**
* Return the class instance from the class
*/
public static Object getInstanceFromClass(Class classFullName) {
if (classFullName == null) {
return null;
}
try {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
return AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(classFullName));
} catch (PrivilegedActionException exception) {
Exception throwableException = exception.getException();
if (throwableException instanceof InstantiationException) {
ValidationException exc = new ValidationException();
exc.setInternalException(throwableException);
throw exc;
} else {
ValidationException exc = new ValidationException();
exc.setInternalException(throwableException);
throw exc;
}
}
} else {
return PrivilegedAccessHelper.newInstanceFromClass(classFullName);
}
} catch (InstantiationException notInstantiatedException) {
ValidationException exception = new ValidationException();
exception.setInternalException(notInstantiatedException);
throw exception;
} catch (IllegalAccessException notAccessedException) {
ValidationException exception = new ValidationException();
exception.setInternalException(notAccessedException);
throw exception;
}
}
/**
* Returns the object class. If a class is primitive return its non primitive class
*/
public static Class getObjectClass(Class javaClass) {
return ConversionManager.getObjectClass(javaClass);
}
/**
* Answers the unqualified class name for the provided class.
*/
public static String getShortClassName(Class javaClass) {
return getShortClassName(javaClass.getName());
}
/**
* Answers the unqualified class name from the specified String.
*/
public static String getShortClassName(String javaClassName) {
return javaClassName.substring(javaClassName.lastIndexOf('.') + 1);
}
/**
* Answers the unqualified class name for the specified object.
*/
public static String getShortClassName(Object object) {
return getShortClassName(object.getClass());
}
/**
* return a package name for the specified class.
*/
public static String getPackageName(Class javaClass) {
String className = Helper.getShortClassName(javaClass);
return javaClass.getName().substring(0, (javaClass.getName().length() - (className.length() + 1)));
}
/**
* Return a string containing the specified number of tabs.
*/
public static String getTabs(int noOfTabs) {
StringWriter writer = new StringWriter();
for (int index = 0; index < noOfTabs; index++) {
writer.write("\t");
}
return writer.toString();
}
/**
* Returns the index of the the first <code>null</code> element found in the specified
* <code>Vector</code> starting the search at the starting index specified.
* Return an int >= 0 and less than size if a <code>null</code> element was found.
* Return -1 if a <code>null</code> element was not found.
* This is needed in jdk1.1, where <code>Vector.contains(Object)</code>
* for a <code>null</code> element will result in a <code>NullPointerException</code>....
*/
public static int indexOfNullElement(Vector v, int index) {
int size = v.size();
for (int i = index; i < size; i++) {
if (v.elementAt(i) == null) {
return i;
}
}
return -1;
}
/**
* ADVANCED
* returns true if the class in question is a primitive wrapper
*/
public static boolean isPrimitiveWrapper(Class classInQuestion) {
return classInQuestion.equals(Character.class) || classInQuestion.equals(Boolean.class) || classInQuestion.equals(Byte.class) || classInQuestion.equals(Short.class) || classInQuestion.equals(Integer.class) || classInQuestion.equals(Long.class) || classInQuestion.equals(Float.class) || classInQuestion.equals(Double.class);
}
/**
* Returns true if the string given is an all upper case string
*/
public static boolean isUpperCaseString(String s) {
char[] c = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
if (Character.isLowerCase(c[i])) {
return false;
}
}
return true;
}
/**
* Returns true if the character given is a vowel. I.e. one of a,e,i,o,u,A,E,I,O,U.
*/
public static boolean isVowel(char c) {
return (c == 'A') || (c == 'a') || (c == 'e') || (c == 'E') || (c == 'i') || (c == 'I') || (c == 'o') || (c == 'O') || (c == 'u') || (c == 'U');
}
/**
* Return an array of the files in the specified directory.
* This allows us to simplify jdk1.1 code a bit.
*/
public static File[] listFilesIn(File directory) {
if (directory.isDirectory()) {
return directory.listFiles();
} else {
return new File[0];
}
}
/**
* Make a Vector from the passed object.
* If it's a Collection, iterate over the collection and add each item to the Vector.
* If it's not a collection create a Vector and add the object to it.
*/
public static Vector makeVectorFromObject(Object theObject) {
if (theObject instanceof Vector) {
return ((Vector)theObject);
}
if (theObject instanceof Collection) {
Vector returnVector = new Vector(((Collection)theObject).size());
Iterator iterator = ((Collection)theObject).iterator();
while (iterator.hasNext()) {
returnVector.add(iterator.next());
}
return returnVector;
}
Vector returnVector = new Vector();
returnVector.addElement(theObject);
return returnVector;
}
/**
* Used by our byte code weaving to enable users who are debugging to output
* the generated class to a file
*
* @param className
* @param classBytes
* @param outputPath
*/
public static void outputClassFile(String className, byte[] classBytes,
String outputPath) {
StringBuffer directoryName = new StringBuffer();
StringTokenizer tokenizer = new StringTokenizer(className, "\n\\/");
String token = null;
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
directoryName.append(token + File.separator);
}
}
FileOutputStream fos = null;
try {
String usedOutputPath = outputPath;
if (!outputPath.endsWith(File.separator)) {
usedOutputPath = outputPath + File.separator;
}
File file = new File(usedOutputPath + directoryName);
file.mkdirs();
file = new File(file, token + ".class");
if (!file.exists()) {
file.createNewFile();
} else {
if (!System.getProperty(
SystemProperties.WEAVING_SHOULD_OVERWRITE, "false")
.equalsIgnoreCase("true")) {
AbstractSessionLog.getLog().log(SessionLog.WARNING,
SessionLog.WEAVER, "weaver_not_overwriting",
className);
return;
}
}
fos = new FileOutputStream(file);
fos.write(classBytes);
} catch (Exception e) {
AbstractSessionLog.getLog().log(SessionLog.WARNING,
SessionLog.WEAVER, "weaver_could_not_write", className, e);
AbstractSessionLog.getLog().logThrowable(SessionLog.FINEST,
SessionLog.WEAVER, e);
} finally {
Helper.close(fos);
}
}
/**
* Return a string containing the platform-appropriate
* characters for separating entries in a path (e.g. the classpath)
*/
public static String pathSeparator() {
// Bug 2756643
if (PATH_SEPARATOR == null) {
PATH_SEPARATOR = System.getProperty("path.separator");
}
return PATH_SEPARATOR;
}
/**
* Return a String containing the printed stacktrace of an exception.
*/
public static String printStackTraceToString(Throwable aThrowable) {
StringWriter swriter = new StringWriter();
PrintWriter writer = new PrintWriter(swriter, true);
aThrowable.printStackTrace(writer);
writer.close();
return swriter.toString();
}
/* Return a string representation of a number of milliseconds in terms of seconds, minutes, or
* milliseconds, whichever is most appropriate.
*/
public static String printTimeFromMilliseconds(long milliseconds) {
if ((milliseconds > 1000) && (milliseconds < 60000)) {
return (milliseconds / 1000) + "s";
}
if (milliseconds > 60000) {
return (milliseconds / 60000) + "min " + printTimeFromMilliseconds(milliseconds % 60000);
}
return milliseconds + "ms";
}
/**
* Given a Vector, print it, even if there is a null in it
*/
public static String printVector(Vector vector) {
StringWriter stringWriter = new StringWriter();
stringWriter.write("[");
Enumeration enumtr = vector.elements();
stringWriter.write(String.valueOf(enumtr.nextElement()));
while (enumtr.hasMoreElements()) {
stringWriter.write(" ");
stringWriter.write(String.valueOf(enumtr.nextElement()));
}
stringWriter.write("]");
return stringWriter.toString();
}
public static Hashtable rehashHashtable(Hashtable table) {
Hashtable rehashedTable = new Hashtable(table.size() + 2);
Enumeration values = table.elements();
for (Enumeration keys = table.keys(); keys.hasMoreElements();) {
Object key = keys.nextElement();
Object value = values.nextElement();
rehashedTable.put(key, value);
}
return rehashedTable;
}
public static Map rehashMap(Map table) {
HashMap rehashedTable = new HashMap(table.size() + 2);
Iterator values = table.values().iterator();
for (Iterator keys = table.keySet().iterator(); keys.hasNext();) {
Object key = keys.next();
Object value = values.next();
rehashedTable.put(key, value);
}
return rehashedTable;
}
/**
* Returns a String which has had enough non-alphanumeric characters removed to be equal to
* the maximumStringLength.
*/
public static String removeAllButAlphaNumericToFit(String s1, int maximumStringLength) {
int s1Size = s1.length();
if (s1Size <= maximumStringLength) {
return s1;
}
// Remove the necessary number of characters
StringBuffer buf = new StringBuffer();
int numberOfCharsToBeRemoved = s1.length() - maximumStringLength;
int s1Index = 0;
while ((numberOfCharsToBeRemoved > 0) && (s1Index < s1Size)) {
char currentChar = s1.charAt(s1Index);
if (Character.isLetterOrDigit(currentChar)) {
buf.append(currentChar);
} else {
numberOfCharsToBeRemoved--;
}
s1Index++;
}
// Append the rest of the character that were not parsed through.
// Is it quicker to build a substring and append that?
while (s1Index < s1Size) {
buf.append(s1.charAt(s1Index));
s1Index++;
}
//
return buf.toString();
}
/**
* Returns a String which has had enough of the specified character removed to be equal to
* the maximumStringLength.
*/
public static String removeCharacterToFit(String s1, char aChar, int maximumStringLength) {
int s1Size = s1.length();
if (s1Size <= maximumStringLength) {
return s1;
}
// Remove the necessary number of characters
StringBuffer buf = new StringBuffer();
int numberOfCharsToBeRemoved = s1.length() - maximumStringLength;
int s1Index = 0;
while ((numberOfCharsToBeRemoved > 0) && (s1Index < s1Size)) {
char currentChar = s1.charAt(s1Index);
if (currentChar == aChar) {
numberOfCharsToBeRemoved--;
} else {
buf.append(currentChar);
}
s1Index++;
}
// Append the rest of the character that were not parsed through.
// Is it quicker to build a substring and append that?
while (s1Index < s1Size) {
buf.append(s1.charAt(s1Index));
s1Index++;
}
//
return buf.toString();
}
/**
* Returns a String which has had enough of the specified character removed to be equal to
* the maximumStringLength.
*/
public static String removeVowels(String s1) {
// Remove the vowels
StringBuffer buf = new StringBuffer();
int s1Size = s1.length();
int s1Index = 0;
while (s1Index < s1Size) {
char currentChar = s1.charAt(s1Index);
if (!isVowel(currentChar)) {
buf.append(currentChar);
}
s1Index++;
}
//
return buf.toString();
}
/**
* Replaces the first subString of the source with the replacement.
*/
public static String replaceFirstSubString(String source, String subString, String replacement) {
int index = source.indexOf(subString);
if (index >= 0) {
return source.substring(0, index) + replacement + source.substring(index + subString.length());
}
return null;
}
public static Vector reverseVector(Vector theVector) {
Vector tempVector = new Vector(theVector.size());
Object currentElement;
for (int i = theVector.size() - 1; i > -1; i--) {
currentElement = theVector.elementAt(i);
tempVector.addElement(currentElement);
}
return tempVector;
}
/**
* Returns a new string with all space characters removed from the right
*
* @param originalString - timestamp representation of date
* @return - String
*/
public static String rightTrimString(String originalString) {
int len = originalString.length();
while ((len > 0) && (originalString.charAt(len - 1) <= ' ')) {
len--;
}
return originalString.substring(0, len);
}
/**
* Returns a String which is a concatenation of two string which have had enough
* vowels removed from them so that the sum of the sized of the two strings is less than
* or equal to the specified size.
*/
public static String shortenStringsByRemovingVowelsToFit(String s1, String s2, int maximumStringLength) {
int size = s1.length() + s2.length();
if (size <= maximumStringLength) {
return s1 + s2;
}
// Remove the necessary number of characters
int s1Size = s1.length();
int s2Size = s2.length();
StringBuffer buf1 = new StringBuffer();
StringBuffer buf2 = new StringBuffer();
int numberOfCharsToBeRemoved = size - maximumStringLength;
int s1Index = 0;
int s2Index = 0;
int modulo2 = 0;
// While we still want to remove characters, and not both string are done.
while ((numberOfCharsToBeRemoved > 0) && !((s1Index >= s1Size) && (s2Index >= s2Size))) {
if ((modulo2 % 2) == 0) {
// Remove from s1
if (s1Index < s1Size) {
if (isVowel(s1.charAt(s1Index))) {
numberOfCharsToBeRemoved--;
} else {
buf1.append(s1.charAt(s1Index));
}
s1Index++;
}
} else {
// Remove from s2
if (s2Index < s2Size) {
if (isVowel(s2.charAt(s2Index))) {
numberOfCharsToBeRemoved--;
} else {
buf2.append(s2.charAt(s2Index));
}
s2Index++;
}
}
modulo2++;
}
// Append the rest of the character that were not parsed through.
// Is it quicker to build a substring and append that?
while (s1Index < s1Size) {
buf1.append(s1.charAt(s1Index));
s1Index++;
}
while (s2Index < s2Size) {
buf2.append(s2.charAt(s2Index));
s2Index++;
}
//
return buf1.toString() + buf2.toString();
}
/**
* Answer a sql.Date from a timestamp.
*/
public static java.sql.Date sqlDateFromUtilDate(java.util.Date utilDate) {
// PERF: Avoid deprecated get methods, that are now very inefficient.
Calendar calendar = allocateCalendar();
calendar.setTime(utilDate);
java.sql.Date date = dateFromCalendar(calendar);
releaseCalendar(calendar);
return date;
}
/**
* Print the sql.Date.
*/
public static String printDate(java.sql.Date date) {
// PERF: Avoid deprecated get methods, that are now very inefficient and used from toString.
Calendar calendar = allocateCalendar();
calendar.setTime(date);
String string = printDate(calendar);
releaseCalendar(calendar);
return string;
}
/**
* Print the date part of the calendar.
*/
public static String printDate(Calendar calendar) {
return printDate(calendar, true);
}
/**
* Print the date part of the calendar.
* Normally the calendar must be printed in the local time, but if the timezone is printed,
* it must be printing in its timezone.
*/
public static String printDate(Calendar calendar, boolean useLocalTime) {
int year;
int month;
int day;
if (useLocalTime && (!defaultTimeZone.equals(calendar.getTimeZone()))) {
// Must convert the calendar to the local timezone if different, as dates have no timezone (always local).
Calendar localCalendar = allocateCalendar();
localCalendar.setTimeInMillis(calendar.getTimeInMillis());
year = localCalendar.get(Calendar.YEAR);
month = localCalendar.get(Calendar.MONTH) + 1;
day = localCalendar.get(Calendar.DATE);
releaseCalendar(localCalendar);
} else {
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH) + 1;
day = calendar.get(Calendar.DATE);
}
char[] buf = "2000-00-00".toCharArray();
buf[0] = Character.forDigit(year / 1000, 10);
buf[1] = Character.forDigit((year / 100) % 10, 10);
buf[2] = Character.forDigit((year / 10) % 10, 10);
buf[3] = Character.forDigit(year % 10, 10);
buf[5] = Character.forDigit(month / 10, 10);
buf[6] = Character.forDigit(month % 10, 10);
buf[8] = Character.forDigit(day / 10, 10);
buf[9] = Character.forDigit(day % 10, 10);
return new String(buf);
}
/**
* Print the sql.Time.
*/
public static String printTime(java.sql.Time time) {
// PERF: Avoid deprecated get methods, that are now very inefficient and used from toString.
Calendar calendar = allocateCalendar();
calendar.setTime(time);
String string = printTime(calendar);
releaseCalendar(calendar);
return string;
}
/**
* Print the time part of the calendar.
*/
public static String printTime(Calendar calendar) {
return printTime(calendar, true);
}
/**
* Print the time part of the calendar.
* Normally the calendar must be printed in the local time, but if the timezone is printed,
* it must be printing in its timezone.
*/
public static String printTime(Calendar calendar, boolean useLocalTime) {
int hour;
int minute;
int second;
if (useLocalTime && (!defaultTimeZone.equals(calendar.getTimeZone()))) {
// Must convert the calendar to the local timezone if different, as dates have no timezone (always local).
Calendar localCalendar = allocateCalendar();
localCalendar.setTimeInMillis(calendar.getTimeInMillis());
hour = localCalendar.get(Calendar.HOUR_OF_DAY);
minute = localCalendar.get(Calendar.MINUTE);
second = localCalendar.get(Calendar.SECOND);
releaseCalendar(localCalendar);
} else {
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
second = calendar.get(Calendar.SECOND);
}
String hourString;
String minuteString;
String secondString;
if (hour < 10) {
hourString = "0" + hour;
} else {
hourString = Integer.toString(hour);
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = Integer.toString(minute);
}
if (second < 10) {
secondString = "0" + second;
} else {
secondString = Integer.toString(second);
}
return (hourString + ":" + minuteString + ":" + secondString);
}
/**
* Print the Calendar.
*/
public static String printCalendar(Calendar calendar) {
return printCalendar(calendar, true);
}
/**
* Print the Calendar.
* Normally the calendar must be printed in the local time, but if the timezone is printed,
* it must be printing in its timezone.
*/
public static String printCalendar(Calendar calendar, boolean useLocalTime) {
String millisString;
// String zeros = "000000000";
if (calendar.get(Calendar.MILLISECOND) == 0) {
millisString = "0";
} else {
millisString = buildZeroPrefixAndTruncTrailZeros(calendar.get(Calendar.MILLISECOND), 3);
}
StringBuffer timestampBuf = new StringBuffer();
timestampBuf.append(printDate(calendar, useLocalTime));
timestampBuf.append(" ");
timestampBuf.append(printTime(calendar, useLocalTime));
timestampBuf.append(".");
timestampBuf.append(millisString);
return timestampBuf.toString();
}
/**
* Print the sql.Timestamp.
*/
public static String printTimestamp(java.sql.Timestamp timestamp) {
// PERF: Avoid deprecated get methods, that are now very inefficient and used from toString.
Calendar calendar = allocateCalendar();
calendar.setTime(timestamp);
String nanosString;
if (timestamp.getNanos() == 0) {
nanosString = "0";
} else {
nanosString = buildZeroPrefixAndTruncTrailZeros(timestamp.getNanos(), 9);
}
StringBuffer timestampBuf = new StringBuffer();
timestampBuf.append(printDate(calendar));
timestampBuf.append(" ");
timestampBuf.append(printTime(calendar));
timestampBuf.append(".");
timestampBuf.append(nanosString);
releaseCalendar(calendar);
return (timestampBuf.toString());
}
/**
* Build a numerical string with leading 0s. number is an existing number that
* the new string will be built on. totalDigits is the number of the required
* digits of the string.
*/
public static String buildZeroPrefix(int number, int totalDigits) {
String numbString = buildZeroPrefixWithoutSign(number, totalDigits);
if (number < 0) {
numbString = "-" + numbString;
} else {
numbString = "+" + numbString;
}
return numbString;
}
/**
* Build a numerical string with leading 0s. number is an existing number that
* the new string will be built on. totalDigits is the number of the required
* digits of the string.
*/
public static String buildZeroPrefixWithoutSign(int number, int totalDigits) {
String zeros = "000000000";
int absValue = (number < 0) ? (-number) : number;
String numbString = Integer.toString(absValue);
// Add leading zeros
numbString = zeros.substring(0, (totalDigits - numbString.length())) + numbString;
return numbString;
}
/**
* Build a numerical string with leading 0s and truncate trailing zeros. number is
* an existing number that the new string will be built on. totalDigits is the number
* of the required digits of the string.
*/
public static String buildZeroPrefixAndTruncTrailZeros(int number, int totalDigits) {
String zeros = "000000000";
String numbString = Integer.toString(number);
// Add leading zeros
numbString = zeros.substring(0, (totalDigits - numbString.length())) + numbString;
// Truncate trailing zeros
char[] numbChar = new char[numbString.length()];
numbString.getChars(0, numbString.length(), numbChar, 0);
int truncIndex = totalDigits - 1;
while (numbChar[truncIndex] == '0') {
truncIndex--;
}
return new String(numbChar, 0, truncIndex + 1);
}
/**
* Print the sql.Timestamp without the nanos portion.
*/
public static String printTimestampWithoutNanos(java.sql.Timestamp timestamp) {
// PERF: Avoid deprecated get methods, that are now very inefficient and used from toString.
Calendar calendar = allocateCalendar();
calendar.setTime(timestamp);
String string = printCalendarWithoutNanos(calendar);
releaseCalendar(calendar);
return string;
}
/**
* Print the Calendar without the nanos portion.
*/
public static String printCalendarWithoutNanos(Calendar calendar) {
StringBuffer timestampBuf = new StringBuffer();
timestampBuf.append(printDate(calendar));
timestampBuf.append(" ");
timestampBuf.append(printTime(calendar));
return timestampBuf.toString();
}
/**
* Answer a sql.Date from a Calendar.
*/
public static java.sql.Date dateFromCalendar(Calendar calendar) {
if (!defaultTimeZone.equals(calendar.getTimeZone())) {
// Must convert the calendar to the local timezone if different, as dates have no timezone (always local).
Calendar localCalendar = allocateCalendar();
localCalendar.setTimeInMillis(calendar.getTimeInMillis());
java.sql.Date date = dateFromYearMonthDate(localCalendar.get(Calendar.YEAR), localCalendar.get(Calendar.MONTH), localCalendar.get(Calendar.DATE));
releaseCalendar(localCalendar);
return date;
} else if ((calendar.get(Calendar.HOUR_OF_DAY) == 0)
&& (calendar.get(Calendar.MINUTE) == 0)
&& (calendar.get(Calendar.SECOND) == 0)
&& (calendar.get(Calendar.MILLISECOND) == 0)) {
// PERF: If just a date set in the Calendar, then just use its millis.
return new java.sql.Date(calendar.getTimeInMillis());
}
return dateFromYearMonthDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
}
/**
* Return a sql.Date with time component zeroed out.
* Starting with version 12.1 Oracle jdbc Statement.setDate method no longer zeroes out the time component.
*/
public static java.sql.Date truncateDate(java.sql.Date date) {
// PERF: Avoid deprecated get methods, that are now very inefficient.
Calendar calendar = allocateCalendar();
calendar.setTime(date);
if ((calendar.get(Calendar.HOUR_OF_DAY) != 0)
|| (calendar.get(Calendar.MINUTE) != 0)
|| (calendar.get(Calendar.SECOND) != 0)
|| (calendar.get(Calendar.MILLISECOND) != 0)) {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.clear();
calendar.set(year, month, day, 0, 0, 0);
long millis = calendar.getTimeInMillis();
date = new java.sql.Date(millis);
}
releaseCalendar(calendar);
return date;
}
/**
* Return a sql.Date with time component zeroed out (with possible exception of milliseconds).
* Starting with version 12.1 Oracle jdbc Statement.setDate method no longer zeroes out the whole time component,
* yet it still zeroes out milliseconds.
*/
public static java.sql.Date truncateDateIgnoreMilliseconds(java.sql.Date date) {
// PERF: Avoid deprecated get methods, that are now very inefficient.
Calendar calendar = allocateCalendar();
calendar.setTime(date);
if ((calendar.get(Calendar.HOUR_OF_DAY) != 0)
|| (calendar.get(Calendar.MINUTE) != 0)
|| (calendar.get(Calendar.SECOND) != 0)) {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.clear();
calendar.set(year, month, day, 0, 0, 0);
long millis = calendar.getTimeInMillis();
date = new java.sql.Date(millis);
}
releaseCalendar(calendar);
return date;
}
/**
* Can be used to mark code if a workaround is added for a JDBC driver or other bug.
*/
public static void systemBug(String description) {
// Use sender to find what is needy.
}
/**
* Answer a Time from a Date
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
* @param timestampObject - time representation of date
* @return - time representation of dateObject
*/
public static java.sql.Time timeFromDate(java.util.Date date) {
// PERF: Avoid deprecated get methods, that are now very inefficient.
Calendar calendar = allocateCalendar();
calendar.setTime(date);
java.sql.Time time = timeFromCalendar(calendar);
releaseCalendar(calendar);
return time;
}
/**
* Answer a Time from a long
*
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.sql.Time timeFromLong(Long longObject) {
return new java.sql.Time(longObject.longValue());
}
/**
* Answer a Time with the hour, minute, second.
* This builds a time avoiding the deprecated, inefficient and concurrency bottleneck date constructors.
* The hour, minute, second are the values calendar uses,
* i.e. year is from 0, month is 0-11, date is 1-31.
*/
public static java.sql.Time timeFromHourMinuteSecond(int hour, int minute, int second) {
// Use a calendar to compute the correct millis for the date.
Calendar localCalendar = allocateCalendar();
localCalendar.clear();
localCalendar.set(1970, 0, 1, hour, minute, second);
long millis = localCalendar.getTimeInMillis();
java.sql.Time time = new java.sql.Time(millis);
releaseCalendar(localCalendar);
return time;
}
/**
* Answer a Time from a string representation.
* This method will accept times in the following
* formats: HH-MM-SS, HH:MM:SS
*
* @param timeString - string representation of time
* @return - time representation of string
*/
public static java.sql.Time timeFromString(String timeString) throws ConversionException {
int hour;
int minute;
int second;
String timePortion = timeString;
if (timeString.length() > 12) {
// Longer strings are Timestamp format (ie. Sybase & Oracle)
timePortion = timeString.substring(11, 19);
}
if ((timePortion.indexOf('-') == -1) && (timePortion.indexOf('/') == -1) && (timePortion.indexOf('.') == -1) && (timePortion.indexOf(':') == -1)) {
throw ConversionException.incorrectTimeFormat(timePortion);
}
StringTokenizer timeStringTokenizer = new StringTokenizer(timePortion, " /:.-");
try {
hour = Integer.parseInt(timeStringTokenizer.nextToken());
minute = Integer.parseInt(timeStringTokenizer.nextToken());
second = Integer.parseInt(timeStringTokenizer.nextToken());
} catch (NumberFormatException exception) {
throw ConversionException.incorrectTimeFormat(timeString);
}
return timeFromHourMinuteSecond(hour, minute, second);
}
/**
* Answer a Time from a Timestamp
* Usus the Hours, Minutes, Seconds instead of getTime() ms value.
*/
public static java.sql.Time timeFromTimestamp(java.sql.Timestamp timestamp) {
return timeFromDate(timestamp);
}
/**
* Answer a sql.Time from a Calendar.
*/
public static java.sql.Time timeFromCalendar(Calendar calendar) {
if (!defaultTimeZone.equals(calendar.getTimeZone())) {
// Must convert the calendar to the local timezone if different, as dates have no timezone (always local).
Calendar localCalendar = allocateCalendar();
localCalendar.setTimeInMillis(calendar.getTimeInMillis());
java.sql.Time date = timeFromHourMinuteSecond(localCalendar.get(Calendar.HOUR_OF_DAY), localCalendar.get(Calendar.MINUTE), localCalendar.get(Calendar.SECOND));
releaseCalendar(localCalendar);
return date;
}
return timeFromHourMinuteSecond(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
}
/**
* Answer a Timestamp from a Calendar.
*/
public static java.sql.Timestamp timestampFromCalendar(Calendar calendar) {
return timestampFromLong(calendar.getTimeInMillis());
}
/**
* Answer a Timestamp from a java.util.Date.
*/
public static java.sql.Timestamp timestampFromDate(java.util.Date date) {
return timestampFromLong(date.getTime());
}
/**
* Answer a Time from a long
*
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.sql.Timestamp timestampFromLong(Long millis) {
return timestampFromLong(millis.longValue());
}
/**
* Answer a Time from a long
*
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.sql.Timestamp timestampFromLong(long millis) {
java.sql.Timestamp timestamp = new java.sql.Timestamp(millis);
// P2.0.1.3: Didn't account for negative millis < 1970
// Must account for the jdk millis bug where it does not set the nanos.
if ((millis % 1000) > 0) {
timestamp.setNanos((int)(millis % 1000) * 1000000);
} else if ((millis % 1000) < 0) {
timestamp.setNanos((int)(1000000000 - (Math.abs((millis % 1000) * 1000000))));
}
return timestamp;
}
/**
* Answer a Timestamp from a string representation.
* This method will accept strings in the following
* formats: YYYY/MM/DD HH:MM:SS, YY/MM/DD HH:MM:SS, YYYY-MM-DD HH:MM:SS, YY-MM-DD HH:MM:SS
*
* @param timestampString - string representation of timestamp
* @return - timestamp representation of string
*/
@SuppressWarnings("deprecation")
public static java.sql.Timestamp timestampFromString(String timestampString) throws ConversionException {
if ((timestampString.indexOf('-') == -1) && (timestampString.indexOf('/') == -1) && (timestampString.indexOf('.') == -1) && (timestampString.indexOf(':') == -1)) {
throw ConversionException.incorrectTimestampFormat(timestampString);
}
StringTokenizer timestampStringTokenizer = new StringTokenizer(timestampString, " /:.-");
int year;
int month;
int day;
int hour;
int minute;
int second;
int nanos;
try {
year = Integer.parseInt(timestampStringTokenizer.nextToken());
month = Integer.parseInt(timestampStringTokenizer.nextToken());
day = Integer.parseInt(timestampStringTokenizer.nextToken());
try {
hour = Integer.parseInt(timestampStringTokenizer.nextToken());
minute = Integer.parseInt(timestampStringTokenizer.nextToken());
second = Integer.parseInt(timestampStringTokenizer.nextToken());
} catch (java.util.NoSuchElementException endOfStringException) {
// May be only a date string desired to be used as a timestamp.
hour = 0;
minute = 0;
second = 0;
}
} catch (NumberFormatException exception) {
throw ConversionException.incorrectTimestampFormat(timestampString);
}
try {
String nanoToken = timestampStringTokenizer.nextToken();
nanos = Integer.parseInt(nanoToken);
for (int times = 0; times < (9 - nanoToken.length()); times++) {
nanos = nanos * 10;
}
} catch (java.util.NoSuchElementException endOfStringException) {
nanos = 0;
} catch (NumberFormatException exception) {
throw ConversionException.incorrectTimestampFormat(timestampString);
}
// Java dates are based on year after 1900 so I need to delete it.
year = year - 1900;
// Java returns the month in terms of 0 - 11 instead of 1 - 12.
month = month - 1;
java.sql.Timestamp timestamp;
// TODO: This was not converted to use Calendar for the conversion because calendars do not take nanos.
// but it should be, and then just call setNanos.
timestamp = new java.sql.Timestamp(year, month, day, hour, minute, second, nanos);
return timestamp;
}
/**
* Answer a Timestamp with the year, month, day, hour, minute, second.
* The hour, minute, second are the values calendar uses,
* i.e. year is from 0, month is 0-11, date is 1-31, time is 0-23/59.
*/
@SuppressWarnings("deprecation")
public static java.sql.Timestamp timestampFromYearMonthDateHourMinuteSecondNanos(int year, int month, int date, int hour, int minute, int second, int nanos) {
// This was not converted to use Calendar for the conversion because calendars do not take nanos.
// but it should be, and then just call setNanos.
return new java.sql.Timestamp(year - 1900, month, date, hour, minute, second, nanos);
}
/**
* Can be used to mark code as need if something strange is seen.
*/
public static void toDo(String description) {
// Use sender to find what is needy.
}
/**
* Convert dotted format class name to slashed format class name.
* @param dottedClassName
* @return String
*/
public static String toSlashedClassName(String dottedClassName){
if(dottedClassName==null){
return null;
}else if(dottedClassName.indexOf('.')>=0){
return dottedClassName.replace('.', '/');
}else{
return dottedClassName;
}
}
/**
* If the size of the original string is larger than the passed in size,
* this method will remove the vowels from the original string.
*
* The removal starts backward from the end of original string, and stops if the
* resulting string size is equal to the passed in size.
*
* If the resulting string is still larger than the passed in size after
* removing all vowels, the end of the resulting string will be truncated.
*/
public static String truncate(String originalString, int size) {
if (originalString.length() <= size) {
//no removal and truncation needed
return originalString;
}
String vowels = "AaEeIiOoUu";
StringBuffer newStringBufferTmp = new StringBuffer(originalString.length());
//need to remove the extra characters
int counter = originalString.length() - size;
for (int index = (originalString.length() - 1); index >= 0; index--) {
//search from the back to the front, if vowel found, do not append it to the resulting (temp) string!
//i.e. if vowel not found, append the chararcter to the new string buffer.
if (vowels.indexOf(originalString.charAt(index)) == -1) {
newStringBufferTmp.append(originalString.charAt(index));
} else {
//vowel found! do NOT append it to the temp buffer, and decrease the counter
counter--;
if (counter == 0) {
//if the exceeded characters (counter) of vowel haven been removed, the total
//string size should be equal to the limits, so append the reversed remaining string
//to the new string, break the loop and return the shrunk string.
StringBuffer newStringBuffer = new StringBuffer(size);
newStringBuffer.append(originalString.substring(0, index));
//need to reverse the string
//bug fix: 3016423. append(BunfferString) is jdk1.4 version api. Use append(String) instead
//in order to support jdk1.3.
newStringBuffer.append(newStringBufferTmp.reverse().toString());
return newStringBuffer.toString();
}
}
}
//the shrunk string still too long, revrese the order back and truncate it!
return newStringBufferTmp.reverse().toString().substring(0, size);
}
/**
* Answer a Date from a long
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.util.Date utilDateFromLong(Long longObject) {
return new java.util.Date(longObject.longValue());
}
/**
* Answer a java.util.Date from a sql.date
*
* @param sqlDate - sql.date representation of date
* @return - java.util.Date representation of the sql.date
*/
public static java.util.Date utilDateFromSQLDate(java.sql.Date sqlDate) {
return new java.util.Date(sqlDate.getTime());
}
/**
* Answer a java.util.Date from a sql.Time
*
* @param time - time representation of util date
* @return - java.util.Date representation of the time
*/
public static java.util.Date utilDateFromTime(java.sql.Time time) {
return new java.util.Date(time.getTime());
}
/**
* Answer a java.util.Date from a timestamp
*
* @param timestampObject - timestamp representation of date
* @return - java.util.Date representation of timestampObject
*/
public static java.util.Date utilDateFromTimestamp(java.sql.Timestamp timestampObject) {
// Bug 2719624 - Conditionally remove workaround for java bug which truncated
// nanoseconds from timestamp.getTime(). We will now only recalculate the nanoseconds
// When timestamp.getTime() results in nanoseconds == 0;
long time = timestampObject.getTime();
boolean appendNanos = ((time % 1000) == 0);
if (appendNanos) {
return new java.util.Date(time + (timestampObject.getNanos() / 1000000));
} else {
return new java.util.Date(time);
}
}
/**
* Convert the specified array into a vector.
*/
public static Vector vectorFromArray(Object[] array) {
Vector result = new Vector(array.length);
for (int i = 0; i < array.length; i++) {
result.addElement(array[i]);
}
return result;
}
/**
* Convert the byte array to a HEX string.
* HEX allows for binary data to be printed.
*/
public static void writeHexString(byte[] bytes, Writer writer) throws IOException {
writer.write(buildHexStringFromBytes(bytes));
}
/**
* Check if the value is 0 (int/long) for primitive ids.
*/
public static boolean isEquivalentToNull(Object value) {
return (!isZeroValidPrimaryKey
&& (((value.getClass() == ClassConstants.LONG) && (((Long)value).longValue() == 0L))
|| ((value.getClass() == ClassConstants.INTEGER) && (((Integer)value).intValue() == 0))));
}
/**
* Returns true if the passed value is Number that is negative or equals to zero.
*/
public static boolean isNumberNegativeOrZero(Object value) {
return ((value.getClass() == ClassConstants.BIGDECIMAL) && (((BigDecimal)value).signum() <= 0)) ||
((value.getClass() == ClassConstants.BIGINTEGER) && (((BigInteger)value).signum() <= 0)) ||
((value instanceof Number) && (((Number)value).longValue() <= 0));
}
/**
* Return an integer representing the number of occurrences (using equals()) of the
* specified object in the specified list.
* If the list is null or empty (or both the object and the list is null), 0 is returned.
*/
public static int countOccurrencesOf(Object comparisonObject, List list) {
int instances = 0;
boolean comparisonObjectIsNull = comparisonObject == null;
if (list != null) {
for (int i = 0; i < list.size(); i++) {
Object listObject = list.get(i);
if ((comparisonObjectIsNull & listObject == null) || (!comparisonObjectIsNull && comparisonObject.equals(listObject))) {
instances++;
}
}
}
return instances;
}
/**
* Convert the URL into a URI allowing for special chars.
*/
public static URI toURI(java.net.URL url) throws URISyntaxException {
try {
// Attempt to use url.toURI since it will deal with all urls
// without special characters and URISyntaxException allows us
// to catch issues with special characters. This will handle
// URLs that already have special characters replaced such as
// URLS derived from searches for persistence.xml on the Java
// System class loader
return url.toURI();
} catch (URISyntaxException exception) {
// Use multi-argument constructor for URI since single-argument
// constructor and URL.toURI() do not deal with special
// characters in path
return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), null);
}
}
/**
* Return the get method name weaved for a value-holder attribute.
*/
public static String getWeavedValueHolderGetMethodName(String attributeName) {
return PERSISTENCE_GET + attributeName + "_vh";
}
/**
* Return the set method name weaved for a value-holder attribute.
*/
public static String getWeavedValueHolderSetMethodName(String attributeName) {
return PERSISTENCE_SET + attributeName + "_vh";
}
/**
* Return the set method name weaved for getting attribute value.
* This method is always weaved in field access case.
* In property access case the method weaved only if attribute name is the same as property name:
* for instance, the method weaved for "manager" attribute that uses "getManager" / "setManager" access methods,
* but not for "m_address" attribute that uses "getAddress" / "setAddress" access methods.
*/
public static String getWeavedGetMethodName(String attributeName) {
return PERSISTENCE_GET + attributeName;
}
/**
* Return the set method name weaved for setting attribute value.
* This method is always weaved in field access case.
* In property access case the method weaved only if attribute name is the same as property name:
* for instance, the method weaved for "manager" attribute that uses "getManager" / "setManager" access methods,
* but not for "m_address" attribute that uses "getAddress" / "setAddress" access methods.
*/
public static String getWeavedSetMethodName(String attributeName) {
return PERSISTENCE_SET + attributeName;
}
/**
* Close a closeable object, eating the exception
*/
public static void close(Closeable c) {
try {
if (c != null) {
c.close();
}
} catch (IOException exception) {
}
}
/**
* INTERNAL:
* Method to convert a getXyz or isXyz method name to an xyz attribute name.
* NOTE: The method name passed it may not actually be a method name, so
* by default return the name passed in.
*/
public static String getAttributeNameFromMethodName(String methodName) {
String restOfName = methodName;
// We're looking at method named 'get' or 'set', therefore,
// there is no attribute name, set it to "" string for now.
if (methodName.equals(GET_PROPERTY_METHOD_PREFIX) || methodName.equals(IS_PROPERTY_METHOD_PREFIX)) {
return "";
} else if (methodName.startsWith(GET_PROPERTY_METHOD_PREFIX)) {
restOfName = methodName.substring(POSITION_AFTER_GET_PREFIX);
} else if (methodName.startsWith(IS_PROPERTY_METHOD_PREFIX)){
restOfName = methodName.substring(POSITION_AFTER_IS_PREFIX);
}
//added for bug 234222 - property name generation differs from Introspector.decapitalize
return java.beans.Introspector.decapitalize(restOfName);
}
public static String getDefaultStartDatabaseDelimiter(){
if (defaultStartDatabaseDelimiter == null){
defaultStartDatabaseDelimiter = DEFAULT_DATABASE_DELIMITER;
}
return defaultStartDatabaseDelimiter;
}
public static String getDefaultEndDatabaseDelimiter(){
if (defaultEndDatabaseDelimiter == null){
defaultEndDatabaseDelimiter = DEFAULT_DATABASE_DELIMITER;
}
return defaultEndDatabaseDelimiter;
}
public static void setDefaultStartDatabaseDelimiter(String delimiter){
defaultStartDatabaseDelimiter = delimiter;
}
public static void setDefaultEndDatabaseDelimiter(String delimiter){
defaultEndDatabaseDelimiter = delimiter;
}
/**
* Convert the SQL like pattern to a regex pattern.
*/
public static String convertLikeToRegex(String like) {
// Bug 3936427 - Replace regular expression reserved characters with escaped version of those characters
// For instance replace ? with \?
String pattern = like.replaceAll("\\?", "\\\\?");
pattern = pattern.replaceAll("\\*", "\\\\*");
pattern = pattern.replaceAll("\\.", "\\\\.");
pattern = pattern.replaceAll("\\[", "\\\\[");
pattern = pattern.replaceAll("\\)", "\\\\)");
pattern = pattern.replaceAll("\\(", "\\\\(");
pattern = pattern.replaceAll("\\{", "\\\\{");
pattern = pattern.replaceAll("\\+", "\\\\+");
pattern = pattern.replaceAll("\\^", "\\\\^");
pattern = pattern.replaceAll("\\|", "\\\\|");
// regular expressions to substitute SQL wildcards with regex wildcards
// Use look behind operators to replace "%" which is not preceded by "\" with ".*"
pattern = pattern.replaceAll("(?<!\\\\)%", ".*");
// Use look behind operators to replace "_" which is not preceded by "\" with "."
pattern = pattern.replaceAll("(?<!\\\\)_", ".");
// replace "\%" with "%"
pattern = pattern.replaceAll("\\\\%", "%");
// replace "\_" with "_"
pattern = pattern.replaceAll("\\\\_", "_");
// regex requires ^ and $ if pattern must start at start and end at end of string as like requires.
pattern = "^" + pattern + "$";
return pattern;
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/page/core/com.odcgroup.page.model/src/main/java/com/odcgroup/page/model/widgets/matrix/impl/MatrixFactory.java | 5946 | package com.odcgroup.page.model.widgets.matrix.impl;
import com.odcgroup.page.metamodel.MetaModel;
import com.odcgroup.page.metamodel.WidgetLibrary;
import com.odcgroup.page.metamodel.WidgetTemplate;
import com.odcgroup.page.metamodel.util.MetaModelRegistry;
import com.odcgroup.page.model.Widget;
import com.odcgroup.page.model.util.WidgetFactory;
import com.odcgroup.page.model.widgets.matrix.IMatrix;
import com.odcgroup.page.model.widgets.matrix.IMatrixAxis;
import com.odcgroup.page.model.widgets.matrix.IMatrixCell;
import com.odcgroup.page.model.widgets.matrix.IMatrixCellItem;
import com.odcgroup.page.model.widgets.matrix.IMatrixContentCell;
import com.odcgroup.page.model.widgets.matrix.IMatrixContentCellItem;
import com.odcgroup.page.model.widgets.matrix.IMatrixExtra;
import com.odcgroup.page.model.widgets.matrix.IMatrixExtraColumn;
import com.odcgroup.page.model.widgets.matrix.IMatrixExtraColumnItem;
import com.odcgroup.page.model.widgets.matrix.IMatrixFactory;
/**
*
* @author pkk
*
*/
public class MatrixFactory implements IMatrixFactory {
private static final String WIDGETTYPE_MATRIX = "Matrix";
private static final String WIDGETTYPE_MATRIXAXIS = "MatrixAxis";
private static final String WIDGETTYPE_MATRIXCELL = "MatrixCell";
private static final String WIDGETTYPE_MATRIXCONTENTCELL = "MatrixContentCell";
private static final String WIDGETTYPE_MATRIXCONTENTCELLITEM = "MatrixContentCellItem";
private static final String WIDGETTYPE_MATRIXCELLITEM = "MatrixCellItem";
private static final String WIDGETTYPE_MATRIXEXTRACOLUMN = "MatrixExtraColumn";
private static final String WIDGETTYPE_MATRIXEXTRACOLUMNITEM = "MatrixExtraColumnItem";
private static final String MATRIX_EXTRA_TEMPLATE = "MatrixExtra";
/** name of the xgui library */
private static final String XGUI_LIBRARY = "xgui";
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixWidget(com.odcgroup.page.model.Widget)
*/
public IMatrix adaptMatrixWidget(Widget widget) {
if (!WIDGETTYPE_MATRIX.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a Matrix widget");
}
return new Matrix(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixAxisWidget(com.odcgroup.page.model.Widget)
*/
public IMatrixAxis adaptMatrixAxisWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXAXIS.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixAxis widget");
}
return new MatrixAxis(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixCellWidget(com.odcgroup.page.model.Widget)
*/
public IMatrixCell adaptMatrixCellWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXCELL.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixCell widget");
}
return new MatrixCell(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixContentCellWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixContentCell adaptMatrixContentCellWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXCONTENTCELL.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixContentCell widget");
}
return new MatrixContentCell(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixCellItemWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixCellItem adaptMatrixCellItemWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXCELLITEM.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixCellItem widget");
}
return new MatrixCellItem(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixContentCellItemWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixContentCellItem adaptMatrixContentCellItemWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXCONTENTCELLITEM.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixContentCellItem widget");
}
return new MatrixContentCellItem(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adapatMatrixExtraColumnItemWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixExtraColumnItem adapatMatrixExtraColumnItemWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXEXTRACOLUMNITEM.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixExtraColumnItem widget");
}
return new MatrixExtraColumnItem(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adapatMatrixExtraColumnWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixExtraColumn adapatMatrixExtraColumnWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXEXTRACOLUMN.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixExtraColumn widget");
}
return new MatrixExtraColumn(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#createTableExtra()
*/
@Override
public IMatrixExtra createTableExtra() {
Widget widget = createWidget(MATRIX_EXTRA_TEMPLATE);
return new MatrixExtra(widget);
}
/**
* Create a new Widget instance given its template name
* @param TemplateName the name of the widget template
* @return Widget
*/
protected Widget createWidget(String TemplateName) {
MetaModel metamodel = MetaModelRegistry.getMetaModel();
WidgetLibrary library = metamodel.findWidgetLibrary(XGUI_LIBRARY);
WidgetTemplate template = library.findWidgetTemplate(TemplateName);
WidgetFactory factory = new WidgetFactory();
Widget widget = factory.create(template);
return widget;
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/t24/ui/com.odcgroup.t24.enquiry.editor/src/main/java/com/odcgroup/t24/enquiry/editor/part/SelectionCriteriaEditPart.java | 1040 | package com.odcgroup.t24.enquiry.editor.part;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPolicy;
import com.google.common.base.Joiner;
import com.odcgroup.t24.enquiry.editor.policy.EnquiryEditorComponentEditPolicy;
import com.odcgroup.t24.enquiry.enquiry.SelectionCriteria;
import com.odcgroup.t24.enquiry.figure.SelectionCriteriaFigure;
/**
*
* @author phanikumark
*
*/
public class SelectionCriteriaEditPart extends AbstractEnquiryEditPart {
@Override
protected IFigure createFigure() {
return new SelectionCriteriaFigure();
}
@Override
protected void createEditPolicies() {
installEditPolicy(EditPolicy.COMPONENT_ROLE, new EnquiryEditorComponentEditPolicy());
}
@Override
protected void refreshVisuals() {
SelectionCriteriaFigure figure = (SelectionCriteriaFigure) getFigure();
SelectionCriteria model = (SelectionCriteria) getModel();
final String labelText = Joiner.on(" ").join(model.getField(), model.getOperand(), model.getValues());
figure.getFieldLabel().setText(labelText);
}
}
| epl-1.0 |
WtfJoke/codemodify | de.simonscholz.codemodify/src/de/simonscholz/junit4converter/converters/StandardModuleTestCaseConverter.java | 2841 | package de.simonscholz.junit4converter.converters;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
import de.simonscholz.junit4converter.JUnit4Converter;
public class StandardModuleTestCaseConverter extends JUnit4Converter implements
Converter {
private static final String MODULETESTCASE_CLASSNAME = "StandardModulTestCase";
private static final String MODULETESTCASE_QUALIFIEDNAME = "CH.obj.Application.Global.Servicelib.StandardModulTestCase";
private static final String MODULETEST_CLASSNAME = "StandardModulTest";
private static final String MODULETEST_QUALIFIEDNAME = "CH.obj.Application.Global.Servicelib.StandardModulTest";
private static final String BEFORE_METHOD = "checkPreconditions";
private final AST ast;
private final ASTRewrite rewriter;
private final ImportRewrite importRewriter;
private boolean wasModified;
private TestConversionHelper helper;
StandardModuleTestCaseConverter(AST ast, ASTRewrite rewriter,
ImportRewrite importRewriter) {
this.ast = ast;
this.rewriter = rewriter;
this.importRewriter = importRewriter;
this.helper = new TestConversionHelper(rewriter, importRewriter);
}
@Override
public boolean isConvertable(TypeDeclaration typeDeclaration) {
return helper.isTestCase(MODULETESTCASE_CLASSNAME, typeDeclaration);
}
@Override
public void convert(TypeDeclaration typeDeclaration) {
wasModified = true;
replaceSuperClass(typeDeclaration.getSuperclassType());
convertCheckPreConditionsIntoBefore(typeDeclaration.getMethods());
}
private void convertCheckPreConditionsIntoBefore(
MethodDeclaration... methods) {
for (MethodDeclaration method : methods) {
String methodName = method.getName().getFullyQualifiedName();
if (methodName.equals(BEFORE_METHOD)) {
removeAnnotation(rewriter, method, OVERRIDE_ANNOTATION_NAME);
createMarkerAnnotation(ast, rewriter, method,
BEFORE_ANNOTATION_NAME);
convertProtectedToPublic(ast, rewriter, method);
importRewriter.addImport(BEFORE_ANNOTATION_QUALIFIED_NAME);
}
}
}
private void replaceSuperClass(Type superclassType) {
SimpleType newNoDBTestRulesProviderSuperType = ast.newSimpleType(ast
.newSimpleName(MODULETEST_CLASSNAME));
rewriter.replace(superclassType, newNoDBTestRulesProviderSuperType,
null);
importRewriter.removeImport(MODULETESTCASE_QUALIFIEDNAME);
importRewriter.addImport(MODULETEST_QUALIFIEDNAME);
wasModified = true;
}
@Override
public boolean wasConverted() {
return wasModified;
}
}
| epl-1.0 |
KayErikMuench/reqiftools | reqifcompiler/src/main/java/de/kay_muench/reqif10/reqifcompiler/types/complex/EnumeratedAttributeValue.java | 1520 | /**
* Copyright (c) 2014 Kay Erik Münch.
* 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.spdx.org/licenses/EPL-1.0
*
* Contributors:
* Kay Erik Münch - initial API and implementation
*
*/
package de.kay_muench.reqif10.reqifcompiler.types.complex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.common.util.EList;
import org.eclipse.rmf.reqif10.AttributeDefinitionEnumeration;
import org.eclipse.rmf.reqif10.AttributeValueEnumeration;
import org.eclipse.rmf.reqif10.EnumValue;
import org.eclipse.rmf.reqif10.ReqIF10Factory;
public class EnumeratedAttributeValue {
private AttributeValueEnumeration value;
public EnumeratedAttributeValue(AttributeDefinitionEnumeration def) {
value = ReqIF10Factory.eINSTANCE.createAttributeValueEnumeration();
value.setDefinition(def);
}
public AttributeValueEnumeration getValue() {
return value;
}
public void setValue(int v) {
List<EnumValue> newValues = new ArrayList<EnumValue>();
final EList<EnumValue> enumValues = value.getDefinition().getType()
.getSpecifiedValues();
for (EnumValue enumValue : enumValues) {
if (enumValue.getProperties().getKey()
.equals(BigInteger.valueOf(v))) {
newValues.add(enumValue);
break;
}
}
value.getValues().clear();
value.getValues().addAll(newValues);
}
} | epl-1.0 |
opendaylight/controller | opendaylight/md-sal/samples/clustering-test-app/karaf-cli/src/main/java/org/opendaylight/clustering/it/karaf/cli/odl/mdsal/lowlevel/control/IsClientAbortedCommand.java | 1563 | /*
* Copyright (c) 2021 PANTHEON.tech, s.r.o. 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.opendaylight.clustering.it.karaf.cli.odl.mdsal.lowlevel.control;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.IsClientAbortedInputBuilder;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Service
@Command(scope = "test-app", name = "is-client-aborted", description = "Run an is-client-aborted test")
public class IsClientAbortedCommand extends AbstractRpcAction {
@Reference
private RpcConsumerRegistry rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
.isClientAborted(new IsClientAbortedInputBuilder().build());
}
}
| epl-1.0 |
Tasktop/code2cloud.server | com.tasktop.c2c.server/com.tasktop.c2c.server.developer.support/src/main/java/com/tasktop/c2c/server/developer/support/LocalServicesWebRunner.java | 2350 | /*******************************************************************************
* Copyright (c) 2010, 2012 Tasktop Technologies
*
* 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:
* Tasktop Technologies - initial API and implementation
******************************************************************************/
package com.tasktop.c2c.server.developer.support;
import org.eclipse.jetty.ajp.Ajp13SocketConnector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* @author Clint Morgan (Tasktop Technologies Inc.)
*
*/
public class LocalServicesWebRunner {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebAppContext serviceContext = new WebAppContext();
serviceContext.setResourceBase("../com.tasktop.c2c.server.services.web/src/main/webapp");
serviceContext.setContextPath("/services");
serviceContext.setParentLoaderPriority(true);
WebAppContext taskContext = new WebAppContext();
taskContext.setResourceBase("../com.tasktop.c2c.server.tasks.web/src/main/webapp");
taskContext.setContextPath("/tasks");
taskContext.setParentLoaderPriority(true);
WebAppContext wikiContext = new WebAppContext();
wikiContext.setResourceBase("../com.tasktop.c2c.server.wiki.web/src/main/webapp");
wikiContext.setContextPath("/wiki");
wikiContext.setParentLoaderPriority(true);
WebAppContext hudsonConfigContext = new WebAppContext();
hudsonConfigContext.setResourceBase("../com.tasktop.c2c.server.hudson.web/src/main/webapp");
hudsonConfigContext.setContextPath("/hudson-config");
hudsonConfigContext.setParentLoaderPriority(true);
ContextHandlerCollection handlers = new ContextHandlerCollection();
handlers.setHandlers(new Handler[] { serviceContext, taskContext, wikiContext, hudsonConfigContext });
server.setHandler(handlers);
Ajp13SocketConnector ajpCon = new Ajp13SocketConnector();
ajpCon.setPort(8009);
server.addConnector(ajpCon);
server.start();
server.join();
}
}
| epl-1.0 |
bedatadriven/renjin | core/src/main/java/org/renjin/compiler/ir/tac/functions/ClosureDefinitionTranslator.java | 1957 | /*
* Renjin : JVM-based interpreter for the R language for the statistical analysis
* Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors
*
* 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, a copy is available at
* https://www.gnu.org/licenses/gpl-2.0.txt
*/
package org.renjin.compiler.ir.tac.functions;
import org.renjin.compiler.ir.tac.IRBodyBuilder;
import org.renjin.compiler.ir.tac.expressions.Expression;
import org.renjin.compiler.ir.tac.expressions.NestedFunction;
import org.renjin.eval.EvalException;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.PairList;
import org.renjin.sexp.SEXP;
/**
* Translator for the {@code function} function.
*/
public class ClosureDefinitionTranslator extends FunctionCallTranslator {
@Override
public Expression translateToExpression(IRBodyBuilder builder,
TranslationContext context, FunctionCall call) {
PairList formals = EvalException.checkedCast(call.getArgument(0));
SEXP body = call.getArgument(1);
SEXP source = call.getArgument(2);
return new NestedFunction(formals, body);
}
@Override
public void addStatement(IRBodyBuilder builder, TranslationContext context,
FunctionCall call) {
// a closure whose value is not used has no side effects
// E.g.
// function(x) x*2
// has no effect.
}
}
| gpl-2.0 |
moriyoshi/quercus-gae | src/main/java/com/caucho/quercus/lib/gettext/expr/MulExpr.java | 1273 | /*
* Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Nam Nguyen
*/
package com.caucho.quercus.lib.gettext.expr;
public class MulExpr extends BinaryExpr
{
public MulExpr(Expr _left, Expr _right)
{
super(_left, _right);
}
public int eval(int n)
{
return _left.eval(n) * _right.eval(n);
}
}
| gpl-2.0 |
erdalmutlu1/sisiya2 | ui/web/src/main/java/org/sisiya/ui/standart/System_service_alert.java | 8129 | //Auto generated file
//Do not edit this file
package org.sisiya.ui.standart;
import org.sql2o.Connection;
import org.sql2o.Query;
import java.util.List;
import org.sisiya.ui.Application;
import java.util.Date;
public class System_service_alert extends Model{
//Fields
protected int id;
protected int user_id;
protected int system_id;
protected int service_id;
protected int alert_type_id;
protected int status_id;
protected int frequency;
protected boolean enabled;
protected Date last_alert_time;
private ModelHooks mh;
private Boolean isNew;
//Constructer
public System_service_alert(){
isNew = true;
//Default Constructer
fields.add(new Field("id","int","system_service_alert-id",true,true));
fields.add(new Field("user_id","int","system_service_alert-user_id",false,false));
fields.add(new Field("system_id","int","system_service_alert-system_id",false,false));
fields.add(new Field("service_id","int","system_service_alert-service_id",false,false));
fields.add(new Field("alert_type_id","int","system_service_alert-alert_type_id",false,false));
fields.add(new Field("status_id","int","system_service_alert-status_id",false,false));
fields.add(new Field("frequency","int","system_service_alert-frequency",false,false));
fields.add(new Field("enabled","boolean","system_service_alert-enabled",false,false));
fields.add(new Field("last_alert_time","Date","system_service_alert-last_alert_time",false,false));
}
public void registerHooks(ModelHooks _mh){
mh = _mh;
}
//Setters
public void setId(int _id){
id = _id;
}
public void setUser_id(int _user_id){
user_id = _user_id;
}
public void setSystem_id(int _system_id){
system_id = _system_id;
}
public void setService_id(int _service_id){
service_id = _service_id;
}
public void setAlert_type_id(int _alert_type_id){
alert_type_id = _alert_type_id;
}
public void setStatus_id(int _status_id){
status_id = _status_id;
}
public void setFrequency(int _frequency){
frequency = _frequency;
}
public void setEnabled(boolean _enabled){
enabled = _enabled;
}
public void setLast_alert_time(Date _last_alert_time){
last_alert_time = _last_alert_time;
}
public void setIsNew(boolean b){
isNew = b;
}
//Getters
public int getId(){
return id;
}
public int getUser_id(){
return user_id;
}
public int getSystem_id(){
return system_id;
}
public int getService_id(){
return service_id;
}
public int getAlert_type_id(){
return alert_type_id;
}
public int getStatus_id(){
return status_id;
}
public int getFrequency(){
return frequency;
}
public boolean getEnabled(){
return enabled;
}
public Date getLast_alert_time(){
return last_alert_time;
}
public Boolean isNew() {
return isNew;
}
//Data Access Methods
//Data Access Methods
public boolean save(Connection _connection){
return(save(_connection,true,true));
}
public boolean save(Connection _connection,boolean doValidate,boolean executeHooks){
if(doValidate){
try {
if(!mh.validate(_connection)){
return(false);
}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
if(!isReadyToSave()){
return(false);
}
}
if(executeHooks){
try {
if(isNew()){
if(!mh.beforeInsert(_connection)){return(false);}
}else{
if(!mh.beforeUpdate(_connection)){return(false);}
}
if(!mh.beforeSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
//Actual db update
if(isNew()){
try {
if(!insert(_connection)){return(false);}
if(!mh.afterInsert(_connection)){return(false);}
if(!mh.afterSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}else{
try {
if(!update(_connection)){return(false);}
if(!mh.afterUpdate(_connection)){return(false);}
if(!mh.afterSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}
}else{
//Actual db operation without hooks
if(isNew()){
try {
if(!insert(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}else{
try {
if(!update(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}
}
return true;
}
public boolean destroy(Connection _connection,boolean executeHooks){
if(executeHooks){
if(!mh.beforeDestroy(_connection)){return(false);}
}
if(!delete(_connection)){return(false);}
if(executeHooks){
if(!mh.afterDestroy(_connection)){return(false);}
}
return(true);
}
public boolean destroy(Connection _connection){
return(destroy(_connection,true));
}
//Private Data Acess utility Methods
private boolean insert(Connection _connection){
Query query;
query = _connection.createQuery(insertSql(),true);
query = query.addParameter("user_idP",user_id);
query = query.addParameter("system_idP",system_id);
query = query.addParameter("service_idP",service_id);
query = query.addParameter("alert_type_idP",alert_type_id);
query = query.addParameter("status_idP",status_id);
query = query.addParameter("frequencyP",frequency);
query = query.addParameter("enabledP",enabled);
query = query.addParameter("last_alert_timeP",last_alert_time);
id = (int) query.executeUpdate().getKey();
return(true);
}
private boolean update(Connection _connection){
Query query;
query = _connection.createQuery(updateSql());
query = query.addParameter("idP",id);
query = query.addParameter("user_idP",user_id);
query = query.addParameter("system_idP",system_id);
query = query.addParameter("service_idP",service_id);
query = query.addParameter("alert_type_idP",alert_type_id);
query = query.addParameter("status_idP",status_id);
query = query.addParameter("frequencyP",frequency);
query = query.addParameter("enabledP",enabled);
query = query.addParameter("last_alert_timeP",last_alert_time);
query.executeUpdate();
return(true);
}
private boolean delete(Connection _connection){
Query query;
query = _connection.createQuery(deleteSql());
query.addParameter("idP",id);
query.executeUpdate();
return(true);
}
private String insertSql(){
String querySql = "insert into system_service_alerts( ";
querySql += "user_id,";
querySql += "system_id,";
querySql += "service_id,";
querySql += "alert_type_id,";
querySql += "status_id,";
querySql += "frequency,";
querySql += "enabled,";
querySql += "last_alert_time)";
querySql += "values (";
querySql += ":user_idP,";
querySql += ":system_idP,";
querySql += ":service_idP,";
querySql += ":alert_type_idP,";
querySql += ":status_idP,";
querySql += ":frequencyP,";
querySql += ":enabledP,";
querySql += ":last_alert_timeP)";
return querySql;
}
private String updateSql(){
String querySql = "update system_service_alerts set ";
querySql += "user_id = :user_idP, " ;
querySql += "system_id = :system_idP, " ;
querySql += "service_id = :service_idP, " ;
querySql += "alert_type_id = :alert_type_idP, " ;
querySql += "status_id = :status_idP, " ;
querySql += "frequency = :frequencyP, " ;
querySql += "enabled = :enabledP, " ;
querySql += "last_alert_time = :last_alert_timeP ";
querySql += " where id = :idP";
return querySql;
}
private String deleteSql(){
String querySql = "delete from system_service_alerts where id = :idP";
return querySql;
}
}
| gpl-2.0 |
owuorJnr/f8th | src/owuor/f8th/adapters/NotificationAdapter.java | 2832 | package owuor.f8th.adapters;
import java.util.List;
import owuor.f8th.R;
import owuor.f8th.ContentProvider.F8thContentProvider;
import owuor.f8th.database.NotificationsTable;
import owuor.f8th.types.F8th;
import owuor.f8th.types.Notification;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NotificationAdapter extends ArrayAdapter<Notification> {
private LayoutInflater layoutInflater;
private Context context;
public NotificationAdapter(Context context) {
super(context, android.R.layout.simple_list_item_2);
this.context = context;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}// end of constructor
public void setNotifyList(List<Notification> data) {
clear();
if (data != null) {
for (Notification appEntry : data) {
add(appEntry);
}
notifyDataSetChanged();
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_profile_notify_row, null);
holder = new ViewHolder();
holder.photoView = (ImageView)convertView.findViewById(R.id.imgSender);
holder.delete = (ImageView)convertView.findViewById(R.id.imgDeleteNotify);
holder.sender = (TextView) convertView.findViewById(R.id.txtFrom);
holder.message = (TextView) convertView.findViewById(R.id.txtMessage);
holder.date = (TextView) convertView.findViewById(R.id.txtDate);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Notification notification = getItem(position);
if(notification.getStatus().equalsIgnoreCase(F8th.NOTIFY_UNREAD)){
holder.sender.setTextColor(Color.RED);
}
holder.sender.setText(notification.getSender());
holder.message.setText(notification.getMessage());
holder.date.setText(notification.getDateSent());
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri uri = Uri.parse(F8thContentProvider.CONTENT_URI + "/" + NotificationsTable.TABLE_NOTIFY);
String selection = NotificationsTable.COLUMN_NOTIFY_ID + "='" + notification.getNotifyId() + "'";
context.getContentResolver().delete(uri, selection, null);
NotificationAdapter.this.remove(notification);
notifyDataSetChanged();
}
});
return convertView;
}// end of method getView()
static class ViewHolder {
ImageView photoView,delete;
TextView sender, message, date;
}
}// END OF CLASS NotificationAdapter | gpl-2.0 |
xiaotian15/meister | meister-config-server/src/main/java/org/xiaotian/config/ConfigFilesFinder.java | 4912 | package org.xiaotian.config;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.xiaotian.config.bean.ConfigFile;
import org.xiaotian.config.bean.ConfigFiles;
import org.xiaotian.extend.CMyFile;
/**
* 按照指定方式(配置文件plugin和mapping.xml在同一目录)读写文件的工具类 <BR>
*
* @author xiaotian15
*
*/
public class ConfigFilesFinder {
private static Logger m_logger = Logger.getLogger(ConfigFilesFinder.class);
/**
* 负有所有配置文件信息的ConfigFile集合
*/
private ConfigFiles m_oConfigFiles = null;
/**
* 配置文件存放的根文件夹位置,是查找的入口
*/
private ArrayList<String> m_pConfigFileRootPaths = new ArrayList<String>();
/**
* 要查找的配置文件的名称,如 config.xml
*/
private String m_sConfigXmlFile;
private HashMap<String, ConfigFile> m_mapAlreadyDoneWithFileNames = new HashMap<String, ConfigFile>();
public ConfigFilesFinder(String _sConfigFileRootPath, String _sConfigXmlFile) {
m_pConfigFileRootPaths.add(_sConfigFileRootPath);
this.m_sConfigXmlFile = _sConfigXmlFile;
}
public ConfigFilesFinder(ArrayList<String> _arConfigFileRootPaths,
String _sConfigXmlFile) {
this.m_pConfigFileRootPaths = _arConfigFileRootPaths;
this.m_sConfigXmlFile = _sConfigXmlFile;
}
/**
* 得到已经组织好的配置文件集合
*
* @return 包含config.xml - mapping.xml的CfgFiles对象
* @throws ConfigException
* 可能的文件读取错误
*/
public ConfigFiles getConfigFiles() throws ConfigException {
if (m_oConfigFiles == null) {
m_oConfigFiles = new ConfigFiles();
for (int i = 0; i < m_pConfigFileRootPaths.size(); i++) {
String sConfigFileRootPath = (String) m_pConfigFileRootPaths
.get(i);
if (m_logger.isDebugEnabled())
m_logger.debug("begin to load config files from["
+ sConfigFileRootPath + "]...");
File fRoot = new File(sConfigFileRootPath);
lookupCfgFiles(fRoot);
}
} else {
if (m_logger.isDebugEnabled())
m_logger.debug("the files have been loaded.");
}
return m_oConfigFiles;
}
/**
* 刷新
*/
public ConfigFiles refresh() throws ConfigException {
m_oConfigFiles = null;
return getConfigFiles();
}
/**
* 递归检索指定目录,将查找的文件加入到m_hshFiles中去
*
* @param _file
* 文件夹路径或者文件路径,后者是递归跳出的条件
*/
private void lookupCfgFiles(File _file) {
if (_file.isFile()) {
// 不是指定的文件名
if (!_file.getName().equals(this.m_sConfigXmlFile)) {
return;
}
// 在与Config.xml同级的目录中寻找配置对象的描述文件:mapping.xml
String sMapping = CMyFile.extractFilePath(_file.getPath())
+ ConfigConstants.NAME_FILE_MAPPING;
File fMapping = CMyFile.fileExists(sMapping) ? new File(sMapping)
: null;
// 分解配置文件
String sAbsolutFileName = _file.getAbsolutePath();
String sConfigFileNameExcludeProjectPath = extractConfigFileNameExcludeProjectPath(sAbsolutFileName);
// 判断是否处理,如果处理了,判断Mapping文件是否设置,没有直接返回
ConfigFile configFile = (ConfigFile) m_mapAlreadyDoneWithFileNames
.get(sConfigFileNameExcludeProjectPath);
if (configFile != null) {
if (configFile.getMapping() == null && fMapping != null) {
configFile.setMapping(fMapping);
}
return;
}
// 记录下已经处理的配置文件
configFile = new ConfigFile(_file, fMapping);
m_mapAlreadyDoneWithFileNames.put(
sConfigFileNameExcludeProjectPath, configFile);
if (m_logger.isDebugEnabled()) {
m_logger.debug("load xml file[" + _file.getPath() + "]");
}
m_oConfigFiles.add(configFile);
return;
}
// 递归调用,遍历所有子文件夹
File[] dirs = _file.listFiles();
if (dirs == null) {
m_logger.warn("May be a IOException,find an invalid dir:"
+ _file.getAbsolutePath());
return;
}
for (int i = 0; i < dirs.length; i++) {
lookupCfgFiles(dirs[i]);
}
}
/**
* 获取s_sAppRootPath后面的路径<BR>
*
* @param _sAbsolutFileName
* config文件的root路径
* @return
*/
private String extractConfigFileNameExcludeProjectPath(
String _sAbsolutFileName) {
String sConfigFilePathFlag = File.separatorChar
+ ConfigConstants.CONFIG_ROOT_PATH + File.separatorChar;
String sConfigFileNameExcludeProjectPath = _sAbsolutFileName;
int nPos = _sAbsolutFileName.indexOf(sConfigFilePathFlag);
if (nPos >= 0) {
sConfigFileNameExcludeProjectPath = _sAbsolutFileName
.substring(nPos);
}
return sConfigFileNameExcludeProjectPath;
}
} | gpl-2.0 |
nakedpony/justcoin-ripple-checker | src/main/java/com/shinydev/wrappers/JustcoinWrapper.java | 2350 | package com.shinydev.wrappers;
import au.com.bytecode.opencsv.CSVReader;
import com.shinydev.justcoin.model.JustcoinTransaction;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
public class JustcoinWrapper {
private static final Logger LOG = LoggerFactory.getLogger(JustcoinWrapper.class);
private final String justcoinCvsFileLocation;
private final DateTimeZone zone;
public JustcoinWrapper(String justcoinCvsFileLocation, DateTimeZone zone) {
this.justcoinCvsFileLocation = justcoinCvsFileLocation;
this.zone = zone;
}
public List<JustcoinTransaction> getJustcoinCreditTransactions(DateTime start, DateTime end) throws IOException {
checkArgument(start.getZone().equals(zone), "start date should be with the same zone as passed in constructor");
checkArgument(end.getZone().equals(zone), "end date should be with the same zone as passed in constructor");
CSVReader reader = new CSVReader(new FileReader(justcoinCvsFileLocation));
List<String[]> myEntries = new ArrayList<>();
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
if ("id".equals(nextLine[0])) {
LOG.debug("Parsed Justcoin CVS header");
} else {
myEntries.add(nextLine);
}
}
List<JustcoinTransaction> justcoinTransactions = myEntries.stream()
.map(entry -> new JustcoinTransaction(
entry[0],
entry[1],
Long.valueOf(entry[2]), //long
DateTime.parse(entry[3]).withZone(zone),
entry[4],
new BigDecimal(entry[5]) //big decimal
))
.collect(Collectors.toList());
return justcoinTransactions.stream()
.filter(tx -> tx.getDateTime().isAfter(start))
.filter(tx -> tx.getDateTime().isBefore(end))
.collect(Collectors.toList());
}
}
| gpl-2.0 |
CleverCloud/Quercus | resin/src/main/java/com/caucho/env/thread/ThreadTask.java | 2251 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.env.thread;
import java.util.concurrent.locks.LockSupport;
import com.caucho.util.Alarm;
/**
* A generic pool of threads available for Alarms and Work tasks.
*/
final class ThreadTask {
private final Runnable _runnable;
private final ClassLoader _loader;
private volatile Thread _thread;
ThreadTask(Runnable runnable, ClassLoader loader, Thread thread)
{
_runnable = runnable;
_loader = loader;
_thread = thread;
}
final Runnable getRunnable()
{
return _runnable;
}
final ClassLoader getLoader()
{
return _loader;
}
void clearThread()
{
_thread = null;
}
final void wake()
{
Thread thread = _thread;
_thread = null;
if (thread != null)
LockSupport.unpark(thread);
}
final void park(long expires)
{
Thread thread = _thread;
while (_thread != null
&& Alarm.getCurrentTimeActual() < expires) {
try {
Thread.interrupted();
LockSupport.parkUntil(thread, expires);
} catch (Exception e) {
}
}
/*
if (_thread != null) {
System.out.println("TIMEOUT:" + thread);
Thread.dumpStack();
}
*/
_thread = null;
}
}
| gpl-2.0 |
PDavid/aTunes | aTunes/src/main/java/net/sourceforge/atunes/gui/views/menus/ApplicationMenuBar.java | 3100 | /*
* aTunes
* Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
*
* See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
*
* http://www.atunes.org
* http://sourceforge.net/projects/atunes
*
* 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.
*/
package net.sourceforge.atunes.gui.views.menus;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import net.sourceforge.atunes.model.IMenuBar;
/**
* The application menu bar.
*/
/**
* @author alex
*
*/
public final class ApplicationMenuBar extends JMenuBar implements IMenuBar {
private static final long serialVersionUID = 234977404080329591L;
private JMenu fileMenu;
private JMenu editMenu;
private JMenu viewMenu;
private JMenu playerMenu;
private PlayListMenu playListMenu;
private JMenu toolsMenu;
private JMenu deviceMenu;
private JMenu helpMenu;
/**
* @param playerMenu
*/
public void setPlayerMenu(JMenu playerMenu) {
this.playerMenu = playerMenu;
}
/**
* @param fileMenu
*/
public void setFileMenu(JMenu fileMenu) {
this.fileMenu = fileMenu;
}
/**
* @param editMenu
*/
public void setEditMenu(JMenu editMenu) {
this.editMenu = editMenu;
}
/**
* @param viewMenu
*/
public void setViewMenu(JMenu viewMenu) {
this.viewMenu = viewMenu;
}
/**
* @param toolsMenu
*/
public void setToolsMenu(JMenu toolsMenu) {
this.toolsMenu = toolsMenu;
}
/**
* @param deviceMenu
*/
public void setDeviceMenu(JMenu deviceMenu) {
this.deviceMenu = deviceMenu;
}
/* (non-Javadoc)
* @see javax.swing.JMenuBar#setHelpMenu(javax.swing.JMenu)
*/
public void setHelpMenu(JMenu helpMenu) {
this.helpMenu = helpMenu;
}
/**
* @param playListMenu
*/
public void setPlayListMenu(PlayListMenu playListMenu) {
this.playListMenu = playListMenu;
}
/**
* Adds the menus.
*/
@Override
public void initialize() {
add(fileMenu);
add(editMenu);
add(viewMenu);
add(playerMenu);
playListMenu.initialize();
add(playListMenu);
add(deviceMenu);
add(toolsMenu);
add(helpMenu);
}
/* (non-Javadoc)
* @see net.sourceforge.atunes.gui.views.menus.IMenuBar#addMenu(javax.swing.JMenu)
*/
@Override
public void addMenu(JMenu newMenu) {
remove(getComponentCount() - 1);
add(newMenu);
add(helpMenu);
}
@Override
public JMenuBar getSwingComponent() {
return this;
}
}
| gpl-2.0 |
serusisergio/CheckEngine | app/src/main/java/it/unica/checkengine/Sommo.java | 11304 | package it.unica.checkengine;
import android.util.Log;
/**
* Created by Stefano on 28/01/2015.
*/
public final class Sommo {
public final static void ave(){
String testo = ".\n,.....................................,,...,.,,,,..,,..............................................,.............,......\n" +
".......................,......................,,....,.....,......................................................,......\n" +
"......................................................,,:,:~,.,,,.,,,...............................,,,.,.........,,,...\n" +
"............................,..............,...,,:~~+?I$$$Z7$$$7$?+=::,,,..................,..,,,.............,....,....\n" +
"..,.........................................,:=+I$$ZZOZOOZO$ZZZ$OZO$$$I?=~:........................................,....\n" +
".........................................,.~?7$ZZOZZZZZ$$$Z$$$$$OZZZZZ7Z$7=+~...........................................\n" +
".......................................:=+$$ZZZZ$$$$7$$7$$$7$$$$$7$$Z$$$OZ$Z7?=:,,........,......,,.....,..............,\n" +
"...,....,........,...................,:?$ZOOOZZZ$77$7$$77I777777$77$7$$$$$$$ZZ7I+,,......,........,.....................\n" +
"....................................~7$OOOZ$$7777777IIIIIIII7III7II7777$$7777$ZZII=,,,,.............,...................\n" +
"................................,.,IZOOZZ$$$7777IIIIII?I???IIIIIIIIII7I77$7$$777$$7+~:,,,,......,.......................\n" +
".................................,$OOOOOZ$Z7777II??????????????II?IIII77777$$777$7$7I+~::,,.............................\n" +
".....,..............,...........~O888O8ZZZ$7IIIII??????????++???++????I?7II77$$7I?II7$?=~:,,........,..............,,...\n" +
"..............................,,Z8DDODZZO$IIIII??????+++?++++++++++??????I?777I7IIIII77?~~~:,,..........................\n" +
".............................,.O88DDD8ZZ7I?I??????+??+?++++++++++++++++++??I?III??II?I$7?++~:,,,.,,,.....,....,,,.......\n" +
"..............................$8D8ND88$II?????????++++++++++++++=++++++++?+?????II?IIII7$7I+=~:,,,.......,..............\n" +
"..............,..............~ON8DDDOZ7I???????+++++++++++++++++==++++++++??????IIIIIII7ZZ7?+=~:,,.,.............,,,....\n" +
"..........,,,................OZ88DDOO$II?????????++++++=+=====+========+++++?????IIIIIII$ZZ7I+=~:,,,....................\n" +
"......,.....................I888ON8OZ77I?+??????+??++++========+=========++++?+???IIIIII7OOZ7?==~:,,,...................\n" +
"......,.,..................~ZD8O8ND8Z77???????I???++++++==================++++++??III77IIZOOZI?+=~:,,.,...............,,\n" +
"...........................7OZ8DO8$ZZ77??????????++++++++++=============+++++++++??III7777ZOO$I?=~:,,...................\n" +
"..........................:$DZOD88ZZZ$7I????????+++???+++++++++++========+++++++??III7777IZOOZ7I+=:...................,,\n" +
"..........................+O8OOZOZO$777I????????+++????+++++++++++++++===++++++????III7777O$OO$7+~,,..,.................\n" +
"........................,.$OOZOZOZ$$777????????????+++++=====+++?+++++++++++?+???I?II77777$ZOOZ$?=:,:,,...........,.....\n" +
"........................,,ZZ8OOOZZ7$$I????I??I????++++=========++++++++++++++++??IIII7777I$OOOOZI+~::,,..........,,.....\n" +
".........................,8OZO$ZO$$$7??I????I????+?+++====~==~~==++===+++++++++???III77777Z8OOOZI?=~::,,.........,......\n" +
"........................,,D88ZZ$$Z$7???I???I?++?+???????+===~~=~=+=+===++===+++++?II777777Z8Z8OO$I+=~:,,,...............\n";
String testo2 = ".\n......................II?IDDZ$OO$$ZII????????++???++=++I$77I====~===========+=++++??II77$ZOOO88OZ7?=~:,,................\n" +
"...................,.III?++7$OOOZZ$7?+????++++???====??+++I7$7+?============+=+++++???I7$$OOZOOOZ$I+~:,,,...............\n" +
".....................+=???+=??8O$$7I?+???+++++++?7?II7I???I????+++=+=====+++III7$$7IIIII$Z88OO8OZ$I+~,.,................\n" +
".....................+=I+:?+=?88OZI?????+++=+++?IZ7ODZ8O~$?II+??++====+++?II7ZZZ$II?7III7Z8Z888OO$I+~:.,,...............\n" +
".....................==?+~?++?ZOO$??????+==+++?+?I?78DOI~=7III??++====+?I$$7????III+?II77$8O8888Z$I+~:,,,,....,.........\n" +
"..........,..........=I++=++??IOZ$I?????+===+++++??????I?II??+?7??++=+?$7???$DNDO$877I$7IZOO888OZ$?+~:..,...............\n" +
".....................=?+=++?I??8Z7?????++==+++++====~~~==??++=III??+=+7$?7I=I8ODD+I$8I77I87?O8OOZ7?+~:,,.....,..........\n" +
".....................?===~+?+?IZ$I????+++==++=+=====:::~=++?+????I?++?I$?+I7I+OZ++7I$$III8?I7OOO$I+=~:,.................\n" +
"........... ......I====?~=?IOZ7????+++====+=====~~:~~=++??????I????I$I?????IIII7$7I?I7$7$88OO$I+=:,,.................\n" +
"........... .......?==++I~=?7IZ+????+++=========+===~==+++++?????+++?7II????++?IIII??I$Z+888OO$I+~:,,.................\n" +
".......... ........~++??I7=I$77?I????++=====~====+==+++++++?++??+++??7III??+++++?7???IO7$888OO$I+=::,.................\n" +
"......................??=++III$7?I?III?++=========+=+====++++++???++++III?I?+?????I???IIZI88888OZ7?=::,.................\n" +
"...................,..,??+===?I7II+I?I?+++==================+????+?+++?I7??I?I++?????IIID?88888O$I+=::,,................\n" +
"........ ..........,..,,?====?IIIII????++=======+======~~++III?I??+++++?$??????I??????IZ$88888OZ7?=~:,,.................\n" +
"..... .................,=====+7?????I???++==========~~~=+=I?++++++++++++??+??+??????II?D88888OO$I+=:,,,.................\n" +
".........................===+=7II???????++=++=======~==+==?++?++++==~=++?7++++?????II77OO8888OZ7?+~:,,..................\n" +
".......,...................?+=7III????+?+++++=============?I++??II++++?I?7=++????IIII7DO88888Z$I+=~:,,..................\n" +
"............................,777III?????+++=+=+======+==++++??+++$???I7?I?+++??I?II77$OO8888O$7?=~:,,,..................\n" +
".............................I7IIII??I??++?+++======++++????????+?++I$I???+++??II7I$7I$8888OZ7?+=:,,..,.................\n" +
".............................77IIII????++++++=++===++++?????+?++++??I7III??+?+?II77$Z$88888O$?+=~:,,....................\n" +
"........................,..,,7777III?I???+++++===++++?+??+++++++?++??7III77?+??I777Z7I88888O7?+=~:,,..,,....,...........\n" +
"........................,,.NO777II?I?I??++++++++++?+=?++?+?++++?++++?II7I7I7???I77787D8888OZI+=~:,,,....................\n" ;
String testo3 = ".\n................,.,.....,,ND~I7$77I?II??++++++++++++++++III??I?++?+??III777II?II77$8888888O$I+~::,..,,.........,,.......\n" +
"................,..,IODN8DD$:7I$$IIIIII?++++++==+++?II77I77$$77II77IIIIII7I7IIII7$8DD8888OZ7?=~:,,..,,.......,...,,.....\n" +
"..............:8NDDDNN8DN8N=:7?I$77IIII??++++++++?????I?I7~=====+=+$8Z$Z$??I?II77$DDD888OZ$?+~:,,,,.....................\n" +
"...........~8NDD88NNMDNNND==:III$$7777I?????+++=?++++??I?I$$?===:==7Z7$II?I??II7$$DDD88OZ$I+=:,,,................,,,....\n" +
".....,.ZDDNNNNDDNNNNNNNNDM==:+I+I$$777I?????++++++++++?????II77$$$$$$$77I??+?I77$888D88Z$I+~:,,,..................,.....\n" +
",...7DDDNDDDDNDNDDDNDNNNDD~=~:I?+I$$$$II?????++++++?+++???+++IIIIIII$7$$7????I77$8DDD8O$7?=~:,,,...........,........,...\n" +
".=DD8DDDDDDDNNDNNDNDNNNNDI~~~,I??I77$$77?????++++++++++?+??IIIIIIIII77$7I???I7$$MMND8OZ$?+~:,,,,.,.......,..........,...\n" +
"DDDDDDDDNNDNNDNNNDNNNNDD8+~~=:,I++I?77$7II????++??++++++++?+?????I777777I???I$ZMMNNNNNDDZ?::,,..........................\n" +
"DDDDDDDDDNNNMNNNDNNNNNDDD=~~~~,:?+?+?I7$7IIII?+????++++++???????????II7I??II$Z8MNDDDDDNNDD88,,........,..,......,..,....\n" +
"ND8DNDD8DNDNNNDDDDDDDNDDD+~:~~:,:?+++II7$$7III?++++++?????+??????II?IIIIIII$ZZMMNDDDDDNDDNDDNDD8~.,.,.....,.............\n" +
"D8DDDDDN8NDNNNDNNDDDNNDDD7~~::::,,I+++??II$$7$7????+++???+=++++???III?I7II7O8MMDDDDDDDNNDDDDNNDNDDDD:.,........,........\n" +
"DDDNDD8DN8DNDDDDDDDDNDDD8D~~::,::,.++++??II77777I??+++??+++++++?+II77I777$ODNMMMN8ZDDNDDDNDDNDDDNDDDN8N7..,.............\n" +
"DNDDDDDDDDNDNDNDDDDNNDDDDN~~::,,,,,,:?++????IIII$7I?++??+++??++??II7II7$ONNNMMNMMNMM$NDDDNDDNDNDNNNDDDDDDDDO:...........\n" +
"NDDDDDNNDDDDNDNDDDDDNDDD8D~~::,,,,,,..?++++??????I7III??I????+?II777I$ZNMNMNMN8MMNMMM$MDNNDDDNDDNNNDDDNDNNNND8Z.........\n" +
"NDDNDDDNNDNNNDDNDDDDNNDNDDZ~::,,,,,,,,.,++++++??????7$$$7777IIIII777ZMMMMMNMMMDMMMMND87MDDNDDDDDDDDNDDNDDDDNDND8Z.,,....\n" +
"NDNDDNDNDNNDDNDDDDDDNDDDDDN:::,,,,,,,,,.,,+++++???+++++=+7O8888D8OZ=8NNNMNMMNMMMMMMMND87MDDDDDNDDDDDNDNDDNDNDNNDND7~,...\n" +
"NDNDDDDDNNMNNDNN8DDD8D8D8DD::::,,,,,,.,,.,,==+=+??+++==++?77II?I7::=MDNNM8MMNNMMMMMMMMD8OMDDDDDNDDDNDDNDNNNNNNDDDDDDD,,,\n" +
"MDDDDDNDNNDDNNNNDDDDDDD88DD~::,,,,,,...,,,,..+++??+=++++?$I????=:::?MDNNNMMMMMMMMMMMMMMD8MMDDDDDNDDNDDNNDNDNNNNNDNND8D~~\n" +
"DDDDDDNDMNNNNN88DDDDDDD8DDNZ:::,,,,,.......,.,,=?+++++??$I????=:::+?MNNNMMMMMMMMMMMMMMMN87MNDDDDDDDNDDDNDDNDNDNNDDDD887=\n" +
"DDNDDDDMNNNNNNDNDDDDDDDDDDON:,:,,,,,.............,I?+?7$I?+++~:,:~?ZDDNNMNMMNMMMMMMNMMMMN8NMDDDDD88DDDDDNDNDDNNDNDDND8N7\n" +
"DDDDNNDNMMMNMN8DNDDDDDDD8DNN,,,,,,,,,...............=Z7???+=:,,::++NNDNNMMNNMNNMMMMNDMMMMM8MM8DD8D8DDD8DDDDNNDDNDDDN8DDD\n" +
"DDDDDNNNMDNMNNNDDNND8DD88DND?,:,,,,,,,...............:~:,:,+?=.:~++MNDNNMNNNNMMNNMMDMNNNMDNMMNDDD88D8DDDDDNDDDNNNDDND8ND\n" +
"D8DNDDDMMNNMNDNNNDDDDD8DDDD8D:,,,,,,,,............,~:,,~?==+MNZ?:=?NDNNNMNNNNDDNDNMMMMNNMMMMMM8DDDDDDDDDD8DDNDNDDDDDDDDD\n" +
"NDDDDDNNNDMNMNDNDDDDNNDDDND8D,,,,,,,,,,.........~.,,,~~~7+N8O8OMM:?MDDNNMNMDNDNNDNDMMMMMMMODMMN8DDDDNDNDDDDN8NNDDDNDDDDD\n" +
"DDDDNNNDNNNMD8NNDDNDDDN8DD888,.,,.,,,,..,,..,DD8+:78O?O$O8IMN7ZMM:=MNDNNMNNNNDDNDNDNMMMMMMM8ZMMDO8DN8DNDDDNDD8DD8NMDDDND\n" +
"DNDN8MNN8DNNNMNND8DDND8D88DOO?,.,,,,,,...=N:7$788$ZZO+OZODDNNZOM~~~NDDNNMNNNDNNDNNNNMNMMMMMMNIMN88NNNDDNDDDDDDDDDNMDD8NN\n" +
"DDNDDNDDNDNNDMNNNNDD888D888D8D,,,,,,.,.=?Z??Z8D88OOO7ZODDDNNOZD~:+:NDDDNNNNNDNNDNNNNNNDNMMMMMD$MM8DDDDNNNDDDDDDNNNMDDDNN\n" +
"DDDDNDDNNDDDNDN8NDDD8DD8D8D8D8..,,,.:.,,..,.?I$I$DOZ~$ZZNMMNMNI~~~?NDDNNNNNNNNDNNDNNNDDDDDMMMMNZMMDNNNDDDDDNDD8DNMNDDNDN\n" +
"8DNDNDDDN88DDDDDDO88D8D8D8888D.,.,,,:........,,$8ZOZZ$8$NNNMM8,:~~8N8DDDNNNNNDDNNDDDDDDNNDDMMMMM7MNNNNNNDDDDDD8NNMD8DNDN";
Log.d("AVE_AL_SOMMO", testo);
Log.d("", testo2);
Log.d("", testo3);
}
}
| gpl-2.0 |
DrewG/mzmine3 | src/main/java/io/github/mzmine/modules/featuretable/renderers/RtRenderer.java | 1988 | /*
* Copyright 2006-2016 The MZmine 3 Development Team
*
* This file is part of MZmine 3.
*
* MZmine 3 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.
*
* MZmine 3 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 MZmine 3; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.github.mzmine.modules.featuretable.renderers;
import java.text.NumberFormat;
import io.github.msdk.datamodel.featuretables.FeatureTableRow;
import io.github.mzmine.main.MZmineCore;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
public class RtRenderer implements
Callback<TreeTableColumn<FeatureTableRow, Object>, TreeTableCell<FeatureTableRow, Object>> {
@Override
public TreeTableCell<FeatureTableRow, Object> call(TreeTableColumn<FeatureTableRow, Object> p) {
return new TreeTableCell<FeatureTableRow, Object>() {
@Override
public void updateItem(Object object, boolean empty) {
super.updateItem(object, empty);
setStyle("-fx-alignment: CENTER;"
+ "-fx-border-color: transparent -fx-table-cell-border-color -fx-table-cell-border-color transparent;");
if (object == null) {
setText(null);
} else {
NumberFormat formatter = MZmineCore.getConfiguration().getRTFormat();
Float floatValue = Float.parseFloat(object.toString());
setText(formatter.format(floatValue));
}
}
};
}
}
| gpl-2.0 |
joshmoore/zeroc-ice | java/src/IceInternal/OutgoingConnectionFactory.java | 37163 | // **********************************************************************
//
// Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
package IceInternal;
public final class OutgoingConnectionFactory
{
//
// Helper class to to multi hash map.
//
private static class MultiHashMap<K, V> extends java.util.HashMap<K, java.util.List<V>>
{
public void
put(K key, V value)
{
java.util.List<V> list = this.get(key);
if(list == null)
{
list = new java.util.LinkedList<V>();
this.put(key, list);
}
list.add(value);
}
public void
remove(K key, V value)
{
java.util.List<V> list = this.get(key);
assert(list != null);
list.remove(value);
if(list.isEmpty())
{
this.remove(key);
}
}
};
interface CreateConnectionCallback
{
void setConnection(Ice.ConnectionI connection, boolean compress);
void setException(Ice.LocalException ex);
}
public synchronized void
destroy()
{
if(_destroyed)
{
return;
}
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
connection.destroy(Ice.ConnectionI.CommunicatorDestroyed);
}
}
_destroyed = true;
notifyAll();
}
public void
waitUntilFinished()
{
java.util.Map<Connector, java.util.List<Ice.ConnectionI> > connections = null;
synchronized(this)
{
//
// First we wait until the factory is destroyed. We also
// wait until there are no pending connections
// anymore. Only then we can be sure the _connections
// contains all connections.
//
while(!_destroyed || !_pending.isEmpty() || _pendingConnectCount > 0)
{
try
{
wait();
}
catch(InterruptedException ex)
{
}
}
//
// We want to wait until all connections are finished outside the
// thread synchronization.
//
connections = new java.util.HashMap<Connector, java.util.List<Ice.ConnectionI> >(_connections);
}
//
// Now we wait until the destruction of each connection is finished.
//
for(java.util.List<Ice.ConnectionI> connectionList : connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
connection.waitUntilFinished();
}
}
synchronized(this)
{
// Ensure all the connections are finished and reapable at this point.
java.util.List<Ice.ConnectionI> cons = _reaper.swapConnections();
if(cons != null)
{
int size = 0;
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
size += connectionList.size();
}
assert(cons.size() == size);
_connections.clear();
_connectionsByEndpoint.clear();
}
else
{
assert(_connections.isEmpty());
assert(_connectionsByEndpoint.isEmpty());
}
}
}
public Ice.ConnectionI
create(EndpointI[] endpts, boolean hasMore, Ice.EndpointSelectionType selType, Ice.BooleanHolder compress)
{
assert(endpts.length > 0);
//
// Apply the overrides.
//
java.util.List<EndpointI> endpoints = applyOverrides(endpts);
//
// Try to find a connection to one of the given endpoints.
//
Ice.ConnectionI connection = findConnectionByEndpoint(endpoints, compress);
if(connection != null)
{
return connection;
}
Ice.LocalException exception = null;
//
// If we didn't find a connection with the endpoints, we create the connectors
// for the endpoints.
//
java.util.List<ConnectorInfo> connectors = new java.util.ArrayList<ConnectorInfo>();
java.util.Iterator<EndpointI> p = endpoints.iterator();
while(p.hasNext())
{
EndpointI endpoint = p.next();
//
// Create connectors for the endpoint.
//
try
{
java.util.List<Connector> cons = endpoint.connectors();
assert(cons.size() > 0);
//
// Shuffle connectors if endpoint selection type is Random.
//
if(selType == Ice.EndpointSelectionType.Random)
{
java.util.Collections.shuffle(cons);
}
for(Connector c : cons)
{
connectors.add(new ConnectorInfo(c, endpoint));
}
}
catch(Ice.LocalException ex)
{
exception = ex;
handleException(exception, hasMore || p.hasNext());
}
}
if(connectors.isEmpty())
{
assert(exception != null);
throw exception;
}
//
// Try to get a connection to one of the connectors. A null result indicates that no
// connection was found and that we should try to establish the connection (and that
// the connectors were added to _pending to prevent other threads from establishing
// the connection).
//
connection = getConnection(connectors, null, compress);
if(connection != null)
{
return connection;
}
//
// Try to establish the connection to the connectors.
//
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
java.util.Iterator<ConnectorInfo> q = connectors.iterator();
ConnectorInfo ci = null;
while(q.hasNext())
{
ci = q.next();
try
{
connection = createConnection(ci.connector.connect(), ci);
connection.start(null);
if(defaultsAndOverrides.overrideCompress)
{
compress.value = defaultsAndOverrides.overrideCompressValue;
}
else
{
compress.value = ci.endpoint.compress();
}
connection.activate();
break;
}
catch(Ice.CommunicatorDestroyedException ex)
{
exception = ex;
handleConnectionException(exception, hasMore || p.hasNext());
connection = null;
break; // No need to continue
}
catch(Ice.LocalException ex)
{
exception = ex;
handleConnectionException(exception, hasMore || p.hasNext());
connection = null;
}
}
//
// Finish creating the connection (this removes the connectors from the _pending
// list and notifies any waiting threads).
//
if(connection != null)
{
finishGetConnection(connectors, ci, connection, null);
}
else
{
finishGetConnection(connectors, exception, null);
}
if(connection == null)
{
assert(exception != null);
throw exception;
}
return connection;
}
public void
create(EndpointI[] endpts, boolean hasMore, Ice.EndpointSelectionType selType,
CreateConnectionCallback callback)
{
assert(endpts.length > 0);
//
// Apply the overrides.
//
java.util.List<EndpointI> endpoints = applyOverrides(endpts);
//
// Try to find a connection to one of the given endpoints.
//
try
{
Ice.BooleanHolder compress = new Ice.BooleanHolder();
Ice.ConnectionI connection = findConnectionByEndpoint(endpoints, compress);
if(connection != null)
{
callback.setConnection(connection, compress.value);
return;
}
}
catch(Ice.LocalException ex)
{
callback.setException(ex);
return;
}
ConnectCallback cb = new ConnectCallback(this, endpoints, hasMore, callback, selType);
cb.getConnectors();
}
public synchronized void
setRouterInfo(IceInternal.RouterInfo routerInfo)
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
assert(routerInfo != null);
//
// Search for connections to the router's client proxy
// endpoints, and update the object adapter for such
// connections, so that callbacks from the router can be
// received over such connections.
//
Ice.ObjectAdapter adapter = routerInfo.getAdapter();
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
for(EndpointI endpoint : routerInfo.getClientEndpoints())
{
//
// Modify endpoints with overrides.
//
if(defaultsAndOverrides.overrideTimeout)
{
endpoint = endpoint.timeout(defaultsAndOverrides.overrideTimeoutValue);
}
//
// The Connection object does not take the compression flag of
// endpoints into account, but instead gets the information
// about whether messages should be compressed or not from
// other sources. In order to allow connection sharing for
// endpoints that differ in the value of the compression flag
// only, we always set the compression flag to false here in
// this connection factory.
//
endpoint = endpoint.compress(false);
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
if(connection.endpoint() == endpoint)
{
connection.setAdapter(adapter);
}
}
}
}
}
public synchronized void
removeAdapter(Ice.ObjectAdapter adapter)
{
if(_destroyed)
{
return;
}
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
if(connection.getAdapter() == adapter)
{
connection.setAdapter(null);
}
}
}
}
public void
flushAsyncBatchRequests(CommunicatorBatchOutgoingAsync outAsync)
{
java.util.List<Ice.ConnectionI> c = new java.util.LinkedList<Ice.ConnectionI>();
synchronized(this)
{
if(!_destroyed)
{
for(java.util.List<Ice.ConnectionI> connectionList : _connections.values())
{
for(Ice.ConnectionI connection : connectionList)
{
if(connection.isActiveOrHolding())
{
c.add(connection);
}
}
}
}
}
for(Ice.ConnectionI conn : c)
{
try
{
outAsync.flushConnection(conn);
}
catch(Ice.LocalException ex)
{
// Ignore.
}
}
}
//
// Only for use by Instance.
//
OutgoingConnectionFactory(Instance instance)
{
_instance = instance;
_destroyed = false;
}
protected synchronized void
finalize()
throws Throwable
{
IceUtilInternal.Assert.FinalizerAssert(_destroyed);
//IceUtilInternal.Assert.FinalizerAssert(_connections.isEmpty());
//IceUtilInternal.Assert.FinalizerAssert(_connectionsByEndpoint.isEmpty());
IceUtilInternal.Assert.FinalizerAssert(_pendingConnectCount == 0);
IceUtilInternal.Assert.FinalizerAssert(_pending.isEmpty());
super.finalize();
}
private java.util.List<EndpointI>
applyOverrides(EndpointI[] endpts)
{
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
java.util.List<EndpointI> endpoints = new java.util.ArrayList<EndpointI>();
for(EndpointI endpoint : endpts)
{
//
// Modify endpoints with overrides.
//
if(defaultsAndOverrides.overrideTimeout)
{
endpoints.add(endpoint.timeout(defaultsAndOverrides.overrideTimeoutValue));
}
else
{
endpoints.add(endpoint);
}
}
return endpoints;
}
synchronized private Ice.ConnectionI
findConnectionByEndpoint(java.util.List<EndpointI> endpoints, Ice.BooleanHolder compress)
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
assert(!endpoints.isEmpty());
for(EndpointI endpoint : endpoints)
{
java.util.List<Ice.ConnectionI> connectionList = _connectionsByEndpoint.get(endpoint);
if(connectionList == null)
{
continue;
}
for(Ice.ConnectionI connection : connectionList)
{
if(connection.isActiveOrHolding()) // Don't return destroyed or un-validated connections
{
if(defaultsAndOverrides.overrideCompress)
{
compress.value = defaultsAndOverrides.overrideCompressValue;
}
else
{
compress.value = endpoint.compress();
}
return connection;
}
}
}
return null;
}
//
// Must be called while synchronized.
//
private Ice.ConnectionI
findConnection(java.util.List<ConnectorInfo> connectors, Ice.BooleanHolder compress)
{
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
for(ConnectorInfo ci : connectors)
{
if(_pending.containsKey(ci.connector))
{
continue;
}
java.util.List<Ice.ConnectionI> connectionList = _connections.get(ci.connector);
if(connectionList == null)
{
continue;
}
for(Ice.ConnectionI connection : connectionList)
{
if(connection.isActiveOrHolding()) // Don't return destroyed or un-validated connections
{
if(defaultsAndOverrides.overrideCompress)
{
compress.value = defaultsAndOverrides.overrideCompressValue;
}
else
{
compress.value = ci.endpoint.compress();
}
return connection;
}
}
}
return null;
}
synchronized private void
incPendingConnectCount()
{
//
// Keep track of the number of pending connects. The outgoing connection factory
// waitUntilFinished() method waits for all the pending connects to terminate before
// to return. This ensures that the communicator client thread pool isn't destroyed
// too soon and will still be available to execute the ice_exception() callbacks for
// the asynchronous requests waiting on a connection to be established.
//
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
++_pendingConnectCount;
}
synchronized private void
decPendingConnectCount()
{
--_pendingConnectCount;
assert(_pendingConnectCount >= 0);
if(_destroyed && _pendingConnectCount == 0)
{
notifyAll();
}
}
private Ice.ConnectionI
getConnection(java.util.List<ConnectorInfo> connectors, ConnectCallback cb, Ice.BooleanHolder compress)
{
synchronized(this)
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
//
// Reap closed connections
//
java.util.List<Ice.ConnectionI> cons = _reaper.swapConnections();
if(cons != null)
{
for(Ice.ConnectionI c : cons)
{
_connections.remove(c.connector(), c);
_connectionsByEndpoint.remove(c.endpoint(), c);
_connectionsByEndpoint.remove(c.endpoint().compress(true), c);
}
}
//
// Try to get the connection. We may need to wait for other threads to
// finish if one of them is currently establishing a connection to one
// of our connectors.
//
while(true)
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
//
// Search for a matching connection. If we find one, we're done.
//
Ice.ConnectionI connection = findConnection(connectors, compress);
if(connection != null)
{
return connection;
}
if(addToPending(cb, connectors))
{
//
// If a callback is not specified we wait until another thread notifies us about a
// change to the pending list. Otherwise, if a callback is provided we're done:
// when the pending list changes the callback will be notified and will try to
// get the connection again.
//
if(cb == null)
{
try
{
wait();
}
catch(InterruptedException ex)
{
}
}
else
{
return null;
}
}
else
{
//
// If no thread is currently establishing a connection to one of our connectors,
// we get out of this loop and start the connection establishment to one of the
// given connectors.
//
break;
}
}
}
//
// At this point, we're responsible for establishing the connection to one of
// the given connectors. If it's a non-blocking connect, calling nextConnector
// will start the connection establishment. Otherwise, we return null to get
// the caller to establish the connection.
//
if(cb != null)
{
cb.nextConnector();
}
return null;
}
private synchronized Ice.ConnectionI
createConnection(Transceiver transceiver, ConnectorInfo ci)
{
assert(_pending.containsKey(ci.connector) && transceiver != null);
//
// Create and add the connection to the connection map. Adding the connection to the map
// is necessary to support the interruption of the connection initialization and validation
// in case the communicator is destroyed.
//
Ice.ConnectionI connection = null;
try
{
if(_destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
connection = new Ice.ConnectionI(_instance, _reaper, transceiver, ci.connector,
ci.endpoint.compress(false), null);
}
catch(Ice.LocalException ex)
{
try
{
transceiver.close();
}
catch(Ice.LocalException exc)
{
// Ignore
}
throw ex;
}
_connections.put(ci.connector, connection);
_connectionsByEndpoint.put(connection.endpoint(), connection);
_connectionsByEndpoint.put(connection.endpoint().compress(true), connection);
return connection;
}
private void
finishGetConnection(java.util.List<ConnectorInfo> connectors,
ConnectorInfo ci,
Ice.ConnectionI connection,
ConnectCallback cb)
{
java.util.Set<ConnectCallback> connectionCallbacks = new java.util.HashSet<ConnectCallback>();
if(cb != null)
{
connectionCallbacks.add(cb);
}
java.util.Set<ConnectCallback> callbacks = new java.util.HashSet<ConnectCallback>();
synchronized(this)
{
for(ConnectorInfo c : connectors)
{
java.util.Set<ConnectCallback> cbs = _pending.remove(c.connector);
if(cbs != null)
{
for(ConnectCallback cc : cbs)
{
if(cc.hasConnector(ci))
{
connectionCallbacks.add(cc);
}
else
{
callbacks.add(cc);
}
}
}
}
for(ConnectCallback cc : connectionCallbacks)
{
cc.removeFromPending();
callbacks.remove(cc);
}
for(ConnectCallback cc : callbacks)
{
cc.removeFromPending();
}
notifyAll();
}
boolean compress;
DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides();
if(defaultsAndOverrides.overrideCompress)
{
compress = defaultsAndOverrides.overrideCompressValue;
}
else
{
compress = ci.endpoint.compress();
}
for(ConnectCallback cc : callbacks)
{
cc.getConnection();
}
for(ConnectCallback cc : connectionCallbacks)
{
cc.setConnection(connection, compress);
}
}
private void
finishGetConnection(java.util.List<ConnectorInfo> connectors, Ice.LocalException ex, ConnectCallback cb)
{
java.util.Set<ConnectCallback> failedCallbacks = new java.util.HashSet<ConnectCallback>();
if(cb != null)
{
failedCallbacks.add(cb);
}
java.util.Set<ConnectCallback> callbacks = new java.util.HashSet<ConnectCallback>();
synchronized(this)
{
for(ConnectorInfo c : connectors)
{
java.util.Set<ConnectCallback> cbs = _pending.remove(c.connector);
if(cbs != null)
{
for(ConnectCallback cc : cbs)
{
if(cc.removeConnectors(connectors))
{
failedCallbacks.add(cc);
}
else
{
callbacks.add(cc);
}
}
}
}
for(ConnectCallback cc : callbacks)
{
assert(!failedCallbacks.contains(cc));
cc.removeFromPending();
}
notifyAll();
}
for(ConnectCallback cc : callbacks)
{
cc.getConnection();
}
for(ConnectCallback cc : failedCallbacks)
{
cc.setException(ex);
}
}
private boolean
addToPending(ConnectCallback cb, java.util.List<ConnectorInfo> connectors)
{
//
// Add the callback to each connector pending list.
//
boolean found = false;
for(ConnectorInfo p : connectors)
{
java.util.Set<ConnectCallback> cbs = _pending.get(p.connector);
if(cbs != null)
{
found = true;
if(cb != null)
{
cbs.add(cb); // Add the callback to each pending connector.
}
}
}
if(found)
{
return true;
}
//
// If there's no pending connection for the given connectors, we're
// responsible for its establishment. We add empty pending lists,
// other callbacks to the same connectors will be queued.
//
for(ConnectorInfo p : connectors)
{
if(!_pending.containsKey(p.connector))
{
_pending.put(p.connector, new java.util.HashSet<ConnectCallback>());
}
}
return false;
}
private void
removeFromPending(ConnectCallback cb, java.util.List<ConnectorInfo> connectors)
{
for(ConnectorInfo p : connectors)
{
java.util.Set<ConnectCallback> cbs = _pending.get(p.connector);
if(cbs != null)
{
cbs.remove(cb);
}
}
}
private void
handleConnectionException(Ice.LocalException ex, boolean hasMore)
{
TraceLevels traceLevels = _instance.traceLevels();
if(traceLevels.retry >= 2)
{
StringBuilder s = new StringBuilder(128);
s.append("connection to endpoint failed");
if(ex instanceof Ice.CommunicatorDestroyedException)
{
s.append("\n");
}
else
{
if(hasMore)
{
s.append(", trying next endpoint\n");
}
else
{
s.append(" and no more endpoints to try\n");
}
}
s.append(ex.toString());
_instance.initializationData().logger.trace(traceLevels.retryCat, s.toString());
}
}
private void
handleException(Ice.LocalException ex, boolean hasMore)
{
TraceLevels traceLevels = _instance.traceLevels();
if(traceLevels.retry >= 2)
{
StringBuilder s = new StringBuilder(128);
s.append("couldn't resolve endpoint host");
if(ex instanceof Ice.CommunicatorDestroyedException)
{
s.append("\n");
}
else
{
if(hasMore)
{
s.append(", trying next endpoint\n");
}
else
{
s.append(" and no more endpoints to try\n");
}
}
s.append(ex.toString());
_instance.initializationData().logger.trace(traceLevels.retryCat, s.toString());
}
}
private static class ConnectorInfo
{
public ConnectorInfo(Connector c, EndpointI e)
{
connector = c;
endpoint = e;
}
public boolean
equals(Object obj)
{
ConnectorInfo r = (ConnectorInfo)obj;
return connector.equals(r.connector);
}
public int
hashCode()
{
return connector.hashCode();
}
public Connector connector;
public EndpointI endpoint;
}
private static class ConnectCallback implements Ice.ConnectionI.StartCallback, EndpointI_connectors
{
ConnectCallback(OutgoingConnectionFactory f, java.util.List<EndpointI> endpoints, boolean more,
CreateConnectionCallback cb, Ice.EndpointSelectionType selType)
{
_factory = f;
_endpoints = endpoints;
_hasMore = more;
_callback = cb;
_selType = selType;
_endpointsIter = _endpoints.iterator();
}
//
// Methods from ConnectionI.StartCallback
//
public void
connectionStartCompleted(Ice.ConnectionI connection)
{
connection.activate();
_factory.finishGetConnection(_connectors, _current, connection, this);
}
public void
connectionStartFailed(Ice.ConnectionI connection, Ice.LocalException ex)
{
assert(_current != null);
_factory.handleConnectionException(ex, _hasMore || _iter.hasNext());
if(ex instanceof Ice.CommunicatorDestroyedException) // No need to continue.
{
_factory.finishGetConnection(_connectors, ex, this);
}
else if(_iter.hasNext()) // Try the next connector.
{
nextConnector();
}
else
{
_factory.finishGetConnection(_connectors, ex, this);
}
}
//
// Methods from EndpointI_connectors
//
public void
connectors(java.util.List<Connector> cons)
{
//
// Shuffle connectors if endpoint selection type is Random.
//
if(_selType == Ice.EndpointSelectionType.Random)
{
java.util.Collections.shuffle(cons);
}
for(Connector p : cons)
{
_connectors.add(new ConnectorInfo(p, _currentEndpoint));
}
if(_endpointsIter.hasNext())
{
nextEndpoint();
}
else
{
assert(!_connectors.isEmpty());
//
// We now have all the connectors for the given endpoints. We can try to obtain the
// connection.
//
_iter = _connectors.iterator();
getConnection();
}
}
public void
exception(Ice.LocalException ex)
{
_factory.handleException(ex, _hasMore || _endpointsIter.hasNext());
if(_endpointsIter.hasNext())
{
nextEndpoint();
}
else if(!_connectors.isEmpty())
{
//
// We now have all the connectors for the given endpoints. We can try to obtain the
// connection.
//
_iter = _connectors.iterator();
getConnection();
}
else
{
_callback.setException(ex);
_factory.decPendingConnectCount(); // Must be called last.
}
}
public void
setConnection(Ice.ConnectionI connection, boolean compress)
{
//
// Callback from the factory: the connection to one of the callback
// connectors has been established.
//
_callback.setConnection(connection, compress);
_factory.decPendingConnectCount(); // Must be called last.
}
public void
setException(Ice.LocalException ex)
{
//
// Callback from the factory: connection establishment failed.
//
_callback.setException(ex);
_factory.decPendingConnectCount(); // Must be called last.
}
public boolean
hasConnector(ConnectorInfo ci)
{
return _connectors.contains(ci);
}
public boolean
removeConnectors(java.util.List<ConnectorInfo> connectors)
{
_connectors.removeAll(connectors);
_iter = _connectors.iterator();
return _connectors.isEmpty();
}
public void
removeFromPending()
{
_factory.removeFromPending(this, _connectors);
}
void
getConnectors()
{
try
{
//
// Notify the factory that there's an async connect pending. This is necessary
// to prevent the outgoing connection factory to be destroyed before all the
// pending asynchronous connects are finished.
//
_factory.incPendingConnectCount();
}
catch(Ice.LocalException ex)
{
_callback.setException(ex);
return;
}
nextEndpoint();
}
void
nextEndpoint()
{
try
{
assert(_endpointsIter.hasNext());
_currentEndpoint = _endpointsIter.next();
_currentEndpoint.connectors_async(this);
}
catch(Ice.LocalException ex)
{
exception(ex);
}
}
void
getConnection()
{
try
{
//
// If all the connectors have been created, we ask the factory to get a
// connection.
//
Ice.BooleanHolder compress = new Ice.BooleanHolder();
Ice.ConnectionI connection = _factory.getConnection(_connectors, this, compress);
if(connection == null)
{
//
// A null return value from getConnection indicates that the connection
// is being established and that everthing has been done to ensure that
// the callback will be notified when the connection establishment is
// done.
//
return;
}
_callback.setConnection(connection, compress.value);
_factory.decPendingConnectCount(); // Must be called last.
}
catch(Ice.LocalException ex)
{
_callback.setException(ex);
_factory.decPendingConnectCount(); // Must be called last.
}
}
void
nextConnector()
{
Ice.ConnectionI connection = null;
try
{
assert(_iter.hasNext());
_current = _iter.next();
connection = _factory.createConnection(_current.connector.connect(), _current);
connection.start(this);
}
catch(Ice.LocalException ex)
{
connectionStartFailed(connection, ex);
}
}
private final OutgoingConnectionFactory _factory;
private final boolean _hasMore;
private final CreateConnectionCallback _callback;
private final java.util.List<EndpointI> _endpoints;
private final Ice.EndpointSelectionType _selType;
private java.util.Iterator<EndpointI> _endpointsIter;
private EndpointI _currentEndpoint;
private java.util.List<ConnectorInfo> _connectors = new java.util.ArrayList<ConnectorInfo>();
private java.util.Iterator<ConnectorInfo> _iter;
private ConnectorInfo _current;
}
private final Instance _instance;
private final ConnectionReaper _reaper = new ConnectionReaper();
private boolean _destroyed;
private MultiHashMap<Connector, Ice.ConnectionI> _connections = new MultiHashMap<Connector, Ice.ConnectionI>();
private MultiHashMap<EndpointI, Ice.ConnectionI> _connectionsByEndpoint =
new MultiHashMap<EndpointI, Ice.ConnectionI>();
private java.util.Map<Connector, java.util.HashSet<ConnectCallback> > _pending =
new java.util.HashMap<Connector, java.util.HashSet<ConnectCallback> >();
private int _pendingConnectCount = 0;
}
| gpl-2.0 |
cst316/spring16project-Team-Chicago | src/net/sf/memoranda/IllegalPhoneNumberException.java | 614 | /**
* Exception class for illegal phone number format strings.
* @author Jonathan Hinkle
*/
package net.sf.memoranda;
/**
* This class is thrown when a string is not a valid phone number format.
*
* @author Jonathan Hinkle
*
*/
@SuppressWarnings("serial")
public class IllegalPhoneNumberException extends IllegalArgumentException {
/**
* IllegalPhoneNumberException constructor.
*/
public IllegalPhoneNumberException() {}
/**
* IllegalPhoneNumberException constructor.
*
* @param message A message String
*/
public IllegalPhoneNumberException(String message) {
super(message);
}
}
| gpl-2.0 |
Jianchu/checker-framework | checker/tests/nullness/EnsuresNonNullIfInheritedTest.java | 934 | import org.checkerframework.checker.nullness.qual.*;
import org.checkerframework.dataflow.qual.Pure;
class Node {
int id;
@Nullable Node next;
Node(int id, @Nullable Node next) {
this.id = id;
this.next = next;
}
}
class SubEnumerate {
protected @Nullable Node current;
public SubEnumerate(Node node) {
this.current = node;
}
@EnsuresNonNullIf(expression = "current", result = true)
public boolean hasMoreElements() {
return (current != null);
}
}
class Enumerate extends SubEnumerate {
public Enumerate(Node node) {
super(node);
}
public boolean hasMoreElements() {
return (current != null);
}
}
class Main {
public static final void main(String args[]) {
Node n2 = new Node(2, null);
Node n1 = new Node(1, n2);
Enumerate e = new Enumerate(n1);
while (e.hasMoreElements()) {}
}
}
| gpl-2.0 |
ParallelAndReconfigurableComputing/Pyjama | src/pj/pr/task/VirtualTarget.java | 1193 | /*
* Copyright (C) 2013-2016 Parallel and Reconfigurable Computing Group, University of Auckland.
*
* Authors: <http://homepages.engineering.auckland.ac.nz/~parallel/ParallelIT/People.html>
*
* This file is part of Pyjama, a Java implementation of OpenMP-like directive-based
* parallelisation compiler and its runtime routines.
*
* Pyjama 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.
*
* Pyjama 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 Pyjama. If not, see <http://www.gnu.org/licenses/>.
*/
package pj.pr.task;
public abstract class VirtualTarget {
protected String targetName;
public abstract void submit(TargetTask<?> task);
public String targetName() {
return this.targetName;
}
}
| gpl-2.0 |
lucaseverini/ROPE | src/rope1401/ClipboardListener.java | 1713 | /**
* <p>Title: ClipboardListener.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: NASA Ames Research Center</p>
* @author Ronald Mak & Luca Severini <lucaseverini@mac.com>
* @version 2.0
*/
package rope1401;
import java.awt.*;
import java.awt.datatransfer.*;
public class ClipboardListener extends Thread implements ClipboardOwner
{
private final Clipboard sysClip;
RopeFrame mainFrame;
public boolean hasValidContent;
ClipboardListener (RopeFrame parent)
{
mainFrame = parent;
// This is ugly but necessary because mainFrame.clipboardListener is used in canPaste() below
mainFrame.clipboardListener = this;
sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
hasValidContent = checkContent(sysClip.getContents(this));
start();
}
@Override
public void run()
{
try
{
regainOwnership(sysClip.getContents(this));
}
catch(Exception ex) {}
while(true)
{
try
{
Thread.sleep(100);
}
catch(InterruptedException ex) {}
}
}
@Override
public void lostOwnership(Clipboard c, Transferable t)
{
// Sleeps a little bit to let the clipboard be ready and avoid exceptions...
try
{
sleep(100);
}
catch(InterruptedException ex)
{
System.out.println("Exception: " + ex);
}
Transferable contents = sysClip.getContents(this);
hasValidContent = checkContent(contents);
regainOwnership(contents);
}
void regainOwnership(Transferable t)
{
sysClip.setContents(t, this);
}
boolean checkContent(Transferable content)
{
return ((content != null) && content.isDataFlavorSupported(DataFlavor.stringFlavor));
}
}
| gpl-2.0 |
lgvalle/Beautiful-Photos | app/src/main/java/com/lgvalle/beaufitulphotos/fivehundredpxs/model/Feature.java | 553 | package com.lgvalle.beaufitulphotos.fivehundredpxs.model;
import com.lgvalle.beaufitulphotos.R;
/**
* Created by luis.gonzalez on 23/07/14.
* Enum to represent service features
*/
public enum Feature {
Popular("popular", R.string.feature_popular),
HighestRated("highest_rated", R.string.feature_highest_rated);
private final String param;
private final int title;
Feature(String param, int title) {
this.param = param;
this.title = title;
}
public String getParam() {
return param;
}
public int getTitle() {
return title;
}
}
| gpl-2.0 |
52North/triturus | src/main/java/org/n52/v3d/triturus/gisimplm/GmSimpleElevationGrid.java | 17502 | /**
* Copyright (C) 2007-2016 52North Initiative for Geospatial Open Source
* Software GmbH
*
* 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.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0.
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* 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.
*
* Contact: Benno Schmidt and Martin May, 52North Initiative for Geospatial
* Open Source Software GmbH, Martin-Luther-King-Weg 24, 48155 Muenster,
* Germany, info@52north.org
*/
package org.n52.v3d.triturus.gisimplm;
import org.n52.v3d.triturus.vgis.*;
import org.n52.v3d.triturus.core.T3dException;
import java.util.ArrayList;
/**
* Class to manage a grid holding elevation values. The grid is assumed
* to be parallel in line with the <i>x</i>- and <i>y</i>-axis. It might be specified
* as vertex-based (so-called <i>"Lattice"</i>) or cell-based
* (<i>"Grid"</i>;, often reffered to as "Raster").
* Note that grid's values may left unset, since for all grid elements
* (vertices or cells) a "no data"-flag can be set.<br/>
* <br/>
* Note: Within this framework, elevation-grids should be used to hold
* georeferenced <i>z</i>-value only, e.g terrain elevation values, groundwater
* levels, geologic depth data, height values inside the atmosphere etc.
* To hold thematic ("non-georeferenced") floating-point data such as
* temperatures, humidities, wind speeds, air pressure values etc. the
* class <tt>{@link GmSimpleFloatGrid}</tt> shall be preferred.
*
* @author Benno Schmidt
*/
public class GmSimpleElevationGrid extends VgElevationGrid
{
private GmSimple2dGridGeometry mGeom;
private double[][] mVal;
private boolean[][] mIsSetFl;
private boolean mLatticeMode = false;
private String mTheme = "Elevation";
/**
* Constructor. This will generate a grid will all elements unset.
*
* @param nCols Number of grid cells in <i>x</i>-direction (columns)
* @param nRows Number of grid cells in <i>y</i>-direction (rows)
* @param origin Origin point
* @param deltaX Cell-size in <i>x</i>-direction
* @param deltaY Cell-size in <i>y</i>-direction
*/
public GmSimpleElevationGrid(
int nCols, int nRows,
VgPoint origin,
double deltaX, double deltaY)
{
// TODO: Im Folgenden besser die static-Methoden aus GmSimpleFloatGrid
// nutzen, um Redundanzen zu vermeiden. (-> nächstes Refactoring)
mGeom = new GmSimple2dGridGeometry(
nCols, nRows,
origin,
deltaX, deltaY);
mVal = new double[nRows][nCols];
mIsSetFl = new boolean[nRows][nCols];
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
mIsSetFl[i][j] = false;
}
}
this.setName("unnamed elevation grid");
}
/**
* Constructor. This will generate a grid will all elements unset.
*
* @param geom Existing grid geometry
*/
public GmSimpleElevationGrid(GmSimple2dGridGeometry geom)
{
mGeom = geom;
int nRows = mGeom.numberOfRows();
int nCols = mGeom.numberOfColumns();
mVal = new double[nRows][nCols];
mIsSetFl = new boolean[nRows][nCols];
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
mIsSetFl[i][j] = false;
}
}
this.setName("unnamed elevation grid");
}
/**
* provides thematic meta-information.
*
* @return List of strings
*/
public ArrayList<String> getThematicAttributes()
{
ArrayList<String> list = new ArrayList<String>();
list.add(mTheme);
return list;
}
/**
* returns the object geometry.
*
* @return {@link GmSimple2dGridGeometry}-object
*/
public VgGeomObject getGeometry() {
return mGeom;
}
/**
* always returns <i>false</i>, since a {@link GmSimpleElevationGrid}
* consists of one and only geo-object.
*
* @return <i>false</i>
*/
public boolean isCollection() {
return false;
}
/**
* always returns this {@link GmSimpleElevationGrid} itself.
*
* @param i (here always 0)
* @return Elevation-grid itself
* @throws T3dException
*/
public VgFeature getFeature(int i) throws T3dException
{
if (i != 0)
throw new T3dException("Index out of bounds." );
// else:
return this;
}
public int numberOfFeatures() {
return 1;
}
public int numberOfSubFeatures() {
return numberOfFeatures();
}
public int numberOfColumns() {
return mGeom.numberOfColumns();
}
public int numberOfRows() {
return mGeom.numberOfRows();
}
/**
* returns the grid's cell-size in <i>x</i>-direction.
*/
public double getDeltaX() {
return mGeom.getDeltaX();
}
/**
* returns the grid's cell-size in <i>y</i>-direction.
*/
public double getDeltaY() {
return mGeom.getDeltaY();
}
/**
* sets vertex-based interpretation mode. It always holds that either
* vertex-based or cell-based interpretation mode is set.
*/
public void setLatticeInterpretation() {
mLatticeMode = true;
}
/**
* sets cell-based interpretation mode.
*
* @see this{@link #setLatticeInterpretation()}
*/
public void setGridInterpretation() {
mLatticeMode = false;
}
/**
* returns the information, whether vertex-based interpretation mode is
* set.
*
* @return <i>true</i> for vertex-based, <i>false</i> for cell-based interpretation
* @see this{@link #setLatticeInterpretation()}
*/
public boolean isLatticeInterpretion() {
return mLatticeMode;
}
/**
* sets vertex-based interpretation mode to the given value.
*
* @param latticeMode <i>true</i> for vertex-based, <i>false</i> for cell-based interpretation
* @see this{@link #setLatticeInterpretation()}
*/
public void setLatticeInterpretation(boolean latticeMode) {
mLatticeMode = latticeMode;
}
/**
* sets the elevation value <tt>z</tt> for the row index <tt>row</tt> and
* the column index <tt>col</tt>. If one of the assertions
* <i>0 <= row < this.numberOfRows(),
* 0 <= col < this.numberOfColumns()</i>
* is violated, a <tt>T3dException</tt> will be thrown. Post-condition:
* <tt>this.isSet(row, col) = true</tt>
*
* @param row Row-index
* @param col Column-index
* @param z Elevation-value
*/
public void setValue(int row, int col, double z) throws T3dException
{
try {
double zOld = mVal[row][col];
mVal[row][col] = z;
mIsSetFl[row][col] = true;
this.updateZBounds(zOld, z);
}
catch (Exception e) {
throw new T3dException(
"Could not set grid value (" + row + ", " + col + ").");
}
}
/**
* returns <i>true</i>, if an elevation-value is assigned to a given
* grid element. If one of the assertions
* <i>0 <= row < this.numberOfRows(),
* 0 <= col < this.numberOfColumns()</i>
* is violated, a <tt>T3dException</tt> will be thrown.
*
* @param row Row index
* @param col Column index
* @throws T3dException
*/
public boolean isSet(int row, int col) throws T3dException
{
try {
return mIsSetFl[row][col];
}
catch (Exception e) {
throw new T3dException(e.getMessage());
}
}
/**
* returns <i>true</i>, if all <i>z</i>-values are assigned to all grid elements.
*/
public boolean isSet()
{
for (int i = 0; i < this.numberOfRows(); i++) {
for (int j = 0; j < this.numberOfColumns(); j++) {
if (!mIsSetFl[i][j]) return false;
}
}
return true;
}
/**
* defines a grid element (vertex or cell) as unset ("nodata").
* If one of the assertions
* <i>0 <= row < this.numberOfRows(),
* 0 <= col < this.numberOfColumns()</i>
* is violated, a <tt>T3dException</tt> will be thrown. Post-condition:
* <tt>this.isIsSet(row, col) = false</tt><p>
*
* @param row Row index
* @param col Column index
* @throws T3dException
*/
public void unset(int row, int col) throws T3dException
{
try {
mIsSetFl[row][col] = false;
}
catch (Exception e) {
throw new T3dException(e.getMessage());
}
}
/**
* gets the elevation-value for the row-index <tt>row</tt> and the
* column-index <tt>col</tt>.
* If one of the assertions
* <i>0 <= row < this.numberOfRows(),
* 0 <= col < this.numberOfColumns()</i>
* is violated, or if the queried element is unset, a
* <tt>T3dException</tt> will be thrown. Post-condition:
* <tt>this.isIsSet(row, col) = false</tt><p>
*
* @param row Row index
* @param col Column index
* @throws T3dException
*/
public double getValue(int row, int col) throws T3dException
{
try {
if (mIsSetFl[row][col]) {
return mVal[row][col];
} else {
throw new T3dException("Tried to access unset grid element.");
}
}
catch (Exception e) {
throw new T3dException(
"Illegal grid element access. " + e.getMessage());
}
}
/**
* gets the elevation-value for the georeferenced position <tt>pPos</tt>.
* Note that the method performs a <i>bilinear</i> interpolation. If the
* given position is outside the elevation grid's extent, the method will
* return <i>null</i>. If the position-points coordinate reference system
* is not compatible to the elevation-grids reference system, a
* {@link T3dSRSException} will be thrown.
*
* @param pos Position (x, y)
* @return Elevation (z) as {@link Double}-object or <i>null</i>
*/
public Double getValue(VgPoint pos) throws T3dSRSException
{
if (pos == null) {
return null;
}
if (!(pos.getSRS() == null && mGeom.getSRS() == null)) {
if (!(pos.getSRS().equalsIgnoreCase(mGeom.getSRS()))) {
throw new T3dSRSException();
}
}
float[] idx = mGeom.getIndicesAsFloat(pos);
if (idx == null) {
return null;
}
float is = idx[0], js = idx[1];
int row = (int) idx[0], col = (int) idx[1];
if (
mIsSetFl[row][col] &&
mIsSetFl[row + 1][col] &&
mIsSetFl[row][col + 1] &&
mIsSetFl[row + 1][col + 1])
{
double lambda = js - ((float) col), my = is - ((float) row);
return
mVal[row][col] * (1.f - my) * (1.f - lambda) +
mVal[row + 1][col] * my * (1.f - lambda) +
mVal[row][col + 1] * (1.f - my) * lambda +
mVal[row + 1][col + 1] * my * lambda;
}
// else:
return null;
}
/**
* returns the elevation grid's bounding-box. Note that this extent
* depends on the grid-type (vertex-based "lattice" mode or
* cell-based "grid" mode)!
*
* @return 3D-bounding-box, or <i>null</i> if an error occurs
* @see GmSimpleElevationGrid#setLatticeInterpretation
* @see GmSimpleElevationGrid#setGridInterpretation
*/
public VgEnvelope envelope()
{
VgEnvelope env = this.getGeometry().envelope();
double xMin = env.getXMin();
double xMax = env.getXMax();
double yMin = env.getYMin();
double yMax = env.getYMax();
if (!mLatticeMode) {
double dx = 0.5 * this.getDeltaX();
xMin -= dx;
xMax += dx;
double dy = 0.5 * this.getDeltaY();
yMin -= dy;
yMax += dy;
}
double zMin, zMax;
try {
zMin = this.minimalElevation();
zMax = this.maximalElevation();
}
catch (T3dException e) {
return null;
}
return new GmEnvelope(xMin, xMax, yMin, yMax, zMin, zMax);
}
public double minimalElevation() throws T3dException
{
try {
this.calculateZBounds();
}
catch (T3dException e) {
throw e;
}
return mZMin;
}
public double maximalElevation() throws T3dException
{
try {
this.calculateZBounds();
}
catch (T3dException e) {
throw e;
}
return mZMax;
}
/**
* deactivates lazy evaluation mode for minimal/maximal <i>z</i>-value
* computation. For performance reasons, it might be necessary to
* deactivate this mode explicitly before starting multiple
* <tt>setValue()</tt>-calls.
*/
public void setZBoundsInvalid() {
mCalculated = false;
}
// Private helpers to compute z-bounds ("lazy evaluation"!):
private boolean mCalculated = false;
private double mZMin, mZMax;
private void calculateZBounds() throws T3dException
{
if (!mCalculated) {
try {
mZMin = this.getFirstSetZValue();
}
catch (T3dException e) {
throw e;
}
mZMax = mZMin;
double z;
for (int i = 0; i < this.numberOfRows(); i++) {
for (int j = 0; j < this.numberOfColumns(); j++) {
if (this.isSet(i, j)) {
z = this.getValue(i, j);
if (z < mZMin) mZMin = z; else {
if (z > mZMax) mZMax = z; }
}
}
}
mCalculated = true;
}
}
private void updateZBounds(double zOld, double zNew)
{
final double eps = 0.000001; // Epsilon for =-operation
if (mCalculated) {
if (zNew <= mZMin) { mZMin = zNew; return; }
// assert: pZMin < pZNew
if (zNew >= mZMax) { mZMax = zNew; return; }
// assert: pZMin < pZNew < mZMax
if (Math.abs(zOld - mZMin) < eps || Math.abs(zOld - mZMax) < eps)
mCalculated = false; // re-computation will be necessary later
} // else:
; // skip
}
// Get z-value of some set grid element:
private double getFirstSetZValue() throws T3dException
{
for (int i = 0; i < this.numberOfRows(); i++) {
for (int j = 0; j < this.numberOfColumns(); j++) {
if (this.isSet(i, j))
return this.getValue(i, j);
}
}
// else:
throw new T3dException("Tried to access empty elevation grid.");
}
/**
* returns the coordinates of a point that is part of the elevation-grid.
* If there is no <i>z</i>-value assigned to the grid point, the return-value
* will be <i>null</i>.
*
* @param row Row-index
* @param col Column-index
* @return Elevation-Point
*/
public VgPoint getPoint(int row, int col)
{
double
x = mGeom.getOrigin().getX() + col * this.getDeltaX(),
y = mGeom.getOrigin().getY() + row * this.getDeltaY(),
z;
if (!this.isSet(row, col))
return null;
z = this.getValue(row, col);
return new GmPoint(x, y, z);
}
/**
* returns the corresponding footprint geometry.
*
* @return Footprint as {@link GmSimple2dGridGeometry}-object
*/
public VgGeomObject footprint() {
return mGeom.footprint();
}
public String getTheme() {
return mTheme;
}
public void setTheme(String theme) {
mTheme = theme;
}
public String toString() {
String strGeom = "<empty geometry>";
if (mGeom != null)
strGeom = mGeom.toString();
return "[" + mTheme + ", \"" + strGeom + "\"]";
}
}
| gpl-2.0 |
sorelmitra/edu | carorder/src/spiridon/carorder/caritems/AlloyRimsCarItem.java | 248 | package spiridon.carorder.caritems;
public class AlloyRimsCarItem extends CarItem {
@Override
public double getPrice() {
return 100;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "Jante Aliaj";
}
}
| gpl-2.0 |