repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
qgears/rtemplate
hu.rtemplate/src/hu/qgears/rtemplate/LinePart.java
594
package hu.qgears.rtemplate; abstract public class LinePart { String content; int from, length; public LinePart(String content, int from, int length) { super(); this.content = content; this.from=from; this.length=length; } public LinePart(String content) { this.content = content; length = content.length(); } public void setFrom(int from) { this.from = from; } public String getContent() { return content; } @Override public String toString() { return content; } public int getFrom() { return from; } public int getLength() { return length; } }
mit
swaplicado/siie32
src/erp/mod/trn/view/SViewInventoryValuation.java
4773
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mod.trn.view; import erp.mod.SModConsts; import java.util.ArrayList; import sa.lib.SLibConsts; import sa.lib.SLibTimeUtils; import sa.lib.db.SDbConsts; import sa.lib.grid.SGridColumnView; import sa.lib.grid.SGridConsts; import sa.lib.grid.SGridFilterValue; import sa.lib.grid.SGridFilterYear; import sa.lib.grid.SGridPaneSettings; import sa.lib.grid.SGridPaneView; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; /** * * @author Sergio Flores */ public class SViewInventoryValuation extends SGridPaneView { private SGridFilterYear moFilterYear; public SViewInventoryValuation(SGuiClient client, String title) { super(client, SGridConsts.GRID_PANE_VIEW, SModConsts.TRN_INV_VAL, SLibConsts.UNDEFINED, title); initComponentsCustom(); moFilterYear = new SGridFilterYear(client, this); moFilterYear.initFilter(SLibTimeUtils.digestYear(miClient.getSession().getCurrentDate())); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(moFilterYear); } private void initComponentsCustom() { setRowButtonsEnabled(true, false, false, false, false); } @Override public void prepareSqlQuery() { String sql = ""; Object filter = null; moPaneSettings = new SGridPaneSettings(1); moPaneSettings.setDeletedApplying(true); moPaneSettings.setUserInsertApplying(true); moPaneSettings.setUserUpdateApplying(true); filter = ((SGridFilterValue) moFiltersMap.get(SGridConsts.FILTER_DELETED)).getValue(); if ((Boolean) filter) { sql += (sql.isEmpty() ? "" : "AND ") + "v.b_del = 0 "; } filter = ((SGridFilterValue) moFiltersMap.get(SGridConsts.FILTER_YEAR)).getValue(); if (filter != null && ((int[]) filter).length == 1) { sql += (sql.isEmpty() ? "" : "AND ") + "v.fk_year_year = " + ((int[]) filter)[0] + " "; } msSql = "SELECT " + "v.id_inv_val AS " + SDbConsts.FIELD_ID + "1, " + "CONCAT(v.fk_year_year, '-', v.fk_year_per) AS " + SDbConsts.FIELD_CODE + ", " + "CONCAT(v.fk_year_year, '-', v.fk_year_per) AS " + SDbConsts.FIELD_NAME + ", " + "v.b_fin, " + "v.fk_year_year, " + "v.fk_year_per, " + "v.b_del AS " + SDbConsts.FIELD_IS_DEL + ", " + "v.fk_usr_ins AS " + SDbConsts.FIELD_USER_INS_ID + ", " + "v.fk_usr_upd AS " + SDbConsts.FIELD_USER_UPD_ID + ", " + "v.ts_usr_ins AS " + SDbConsts.FIELD_USER_INS_TS + ", " + "v.ts_usr_upd AS " + SDbConsts.FIELD_USER_UPD_TS + ", " + "ui.usr AS " + SDbConsts.FIELD_USER_INS_NAME + ", " + "uu.usr AS " + SDbConsts.FIELD_USER_UPD_NAME + " " + "FROM " + SModConsts.TablesMap.get(SModConsts.TRN_INV_VAL) + " AS v " + "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.USRU_USR) + " AS ui ON " + "v.fk_usr_ins = ui.id_usr " + "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.USRU_USR) + " AS uu ON " + "v.fk_usr_upd = uu.id_usr " + (sql.isEmpty() ? "" : "WHERE " + sql) + "ORDER BY v.fk_year_year, v.fk_year_per, v.id_inv_val "; } @Override public ArrayList<SGridColumnView> createGridColumns() { ArrayList<SGridColumnView> columns = new ArrayList<>(); columns.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_CAL_YEAR, "v.fk_year_year", "Año")); columns.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_CAL_MONTH, "v.fk_year_per", "Mes")); columns.add(new SGridColumnView(SGridConsts.COL_TYPE_BOOL_M, "v.b_fin", "Terminada")); columns.add(new SGridColumnView(SGridConsts.COL_TYPE_BOOL_S, SDbConsts.FIELD_IS_DEL, SGridConsts.COL_TITLE_IS_DEL)); columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_USR, SDbConsts.FIELD_USER_INS_NAME, SGridConsts.COL_TITLE_USER_INS_NAME)); columns.add(new SGridColumnView(SGridConsts.COL_TYPE_DATE_DATETIME, SDbConsts.FIELD_USER_INS_TS, SGridConsts.COL_TITLE_USER_INS_TS)); columns.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_USR, SDbConsts.FIELD_USER_UPD_NAME, SGridConsts.COL_TITLE_USER_UPD_NAME)); columns.add(new SGridColumnView(SGridConsts.COL_TYPE_DATE_DATETIME, SDbConsts.FIELD_USER_UPD_TS, SGridConsts.COL_TITLE_USER_UPD_TS)); return columns; } @Override public void defineSuscriptions() { moSuscriptionsSet.add(mnGridType); moSuscriptionsSet.add(SModConsts.USRU_USR); } }
mit
runtimeverification/llvmmop
src/llvmmop/SpecCombiner.java
1645
package llvmmop; import java.util.ArrayList; import java.util.List; import llvmmop.parser.ast.ImportDeclaration; import llvmmop.parser.ast.MOPSpecFile; import llvmmop.parser.ast.PackageDeclaration; import llvmmop.parser.ast.mopspec.LLVMMOPSpec; public class SpecCombiner { static public MOPSpecFile process(ArrayList<MOPSpecFile> specFiles) throws MOPException{ PackageDeclaration pakage = null; List<ImportDeclaration> imports = new ArrayList<ImportDeclaration>(); List<LLVMMOPSpec> specList = new ArrayList<LLVMMOPSpec>(); for(MOPSpecFile specFile : specFiles){ //package decl PackageDeclaration pakage2 = specFile.getPakage(); if(pakage == null) pakage = pakage2; else { if(!pakage2.getName().getName().equals(pakage.getName().getName())) throw new MOPException("Specifications need to be in the same package to be combined."); } //imports List<ImportDeclaration> imports2 = specFile.getImports(); for(ImportDeclaration imp2 : imports2){ boolean included = false; for(ImportDeclaration imp : imports){ if(imp2.getName().getName().equals(imp.getName().getName())){ included = true; break; } } if(!included) imports.add(imp2); } //specs List<LLVMMOPSpec> specList2 = specFile.getSpecs(); for(LLVMMOPSpec spec2 : specList2){ boolean included = false; for(LLVMMOPSpec spec : specList){ if(spec2.getName().equals(spec.getName())){ included = true; break; } } if(!included) specList.add(spec2); } } return new MOPSpecFile(0, 0, pakage, imports, specList); } }
mit
powerofpi/FlowMiner
edu.iastate.flowminer.io/src/edu/iastate/flowminer/io/log/Log.java
1320
package edu.iastate.flowminer.io.log; import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import edu.iastate.flowminer.io.Activator; /** * Centralized logging for Eclipse plugins. * */ public class Log { public static final String pluginid = "edu.iastate.flowminer.io"; private static ILog log; static { BundleContext context = Activator.getContext(); if (context != null) { Bundle bundle = context.getBundle(); log = Platform.getLog(bundle); } } public static void error(String message, Throwable e) { log(Status.ERROR, message, e); } public static void warning(String message) { warning(message, null); } public static void warning(String message, Throwable e) { log(Status.WARNING, message, e); } public static void info(String message) { info(message, null); } public static void info(String message, Throwable e) { log(Status.INFO, message, e); } public static void log(int severity, String string, Throwable e) { if(log == null){ System.err.println(string + "\n" + e); }else{ IStatus status = new Status(severity, pluginid, string, e); log.log(status); } } }
mit
esuomi/algae
src/main/java/io/induct/algae/checksum/LuhnAlgorithm.java
1160
package io.induct.algae.checksum; import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; /** * Checksum validator using Luhn algorithm. * * @author EskoSuomi * @since 2014-10-18 * @see <a href="http://en.wikipedia.org/wiki/Luhn_algorithm">Luhn algorithm</a> */ public enum LuhnAlgorithm implements Checksum { INSTANCE; // TODO: Some enum thingy for describind security? Like LuhnAlgorithm.Validity.isCryptographicallySecure() @Override public boolean matches(String content, int checksum) { return calculate(content) == checksum; } @Override public int calculate(String input) { Preconditions.checkNotNull(input); String digitsStr = CharMatcher.DIGIT.retainFrom(input); int sum = 0; for (int i = 0; i < digitsStr.length(); i++) { int n = Integer.parseInt(digitsStr.substring(i, i + 1)); if (i % 2 != 0 && i % 1 == 0) { n <<= 1; if (n >= 10) { n = (n % 10) + (n / 10); } } sum += n; } return (sum * 9) % 10; } }
mit
VivaceVivo/cucumber-mod-DI
android/src/cucumber/api/android/CucumberInstrumentation.java
10891
package cucumber.api.android; import android.app.Activity; import android.app.Instrumentation; import android.content.Context; import android.os.Bundle; import android.os.Looper; import android.util.Log; import cucumber.api.CucumberOptions; import cucumber.runtime.*; import cucumber.runtime.Runtime; import cucumber.runtime.android.AndroidFormatter; import cucumber.runtime.android.AndroidObjectFactory; import cucumber.runtime.android.AndroidResourceLoader; import cucumber.runtime.android.DexClassFinder; import cucumber.runtime.ClassFinder; import cucumber.runtime.io.ResourceLoader; import cucumber.runtime.java.JavaBackend; import cucumber.runtime.java.ObjectFactory; import cucumber.runtime.model.*; import dalvik.system.DexFile; import gherkin.formatter.Formatter; import gherkin.formatter.Reporter; import gherkin.formatter.model.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class CucumberInstrumentation extends Instrumentation { public static final String REPORT_VALUE_ID = "InstrumentationTestRunner"; public static final String REPORT_KEY_NUM_TOTAL = "numtests"; public static final String REPORT_KEY_NUM_CURRENT = "current"; public static final String REPORT_KEY_NAME_CLASS = "class"; public static final String REPORT_KEY_NAME_TEST = "test"; public static final int REPORT_VALUE_RESULT_START = 1; public static final int REPORT_VALUE_RESULT_ERROR = -1; public static final int REPORT_VALUE_RESULT_FAILURE = -2; public static final String REPORT_KEY_STACK = "stack"; public static final String TAG = "cucumber-android"; private RuntimeOptions runtimeOptions; private ResourceLoader resourceLoader; private ClassLoader classLoader; private Runtime runtime; @Override public void onCreate(Bundle arguments) { super.onCreate(arguments); if (arguments == null) { throw new CucumberException("No arguments"); } Context context = getContext(); classLoader = context.getClassLoader(); String apkPath = context.getPackageCodePath(); ClassFinder classFinder = new DexClassFinder(newDexFile(apkPath)); Class<?> optionsAnnotatedClass = null; for (Class<?> clazz : classFinder.getDescendants(Object.class, context.getPackageName())) { if (clazz.isAnnotationPresent(CucumberOptions.class)) { Log.d(TAG, "Found CucumberOptions in class " + clazz.getName()); optionsAnnotatedClass = clazz; break; // We assume there is only one CucumberOptions annotated class. } } if (optionsAnnotatedClass == null) { throw new CucumberException("No CucumberOptions annotation"); } @SuppressWarnings("unchecked") RuntimeOptionsFactory factory = new RuntimeOptionsFactory(optionsAnnotatedClass, new Class[]{CucumberOptions.class}); runtimeOptions = factory.create(); resourceLoader = new AndroidResourceLoader(context); List<Backend> backends = new ArrayList<Backend>(); ObjectFactory delegateObjectFactory = JavaBackend.loadObjectFactory(classFinder); AndroidObjectFactory objectFactory = new AndroidObjectFactory(delegateObjectFactory, this); backends.add(new JavaBackend(objectFactory, classFinder)); runtime = new Runtime(resourceLoader, classLoader, backends, runtimeOptions); start(); } private DexFile newDexFile(String apkPath) { try { return new DexFile(apkPath); } catch (IOException e) { throw new CucumberException("Failed to open " + apkPath); } } @Override public void onStart() { Looper.prepare(); List<CucumberFeature> cucumberFeatures = runtimeOptions.cucumberFeatures(resourceLoader); int numScenarios = 0; // How many individual scenarios (test cases) exist - is there a better way to do this? // This is only relevant for reporting back to the Instrumentation and does not affect // execution. for (CucumberFeature feature : cucumberFeatures) { for (CucumberTagStatement statement : feature.getFeatureElements()) { if (statement instanceof CucumberScenario) { numScenarios++; } else if (statement instanceof CucumberScenarioOutline) { for (CucumberExamples examples : ((CucumberScenarioOutline) statement).getCucumberExamplesList()) { for (ExamplesTableRow row : examples.getExamples().getRows()) { numScenarios++; } } numScenarios--; // subtract table header } } } AndroidReporter reporter = new AndroidReporter(numScenarios); runtimeOptions.getFormatters().clear(); runtimeOptions.getFormatters().add(reporter); for (CucumberFeature cucumberFeature : cucumberFeatures) { Formatter formatter = runtimeOptions.formatter(classLoader); cucumberFeature.run(formatter, reporter, runtime); } Formatter formatter = runtimeOptions.formatter(classLoader); formatter.done(); printSummary(); formatter.close(); finish(Activity.RESULT_OK, new Bundle()); } private void printSummary() { for (Throwable t : runtime.getErrors()) { Log.e(TAG, t.toString()); } for (String s : runtime.getSnippets()) { Log.w(TAG, s); } } /** * This class reports the current test-state back to the framework. * It also wraps the AndroidFormatter to intercept important callbacks. */ private class AndroidReporter implements Formatter, Reporter { private final AndroidFormatter formatter; private final Bundle resultTemplate; private Bundle testResult; private int scenarioCounter; private int resultCode; // aka exit status private Feature currentFeature; private Step currentStep; public AndroidReporter(int numTests) { formatter = new AndroidFormatter(TAG); resultTemplate = new Bundle(); resultTemplate.putString(Instrumentation.REPORT_KEY_IDENTIFIER, REPORT_VALUE_ID); resultTemplate.putInt(REPORT_KEY_NUM_TOTAL, numTests); } @Override public void uri(String uri) { formatter.uri(uri); } @Override public void feature(Feature feature) { currentFeature = feature; formatter.feature(feature); } @Override public void background(Background background) { reportLastResult(); formatter.background(background); beginScenario(background); } @Override public void scenario(Scenario scenario) { reportLastResult(); formatter.scenario(scenario); beginScenario(scenario); } @Override public void scenarioOutline(ScenarioOutline scenarioOutline) { reportLastResult(); formatter.scenarioOutline(scenarioOutline); beginScenario(scenarioOutline); } @Override public void examples(Examples examples) { formatter.examples(examples); } @Override public void step(Step step) { currentStep = step; formatter.step(step); } @Override public void syntaxError(String state, String event, List<String> legalEvents, String uri, Integer line) { formatter.syntaxError(state, event, legalEvents, uri, line); } @Override public void eof() { reportLastResult(); formatter.eof(); } @Override public void done() { formatter.done(); } @Override public void close() { formatter.close(); } @Override public void embedding(String mimeType, byte[] data) { } @Override public void write(String text) { } @Override public void before(Match match, Result result) { } @Override public void after(Match match, Result result) { } @Override public void match(Match match) { } private void beginScenario(DescribedStatement scenario) { if (testResult == null) { String testClass = String.format("%s %s", currentFeature.getKeyword(), currentFeature.getName()); String testName = String.format("%s %s", scenario.getKeyword(), scenario.getName()); testResult = new Bundle(resultTemplate); testResult.putString(REPORT_KEY_NAME_CLASS, testClass); testResult.putString(REPORT_KEY_NAME_TEST, testName); testResult.putInt(REPORT_KEY_NUM_CURRENT, ++scenarioCounter); testResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, String.format("\n%s:", testClass)); sendStatus(REPORT_VALUE_RESULT_START, testResult); resultCode = 0; } } @Override public void result(Result result) { if (result.getError() != null) { // If the result contains an error, report a failure. testResult.putString(REPORT_KEY_STACK, result.getErrorMessage()); resultCode = REPORT_VALUE_RESULT_FAILURE; testResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, result.getErrorMessage()); } else if (result.getStatus().equals("undefined")) { // There was a missing step definition, report an error. List<String> snippets = runtime.getSnippets(); String report = String.format("Missing step-definition\n\n%s\nfor step '%s'", snippets.get(snippets.size() - 1), currentStep.getName()); testResult.putString(REPORT_KEY_STACK, report); resultCode = REPORT_VALUE_RESULT_ERROR; testResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, String.format("Missing step-definition: %s", currentStep.getName())); } } private void reportLastResult() { if (testResult != null && !testResult.isEmpty() && scenarioCounter != 0) { if (resultCode == 0) { testResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, "."); } sendStatus(resultCode, testResult); testResult = null; } } } }
mit
VoltDB/voltdb-hadoop-extension
voltdb-hive/src/main/java/org/voltdb/hive/VoltSerdeException.java
1646
/* This file is part of VoltDB. * Copyright (C) 2008-2018 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb.hive; import org.apache.hadoop.hive.serde2.SerDeException; public class VoltSerdeException extends SerDeException { private static final long serialVersionUID = 5837394515987837570L; public VoltSerdeException() { } public VoltSerdeException(String message) { super(message); } public VoltSerdeException(Throwable cause) { super(cause); } public VoltSerdeException(String message, Throwable cause) { super(message, cause); } }
mit
cleyssonazevedo/Rede-Social
src/br/com/social/model/amigos/Amigos.java
1125
package br.com.social.model.amigos; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ForeignKey; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import br.com.social.model.contato.Contato; @Entity public class Amigos { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_contato", foreignKey = @ForeignKey(name = "fk_amigos"), unique = true) private Contato contato; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "id_amigo", foreignKey = @ForeignKey(name = "fk_amigos"), unique = true) private Contato amigo; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Contato getContato() { return contato; } public void setContato(Contato contato) { this.contato = contato; } public Contato getAmigo() { return amigo; } public void setAmigo(Contato amigo) { this.amigo = amigo; } }
mit
OpenMods/OpenPeripheral
src/main/java/openperipheral/api/peripheral/Volatile.java
475
package openperipheral.api.peripheral; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Peripheral created for types marked with this annotation will not be cached (i.e. one will be created on any call). * * @deprecated No longer implemented */ @Deprecated @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Volatile { }
mit
mdnu/core
src/corejava/parallel/Op.java
69
package corejava.parallel; public interface Op { String runOp(); }
mit
Hamz-a/MyCTFWriteUps
seccon_2015/Reverse-Engineering Android APK 1/files/source/src/android/support/annotation/UiThread.java
306
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package android.support.annotation; import java.lang.annotation.Annotation; public interface UiThread extends Annotation { }
mit
enlo/jmt-projects
jmt-core/src/main/java/info/naiv/lab/java/jmt/ComparableComparator.java
2720
/* * The MIT License * * Copyright 2015 enlo. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package info.naiv.lab.java.jmt; import java.io.Serializable; import java.util.Comparator; import javax.annotation.concurrent.ThreadSafe; /** * 比較可能な型Tのオブジェクトの{@link Comparator}. * <ol> * <li>o1 == o2 なら 0. * <li>o1 == null なら -1. * <li>o2 == null なら 1. * <li>それ以外なら o1.compareTo(o2) を戻す. * </ol> * * @author enlo * @param <T> 型T * */ @ThreadSafe public class ComparableComparator<T extends Comparable<T>> implements Comparator<T>, Serializable { /** * */ public static final ComparableComparator INSTANCE = new ComparableComparator(); private static final long serialVersionUID = 1L; @Override public int compare(T o1, T o2) { if (o1 == o2) { return 0; } else if (o1 == null) { return -1; } else if (o2 == null) { return 1; } else { return doCompare(o1, o2); } } /** * 値の小さなほうを取得する. * * @param o1 * @param o2 * @return */ public final T min(T o1, T o2) { if (o1 == o2) { return o1; } else if (o1 == null) { return o2; } else if (o2 == null) { return o1; } else { return doCompare(o1, o2) < 0 ? o1 : o2; } } /** * 比較メソッド. * * @param o1 * @param o2 * @return */ protected int doCompare(T o1, T o2) { return o1.compareTo(o2); } }
mit
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/annotations/APIMethod.java
249
package net.nemerosa.ontrack.model.annotations; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface APIMethod { String value(); String description() default ""; }
mit
Linecommander/Simly
source/syntaxtree/NodeListInterface.java
584
// // Generated by JTB 1.3.2 // package Simly.syntaxtree; /** * The interface which NodeList, NodeListOptional, and NodeSequence * implement. */ public interface NodeListInterface extends Node { public void addNode(Node n); public Node elementAt(int i); public java.util.Enumeration<Node> elements(); public int size(); public void accept(Simly.visitor.Visitor v); public <R,A> R accept(Simly.visitor.GJVisitor<R,A> v, A argu); public <R> R accept(Simly.visitor.GJNoArguVisitor<R> v); public <A> void accept(Simly.visitor.GJVoidVisitor<A> v, A argu); }
mit
mmazi/rescu
src/test/java/si/mazi/rescu/InvocationDigestTest.java
8233
/* * Copyright (C) 2021 Matija Mazi * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package si.mazi.rescu; import com.fasterxml.jackson.databind.ObjectMapper; import org.testng.annotations.Test; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; public class InvocationDigestTest { private final RequestWriterResolver requestWriterResolver = RequestWriterResolver.createDefault(new ObjectMapper()); @Test public void shouldDigestUrlInFormParam() throws Exception { RestInvocation restInvocation = getRestInvocation( "digestUrlInFormParam", new Object[]{"v1", new UrlDigest()}, String.class, UrlDigest.class); assertThat(restInvocation.getRequestBody()).contains("signature=_50_"); // https://example.com/api/digestUrlInFormParam?q1=v1 } @Test public void shouldDigestUrlInHeader() throws Exception { RestInvocation restInvocation = getRestInvocation( "digestUrlInHeader", new Object[]{"v1", new UrlDigest()}, String.class, UrlDigest.class); assertThat(restInvocation.getHttpHeadersFromParams()).contains(entry("signature", "_47_")); // https://example.com/api/digestUrlInHeader?q1=v1 } @Test public void shouldDigestBodyInHeader() throws Exception { RestInvocation restInvocation = getRestInvocation( "digestBodyInHeader", new Object[]{"This method body is 39 characters long.", new BodyDigest()}, String.class, BodyDigest.class); assertThat(restInvocation.getHttpHeadersFromParams()).contains(entry("signature", "_39_")); } @Test public void shouldDigestBodyInQueryParam() throws Exception { RestInvocation restInvocation = getRestInvocation( "digestBodyInQueryParam", new Object[]{"This method body is 39 characters long.", new BodyDigest()}, String.class, BodyDigest.class); assertThat(restInvocation.getInvocationUrl()).contains("signature=_39_"); } @Test public void shouldDigestHeadersInFormParam() throws Exception { RestInvocation restInvocation = getRestInvocation( "digestHeadersInFormParam", new Object[]{"first", "second", new HeaderDigest()}, String.class, String.class, HeaderDigest.class); assertThat(restInvocation.getRequestBody()).contains("signature=_2_"); } @Test public void shouldDigestHeadersInQueryParam() throws Exception { RestInvocation restInvocation = getRestInvocation( "digestHeadersInQueryParam", new Object[]{"first", "second", new HeaderDigest()}, String.class, String.class, HeaderDigest.class); assertThat(restInvocation.getInvocationUrl()).contains("signature=_2_"); } @Test public void shouldDigestUrlInPlainBody() throws Exception { RestInvocation restInvocation = getRestInvocation( "digestUrlInPlainBody", new Object[]{"v1", new UrlDigest()}, String.class, UrlDigest.class); assertThat(restInvocation.getRequestBody()).isEqualTo("_50_"); // https://example.com/api/digestUrlInPlainBody?q1=v1 } private RestInvocation getRestInvocation(String methodName, Object[] invocationArguments, Class<?>... methodParamTypes) throws NoSuchMethodException { return RestInvocation.create(requestWriterResolver, RestMethodMetadata.create( DigestService.class.getDeclaredMethod(methodName, methodParamTypes), "https://example.com/", "api"), invocationArguments, new HashMap<>() ); } private static String wrapInUnderscores(int number) { return String.format("_%d_", number); } /** Digests the body by returning its length between underscores. */ static class BodyDigest implements ParamsDigest { @Override public String digestParams(RestInvocation restInvocation) { return wrapInUnderscores(restInvocation.getRequestBody().length()); } } /** Digests the URL by returning its length between underscores. */ static class UrlDigest implements ParamsDigest { @Override public String digestParams(RestInvocation restInvocation) { return wrapInUnderscores(restInvocation.getInvocationUrl().length()); } } /** Digests the headers by returning their count between underscores. */ static class HeaderDigest implements ParamsDigest { @Override public String digestParams(RestInvocation restInvocation) { return wrapInUnderscores(restInvocation.getHttpHeadersFromParams().size()); } } @SuppressWarnings("RestParamTypeInspection") @Path("api") public interface DigestService { @POST @Path("digestUrlInHeader") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) String digestUrlInHeader( @QueryParam("q1") String q1, @HeaderParam("signature") UrlDigest digest ); @POST @Path("digestUrlInFormParam") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) String digestUrlInFormParam( @QueryParam("q1") String q1, @FormParam("signature") UrlDigest digest ); @POST @Path("digestBodyInHeader") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.TEXT_PLAIN) String digestBodyInHeader( String body, @HeaderParam("signature") BodyDigest digest ); @POST @Path("digestBodyInQueryParam") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.TEXT_PLAIN) String digestBodyInQueryParam( String body, @QueryParam("signature") BodyDigest digest ); @POST @Path("digestHeadersInFormParam") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) String digestHeadersInFormParam( @HeaderParam("h1") String h1, @HeaderParam("h2") String h2, @FormParam("signature") HeaderDigest digest ); @POST @Path("digestHeadersInQueryParam") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) String digestHeadersInQueryParam( @HeaderParam("h1") String h1, @HeaderParam("h2") String h2, @QueryParam("signature") HeaderDigest digest ); @POST @Path("digestUrlInPlainBody") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.TEXT_PLAIN) String digestUrlInPlainBody( @QueryParam("q1") String q1, UrlDigest digest ); } }
mit
Activeghost/Elements
src/EPI/Stacks/Stack.java
1111
package EPI.Stacks; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; class ElementWithCachedMax<T> { T element; T max; T min; } /** * Stack class */ public class Stack<T> { private final Deque<ElementWithCachedMax<T>> _deque; private Comparator<T> _comparator; private T _max; private T _min; public Stack(Comparator<T> comparator) { _comparator = comparator; _deque = new LinkedList<>(); } public void push(T item) { ElementWithCachedMax<T> wrappedItem = new ElementWithCachedMax<>(); if(_comparator.compare(_max, item) == 1) { _max = item; } if(_comparator.compare(_min, item) == -1) { _min = item; } wrappedItem.max = _max; wrappedItem.min = _min; _deque.push(wrappedItem); } public T pop() { ElementWithCachedMax<T> item = _deque.pop(); _max = item.max; _min = item.min; return item.element; } public int size() { return _deque.size(); } public T min() { return _min; } public T max() { return _max; } public boolean isEmpty() { return _deque.isEmpty(); } }
mit
pascoej/ajario
src/main/java/me/pascoej/ajario/gui/views/MessageView.java
1911
package me.pascoej.ajario.gui.views; import me.pascoej.ajario.gui.ClientGUI; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; /** * Created by john on 6/15/15. */ public class MessageView extends View { private long startTime = -1; private final ClientGUI clientGUI; private final long duration; private final String message; public MessageView(ClientGUI clientGUI, String message, long duration) { this.clientGUI = clientGUI; this.message = message; this.duration = duration; } @Override public void render(GameContainer gc, Graphics g) { long currentTime = System.currentTimeMillis(); if (startTime == -1) { startTime = currentTime; } long timeLeft = duration - (currentTime - startTime); if (timeLeft <= 0) { clientGUI.removeView(this); return; } double opacityModifier = 1; if (timeLeft < 3000) { opacityModifier = timeLeft / 3000.0; } g.setColor(new Color(150, 150, 150, (int) (175 * opacityModifier))); int width = gc.getWidth(); int borderX = 50; int borderY = 5; int padding = 10; int notifWidth = width - (2 * borderX); int notifHeight = g.getFont().getHeight("|") + 2 * padding; int messageWidth = g.getFont().getWidth(message); int centerX = width / 2; int startMessageX = centerX - (messageWidth / 2); g.fillRoundRect(borderX, borderY, notifWidth, notifHeight, 4); g.setColor(new Color(0, 255, 0, (int) (200 * opacityModifier))); g.drawString(message, startMessageX, borderY + padding); } @Override public boolean shouldDraw() { return true; } @Override public boolean isAcceptingInput() { return false; } }
mit
kevinchandler/catwars
android/app/src/main/java/com/catwars/MainActivity.java
2281
package com.catwars; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import com.facebook.react.LifecycleState; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactRootView; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler { private ReactInstanceManager mReactInstanceManager; private ReactRootView mReactRootView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mReactRootView = new ReactRootView(this); mReactInstanceManager = ReactInstanceManager.builder() .setApplication(getApplication()) .setBundleAssetName("index.android.bundle") .setJSMainModuleName("index.android") .addPackage(new MainReactPackage()) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .build(); mReactRootView.startReactApplication(mReactInstanceManager, "CatWars", null); setContentView(mReactRootView); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) { mReactInstanceManager.showDevOptionsDialog(); return true; } return super.onKeyUp(keyCode, event); } @Override public void onBackPressed() { if (mReactInstanceManager != null) { mReactInstanceManager.onBackPressed(); } else { super.onBackPressed(); } } @Override public void invokeDefaultOnBackPressed() { super.onBackPressed(); } @Override protected void onPause() { super.onPause(); if (mReactInstanceManager != null) { mReactInstanceManager.onPause(); } } @Override protected void onResume() { super.onResume(); if (mReactInstanceManager != null) { mReactInstanceManager.onResume(this, this); } } }
mit
wallner/connector4java-integration-tests
src/test/java/org/osiam/client/ScopeIT.java
9441
package org.osiam.client; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.osiam.client.connector.OsiamConnector; import org.osiam.client.exception.ForbiddenException; import org.osiam.client.oauth.AccessToken; import org.osiam.client.oauth.GrantType; import org.osiam.client.oauth.Scope; import org.osiam.client.query.Query; import org.osiam.client.update.UpdateGroup; import org.osiam.client.update.UpdateUser; import org.osiam.resources.scim.Group; import org.osiam.resources.scim.User; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/context.xml") @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class}) @DatabaseSetup("/database_seed.xml") public class ScopeIT { static final private String VALID_USER_ID = "834b410a-943b-4c80-817a-4465aed037bc"; static final private String VALID_GROUP_ID = "69e1a5dc-89be-4343-976c-b5541af249f4"; protected static final String AUTH_ENDPOINT_ADDRESS = "http://localhost:8180/osiam-auth-server"; protected static final String RESOURCE_ENDPOINT_ADDRESS = "http://localhost:8180/osiam-resource-server"; private static String CLIENT_ID = "example-client"; private static String CLIENT_SECRET = "secret"; private OsiamConnector oConnector; private AccessToken accessToken; private OsiamConnector.Builder oConBuilder; @Before public void setUp() throws Exception { oConBuilder = new OsiamConnector.Builder(). setAuthServiceEndpoint(AUTH_ENDPOINT_ADDRESS). setResourceEndpoint(RESOURCE_ENDPOINT_ADDRESS). setClientId(CLIENT_ID). setClientSecret(CLIENT_SECRET). setGrantType(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS). setUserName("marissa"). setPassword("koala") ; } @Test (expected = ForbiddenException.class) public void try_to_retrieve_user_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToGetUser(); } @Test (expected = ForbiddenException.class) public void try_to_retrieve_group_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToGetGroup(); } @Test (expected = ForbiddenException.class) public void try_to_retrieve_all_users_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToGetAllUsers(); } @Test (expected = ForbiddenException.class) public void try_to_retrieve_all_groups_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToGetAllGroups(); } @Test(expected = ForbiddenException.class) public void try_to_create_user_raises_exception(){ setInvalidScope(); retrieveAccessToken(); createTestUser(); } @Test(expected = ForbiddenException.class) public void try_to_create_group_raises_exception(){ setInvalidScope(); retrieveAccessToken(); createTestGroup(); } @Test (expected = ForbiddenException.class) public void try_to_get_actual_user_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToGetMe(); } @Test (expected = ForbiddenException.class) public void try_to_update_user_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToUpdateUser(); } @Test (expected = ForbiddenException.class) public void try_to_update_group_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToUpdateGroup(); } @Test (expected = ForbiddenException.class) public void try_to_search_for_user_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToSearchForUsers(); } @Test (expected = ForbiddenException.class) public void try_to_search_for_group_raises_exception(){ setInvalidScope(); retrieveAccessToken(); tryToSearchForGroups(); } @Test (expected = ForbiddenException.class) public void try_to_delete_user_raises_exception(){ setInvalidScopeForDeleting(); retrieveAccessToken(); oConnector.deleteUser(VALID_USER_ID, accessToken); } @Test (expected = ForbiddenException.class) public void try_to_delete_group_raises_exception(){ setInvalidScopeForDeleting(); retrieveAccessToken(); oConnector.deleteGroup(VALID_GROUP_ID, accessToken); } @Test public void try_to_retrieve_user(){ oConnector = oConBuilder.setScope(Scope.GET).build(); retrieveAccessToken(); tryToGetUser(); } @Test public void try_to_retrieve_group(){ oConnector = oConBuilder.setScope(Scope.GET).build(); retrieveAccessToken(); tryToGetGroup(); } @Test public void try_to_retrieve_all_users(){ oConnector = oConBuilder.setScope(Scope.GET).build(); retrieveAccessToken(); tryToGetAllUsers(); } @Test public void try_to_retrieve_all_groups(){ oConnector = oConBuilder.setScope(Scope.GET).build(); retrieveAccessToken(); tryToGetAllGroups(); } @Test public void try_to_create_user(){ oConnector = oConBuilder.setScope(Scope.POST).build(); retrieveAccessToken(); createTestUser(); } @Test public void try_to_create_group(){ oConnector = oConBuilder.setScope(Scope.POST).build(); retrieveAccessToken(); createTestGroup(); } @Test @Ignore("/User/me is no longer available and '/me' is not yet supported by connector") public void try_to_get_actual_user(){ oConnector = oConBuilder.setScope(Scope.GET).build(); retrieveAccessToken(); tryToGetMe(); } @Test public void try_to_update_user(){ oConnector = oConBuilder.setScope(Scope.PATCH).build(); retrieveAccessToken(); tryToUpdateUser(); } @Test public void try_to_update_group(){ oConnector = oConBuilder.setScope(Scope.PATCH).build(); retrieveAccessToken(); tryToUpdateGroup(); } @Test public void try_to_search_for_user(){ oConnector = oConBuilder.setScope(Scope.GET).build(); retrieveAccessToken(); tryToSearchForUsers(); } @Test public void try_to_search_for_group(){ oConnector = oConBuilder.setScope(Scope.GET).build(); retrieveAccessToken(); tryToSearchForGroups(); } @Test public void try_to_delete_user(){ oConnector = oConBuilder.setScope(Scope.DELETE, Scope.POST).build(); retrieveAccessToken(); String newUserId = createTestUser(); oConnector.deleteUser(newUserId, accessToken); } @Test public void try_to_delete_group(){ oConnector = oConBuilder.setScope(Scope.DELETE).build(); retrieveAccessToken(); oConnector.deleteGroup(VALID_GROUP_ID, accessToken); } @Test @Ignore("/User/me is no longer available and '/me' is not yet supported by connector") public void try_to_get_actual_user_with_string_scope(){ oConnector = oConBuilder.setScope("GET").build(); retrieveAccessToken(); tryToGetMe(); } private String createTestUser(){ User user = new User.Builder("testUSer0065").build(); return oConnector.createUser(user, accessToken).getId(); } private void createTestGroup(){ Group group = new Group.Builder().setDisplayName("test").build(); oConnector.createGroup(group, accessToken); } private void setInvalidScope(){ oConnector = oConBuilder.setScope(Scope.DELETE).build(); } private void setInvalidScopeForDeleting(){ oConnector = oConBuilder.setScope(Scope.GET).build(); } private void retrieveAccessToken(){ accessToken = oConnector.retrieveAccessToken(); } private void tryToGetUser(){ oConnector.getUser(VALID_USER_ID, accessToken); } private void tryToGetGroup(){ oConnector.getGroup(VALID_GROUP_ID, accessToken); } private void tryToGetAllUsers(){ oConnector.getAllUsers(accessToken); } private void tryToGetAllGroups(){ oConnector.getAllGroups(accessToken); } private void tryToGetMe(){ oConnector.getMe(accessToken); } private void tryToUpdateUser(){ UpdateUser updateUser = new UpdateUser.Builder().updateUserName("newName").updateActive(false).build(); oConnector.updateUser(VALID_USER_ID, updateUser, accessToken); } private void tryToUpdateGroup(){ UpdateGroup updateGroup = new UpdateGroup.Builder().updateDisplayName("irrelevant").build(); oConnector.updateGroup(VALID_GROUP_ID, updateGroup, accessToken); } private void tryToSearchForUsers(){ Query query = new Query.Builder(User.class).setStartIndex(0).build(); oConnector.searchUsers(query, accessToken); } private void tryToSearchForGroups(){ Query query = new Query.Builder(Group.class).setStartIndex(0).build(); oConnector.searchUsers(query, accessToken); } }
mit
carsonreinke/mozu-java-sdk
src/main/java/com/mozu/api/contracts/commerceruntime/carts/CartItemCollection.java
1229
/** * This code was auto-generated by a tool. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.contracts.commerceruntime.carts; import java.util.List; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.joda.time.DateTime; import com.mozu.api.contracts.commerceruntime.carts.CartItem; /** * Collection of items in a cart. */ @JsonIgnoreProperties(ignoreUnknown = true) public class CartItemCollection implements Serializable { // Default Serial Version UID private static final long serialVersionUID = 1L; /** * The number of results listed in the query collection, represented by a signed 64-bit (8-byte) integer. This value is system-supplied and read-only. */ protected Long totalCount; public Long getTotalCount() { return this.totalCount; } public void setTotalCount(Long totalCount) { this.totalCount = totalCount; } /** * An array list of objects in the returned collection. */ protected List<CartItem> items; public List<CartItem> getItems() { return this.items; } public void setItems(List<CartItem> items) { this.items = items; } }
mit
unchartedsoftware/aperture-tiles
binning-utilities/src/test/java/com/oculusinfo/binning/io/impl/ZipResourcePyramidSourceTest.java
3050
/* * Copyright (c) 2014 Oculus Info Inc. * http://www.oculusinfo.com/ * * Released under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oculusinfo.binning.io.impl; import com.oculusinfo.binning.TileIndex; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.InputStream; import static org.junit.Assert.fail; public class ZipResourcePyramidSourceTest { @Test public void test() { ZipArchiveOutputStream zos = null; File archive; String filename = ""; try { archive = File.createTempFile("test.", ".zip", null); archive.deleteOnExit(); filename = archive.getAbsolutePath(); zos = new ZipArchiveOutputStream(archive); for(int z=0; z<3; z++){ for(int x=0; x<Math.pow(2, z); x++){ for(int y=0; y<Math.pow(2, z); y++){ ZipArchiveEntry entry = new ZipArchiveEntry(getDummyFile(), "test/tiles/" +z+ "/" +x+ "/" +y+ ".dummy"); zos.putArchiveEntry(entry); } } } ZipArchiveEntry entry = new ZipArchiveEntry(getDummyFile(), "test/metadata.json"); zos.putArchiveEntry(entry); zos.closeArchiveEntry(); zos.close(); zos=null; } catch (IOException e) { fail(e.getMessage()); } try { ZipResourcePyramidSource src = new ZipResourcePyramidSource(filename, "dummy"); TileIndex tileDef = new TileIndex(0, 0, 0, 1, 1); InputStream is = src.getSourceTileStream("test", tileDef); Assert.assertTrue(is!=null); tileDef = new TileIndex(2, 3, 3, 1, 1); is = src.getSourceTileStream("test", tileDef); Assert.assertTrue(is!=null); is = src.getSourceMetaDataStream("test"); Assert.assertTrue(is!=null); } catch (IOException e) { fail(e.getMessage()); } } private File getDummyFile() throws IOException{ return File.createTempFile("dummy", null); } }
mit
Syncano/syncano-android-demo
Eclipse/SyncanoLib/src/com/syncano/android/lib/modules/apikeys/ResponseApiKeyStartSession.java
891
package com.syncano.android.lib.modules.apikeys; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.syncano.android.lib.modules.Response; public class ResponseApiKeyStartSession extends Response { /** Session id */ @Expose @SerializedName(value = "session_id") private String sessionId; /** UUID */ @Expose private String uuid; /** * @return session id for current session */ public String getSessionId() { return sessionId; } /** * Sets new session id * * @param sessionId * new session id */ public void setSessionId(String sessionId) { this.sessionId = sessionId; } /** * @return UUID for response */ public String getUuid() { return uuid; } /** * Sets new UUID * * @param uuid * new UUID */ public void setUuid(String uuid) { this.uuid = uuid; } }
mit
CS2103JAN2017-T09-B1/main
src/main/java/seedu/today/commons/events/ui/JumpToListRequestEvent.java
446
package seedu.today.commons.events.ui; import seedu.today.commons.events.BaseEvent; /** * Indicates a request to jump to the list of tasks */ public class JumpToListRequestEvent extends BaseEvent { public final String targetIndex; public JumpToListRequestEvent(String targetIndex) { this.targetIndex = targetIndex; } @Override public String toString() { return this.getClass().getSimpleName(); } }
mit
bkromhout/Ruqus
sample/src/main/java/com/bkromhout/ruqus/sample/models/Person.java
2077
package com.bkromhout.ruqus.sample.models; import com.bkromhout.ruqus.Hide; import com.bkromhout.ruqus.Queryable; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.Ignore; @Queryable(name = "Person") public class Person extends RealmObject { private static final String TEST = "TEST"; private String name; private int age; private Dog dog; private RealmList<Cat> cats; @Ignore private int tempReference; @Hide private long id; public Person() {} public Person(String name, int age, Dog dog, long id) { this.name = name; this.age = age; this.dog = dog; this.cats = new RealmList<>(); this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } public RealmList<Cat> getCats() { return cats; } public void setCats(RealmList<Cat> cats) { this.cats = cats; } public int getTempReference() { return tempReference; } public void setTempReference(int tempReference) { this.tempReference = tempReference; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String toString(String indent) { String s = indent + "Name: " + name + ",\n" + indent + "Age: " + age + ",\n" + indent + "Dog: {" + (dog != null ? "\n" + dog.toString(indent + "\t") + indent : "") + "},\n" + indent + "Cats: ["; if (!cats.isEmpty()) { s += "\n"; for (Cat cat : cats) s += indent + "\t" + "{\n" + cat.toString(indent + "\t") + indent + "\t" + "},\n"; s += indent; } s += "]\n"; return s; } }
mit
AURIN/online-whatif
src/main/java/au/org/aurin/wif/controller/ProjectController.java
56527
package au.org.aurin.wif.controller; import static au.org.aurin.wif.io.RestAPIConstants.HEADER_USER_ID_KEY; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import org.geotools.filter.text.cql2.CQLException; import org.geotools.referencing.CRS; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.validation.BindException; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.vividsolutions.jts.io.ParseException; import au.org.aurin.wif.exception.config.GeoServerConfigException; import au.org.aurin.wif.exception.config.InvalidEntityIdException; import au.org.aurin.wif.exception.config.ParsingException; import au.org.aurin.wif.exception.config.WifInvalidConfigException; import au.org.aurin.wif.exception.io.DataStoreCreationException; import au.org.aurin.wif.exception.io.DataStoreUnavailableException; import au.org.aurin.wif.exception.io.DatabaseFailedException; import au.org.aurin.wif.exception.io.MiddlewarePersistentException; import au.org.aurin.wif.exception.io.WifIOException; import au.org.aurin.wif.exception.validate.IncompleteSuitabilityLUConfigException; import au.org.aurin.wif.exception.validate.InvalidFFNameException; import au.org.aurin.wif.exception.validate.InvalidLabelException; import au.org.aurin.wif.exception.validate.ProjectNotReadyException; import au.org.aurin.wif.exception.validate.ProjectSetupFailedException; import au.org.aurin.wif.exception.validate.UAZAlreadyCreatedException; import au.org.aurin.wif.exception.validate.WifInvalidInputException; import au.org.aurin.wif.io.GeodataFinder; import au.org.aurin.wif.io.parsers.ProjectCouchParser; import au.org.aurin.wif.model.WifProject; import au.org.aurin.wif.model.allocation.AllocationConfigs; import au.org.aurin.wif.model.allocation.AllocationLU; import au.org.aurin.wif.model.allocation.ColorALU; import au.org.aurin.wif.model.reports.ProjectReport; import au.org.aurin.wif.model.suitability.SuitabilityConfig; import au.org.aurin.wif.repo.allocation.AllocationConfigsDao; import au.org.aurin.wif.svc.AllocationLUService; import au.org.aurin.wif.svc.AsyncProjectService; import au.org.aurin.wif.svc.ProjectService; import au.org.aurin.wif.svc.WifKeys; import au.org.aurin.wif.svc.report.ReportService; import au.org.aurin.wif.svc.suitability.FactorService; /** * The Class ProjectController. */ @Controller @RequestMapping(OWIURLs.PROJECT_SVC_URI) public class ProjectController { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory .getLogger(ProjectController.class); /** The project service. */ @Resource private ProjectService projectService; /** The async project service. */ @Resource private AsyncProjectService asyncProjectService; /** The geodata finder. */ @Resource private GeodataFinder geodataFinder; /** The report service. */ @Autowired private ReportService reportService; @Autowired private ProjectCouchParser projectParser; @Autowired private AllocationConfigsDao AllocationConfigsDao; /** The projects pool. */ private final HashMap<String, Future<String>> projectsPool = new HashMap<String, Future<String>>(); /** The uploads pool. */ private final HashMap<String, Future<String>> uploadsPool = new HashMap<String, Future<String>>(); @Resource private AllocationLUService allocationLUService; /** the service. */ @Resource private FactorService factorService; /** * Gets the project revision. * * @param roleId * the role id * @param id * the id * @return the project revision * @throws WifInvalidInputException * the wif invalid input exception * @throws WifInvalidConfigException * the wif invalid config exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/revision", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody String getProjectRevision( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException, WifInvalidConfigException { final String msg = "getProjectRevision failed: {}"; try { return projectService.getProjectNoMapping(id).getRevision(); } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } } /** * Gets the zipfile of the project. * * @param roleId * @param id * @param response * @return * @throws WifInvalidConfigException * @throws WifInvalidInputException * @throws DatabaseFailedException */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/zipUAZ", produces = "application/zip") @ResponseStatus(HttpStatus.OK) @ResponseBody public FileSystemResource getZipUAZ( // public byte[] getZipUAZ( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id, final HttpServletResponse response) throws WifInvalidConfigException, WifInvalidInputException, DatabaseFailedException { LOGGER.info("*******>> getProjectZipUAZ request for project id ={}", id); final String msg = "getProject failed: {}"; try { final File zipFile = projectService.getProjectZipUAZ(id); final FileSystemResource result = new FileSystemResource(zipFile); response.setContentType("application/zip"); final byte[] bytem = org.springframework.util.FileCopyUtils .copyToByteArray(zipFile); response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFile.getName() + "\""); response.setContentLength(bytem.length); LOGGER.info("Returning zip file"); return result; // return bytem; } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } catch (final IOException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } } /** * Gets the project. * * @param roleId * the role id * @param id * the id * @return the project * @throws WifInvalidConfigException * the wif invalid config exception * @throws WifInvalidInputException * the wif invalid input exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody WifProject getProject(@RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidConfigException, WifInvalidInputException { LOGGER.info("*******>> getProject request for project id ={}", id); final String msg = "getProject failed: {}"; try { return projectService.getProject(id); } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } } /** * Gets the all projects. * * @param roleId * the role id * @return the all projects * @throws WifInvalidConfigException * the wif invalid config exception * @throws WifInvalidInputException * the wif invalid input exception * @throws NoSuchAuthorityCodeException * the no such authority code exception * @throws FactoryException * the factory exception * @throws TransformException * the transform exception * @throws ParseException * the parse exception * @throws CQLException * the cQL exception */ @RequestMapping(method = RequestMethod.GET, value = "/") @ResponseStatus(HttpStatus.OK) @SuppressWarnings({ "unchecked", "rawtypes" }) public @ResponseBody List<WifProject> getAllProjects( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, final HttpServletResponse response) throws WifInvalidConfigException, WifInvalidInputException, NoSuchAuthorityCodeException, FactoryException, TransformException, ParseException, CQLException { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE"); response.setHeader("Access-Control-Allow-Headers", HEADER_USER_ID_KEY); response .setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); LOGGER.info("*******>> getAllProjectsNoMapping"); try { return projectService.getAllProjects(roleId); } catch (final Exception e) { LOGGER.error("find a project failed {}"); throw new WifInvalidInputException("find a project failed {}"); } } /** * Gets the project configuration. * * @param roleId * the role id * @param id * the id * @return the project configuration * @throws WifInvalidInputException * the wif invalid input exception * @throws WifInvalidConfigException * the wif invalid config exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/configuration", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody WifProject getProjectConfiguration( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException, WifInvalidConfigException { LOGGER .info( "*******>> getProjectFullConfiguration request for project id ={}", id); final String msg = "getProjectFullConfiguration failed: {}"; try { return projectService.getProjectConfiguration(id); } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } } /** * Gets the status. * * @param roleId * the role id * @param id * the id * @return the status * @throws WifInvalidInputException * the wif invalid input exception * @throws WifInvalidConfigException * the wif invalid config exception * @throws ProjectSetupFailedException * the project setup failed exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/status", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody HashMap<String, String> getStatus( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException, WifInvalidConfigException, ProjectSetupFailedException { LOGGER.trace("*******>> getProjectStatus request for project id ={}", id); if (id == null) { LOGGER.error("get status failed, ID is undefined", id); throw new InvalidEntityIdException("get status failed "); } if (id.equalsIgnoreCase("undefined")) { LOGGER.error("get status failed, ID is undefined", id); throw new InvalidEntityIdException("get status failed "); } final HashMap<String, String> answer = new HashMap<String, String>(2); answer.put(WifKeys.SETUP_PROCESS_KEY, WifKeys.PROCESS_STATE_SETUP); String statusMessage = WifKeys.PROCESS_STATE_NA; final WifProject project = projectService.getProjectNoMapping(id); if (project.getReady()) { statusMessage = WifKeys.PROCESS_STATE_SUCCESS; } else { final String msge = "get status failed: {}"; try { final Future<String> result = projectsPool.get(id); if (result == null) { LOGGER.error("id not found in futuresPool for {}", id); throw new WifInvalidInputException("id not found in futuresPool"); } if (result.isDone()) { try { final String msg = result.get(); LOGGER.info("process ended with result: {}", msg); } catch (final ExecutionException e) { statusMessage = WifKeys.PROCESS_STATE_FAILED; final String errorMessage = "project a synchronous setup failed"; answer.put(WifKeys.STATUS_KEY, statusMessage); LOGGER.info("Status is = {}", answer.get(WifKeys.STATUS_KEY)); LOGGER.error(errorMessage, e); projectsPool.remove(id); projectService.purgeProject(project.getId()); throw new ProjectSetupFailedException(errorMessage, e); } statusMessage = WifKeys.PROCESS_STATE_SUCCESS; projectsPool.remove(id); // TODO Probably this is not necessary...only time will tell // project.setReady(true); // projectService.updateProject(project); } else { statusMessage = WifKeys.PROCESS_STATE_RUNNING; } } catch (final Exception e) { if (e instanceof InterruptedException) { LOGGER.error("Interrupted asynchronous creation of project " + msge, e.getMessage()); throw new ProjectSetupFailedException(msge, e); } else { LOGGER.error(msge, e.getMessage()); throw new ProjectSetupFailedException(msge, e); } } } answer.put(WifKeys.STATUS_KEY, statusMessage); LOGGER.debug("Status is ={}", answer.get(WifKeys.STATUS_KEY)); return answer; } /** * Update project. * * @param roleId * the role id * @param id * the id * @param project * the project * @throws WifInvalidInputException * the wif invalid input exception * @throws WifInvalidConfigException * the wif invalid config exception */ @RequestMapping(method = RequestMethod.PUT, value = "/{id}", consumes = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) public void updateProject( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id, @RequestBody final WifProject project) throws WifInvalidInputException, WifInvalidConfigException { LOGGER.info("*******>> updateProject request for project id ={}", id); // TODO we'll need to wire the project id on the wifProject object so // that the DAO will be able to handle it. Doing it this way will also // prevent // users/callers to request project 'A' to be updated but providing a // different // project ID on the actual content body final String msg = "setupAllocationConfig failed: {}"; project.setId(id); try { projectService.updateProject(project); } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } } /** * Delete project. * * @param roleId * the role id * @param id * the id * @throws WifInvalidInputException * the wif invalid input exception * @throws WifInvalidConfigException * the wif invalid config exception */ @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteProject( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException, WifInvalidConfigException { LOGGER.info("*******>> deleteProject request for project id ={}", id); final String msg = "deleteProject failed: {}"; try { projectService.deleteProject(id); } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } } /** * Creates the project. * * @param roleId * the role id * @param project * the project * @param response * the response * @return the wif project * @throws WifInvalidConfigException * the wif invalid config exception * @throws WifInvalidInputException * the wif invalid input exception * @throws DataStoreUnavailableException * the data store unavailable exception * @throws DataStoreCreationException * the data store creation exception * @throws InvalidFFNameException * @throws InvalidLabelException */ @RequestMapping(method = RequestMethod.POST, value = "/", consumes = "application/json", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public @ResponseBody WifProject createProject( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @RequestBody WifProject project, final HttpServletResponse response) throws WifInvalidConfigException, WifInvalidInputException, DataStoreUnavailableException, DataStoreCreationException, InvalidLabelException, InvalidFFNameException { LOGGER.info("*******>> createProject request for project label ={}", project.getLabel()); final String msg = "createProject failed: {}"; try { project = projectService.createProject(project, roleId); LOGGER .info( "*******>> project created with ID ={} requesting asynchronous task to finish setup ", project.getId()); final Future<String> future = asyncProjectService.setupProjectAsync( project, roleId); projectsPool.put(project.getId(), future); response.setHeader("Location", OWIURLs.PROJECT_SVC_URI + "/" + project.getId()); return project; } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } catch (final DataStoreUnavailableException e) { LOGGER.error(msg, e.getMessage()); throw new DataStoreUnavailableException(msg, e); } catch (final DataStoreCreationException e) { LOGGER.error(msg, e.getMessage()); throw new DataStoreCreationException(msg, e); } } /** * Gets the uAZ attributes. * * @param roleId * the role id * @param id * the id * @return the uAZ attributes * @throws WifInvalidInputException * the wif invalid input exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/unionAttributes", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody List<String> getUAZAttributes( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException { LOGGER.info("*******>> getUAZAttributes for Project request id ={}", id); try { final WifProject project = projectService.getProjectNoMapping(id); final SuitabilityConfig suitabilityConfig = project .getSuitabilityConfig(); if (suitabilityConfig != null) { final String uazTbl = suitabilityConfig.getUnifiedAreaZone(); return geodataFinder.getUAZAttributes(uazTbl); } else { LOGGER .error( "No analysisConfig set, getUAZAttributes project failed for {}", id); throw new WifInvalidInputException( "No analysisConfig set, getUAZAttributes project failed for " + id); } } catch (final Exception e) { if (e instanceof InvalidEntityIdException) { LOGGER.error("getUAZAttributes failed for {}", id); throw new InvalidEntityIdException("getUAZAttributes failed " + e.toString()); } else if (e instanceof NumberFormatException) { LOGGER.error( "NumberFormatException getUAZAttributes a project failed for {}", id); throw new WifInvalidInputException( "NumberFormatException getUAZAttributes project failed " + e.toString()); } else { LOGGER.error("getUAZAttributes a project failed for {}", id); throw new WifInvalidInputException("find a project failed " + id); } } } /** * Gets the distinct entries for uaz attribute. * * @param roleId * the role id * @param id * the id * @param attr * the attr * @return the distinct entries for uaz attribute * @throws WifInvalidInputException * the wif invalid input exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/unionAttributes/{attr}/values", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody List<String> getDistinctEntriesForUAZAttribute( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id, @PathVariable("attr") final String attr) throws WifInvalidInputException { LOGGER .info( "*******>> getDistinctEntriesForUAZAttribute on Project id ={} and attr ={}", id, attr); try { final WifProject project = projectService.getProjectNoMapping(id); final SuitabilityConfig suitabilityConfig = project .getSuitabilityConfig(); if (suitabilityConfig != null) { final String uazTbl = suitabilityConfig.getUnifiedAreaZone(); return geodataFinder.getDistinctEntriesForUAZAttribute(uazTbl, attr); } else { LOGGER .error( "No analysisConfig set, getDistinctEntriesForUAZAttribute project failed for {}", id); throw new WifInvalidInputException( "No analysisConfig set, getDistinctEntriesForUAZAttribute project failed for " + id); } } catch (final Exception e) { if (e instanceof InvalidEntityIdException) { LOGGER.error("getDistinctEntriesForUAZAttribute failed for {}", id); throw new InvalidEntityIdException( "getDistinctEntriesForUAZAttribute project failed " + e.toString()); } else if (e instanceof NumberFormatException) { LOGGER .error( "NumberFormatException getDistinctEntriesForUAZAttribute a project failed for {}", id); throw new WifInvalidInputException( "NumberFormatException getDistinctEntriesForUAZAttribute project failed " + e.toString()); } else { LOGGER.error( "getDistinctEntriesForUAZAttribute a project failed for {}", id); throw new WifInvalidInputException( "getDistinctEntriesForUAZAttribute a project failed " + id); } } } @RequestMapping(method = RequestMethod.GET, value = "/{id}/unionAttributesfixed", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody List<String> getDistinctEntriesForUAZAttributefixed( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException { LOGGER.info( "*******>> getDistinctEntriesForUAZAttributefixed on Project id ={} ", id); try { final WifProject project = projectService.getProjectNoMapping(id); final String attr = project.getExistingLUAttributeName(); final SuitabilityConfig suitabilityConfig = project .getSuitabilityConfig(); if (suitabilityConfig != null) { final String uazTbl = suitabilityConfig.getUnifiedAreaZone(); return geodataFinder.getDistinctEntriesForUAZAttribute(uazTbl, attr); } else { LOGGER .error( "No analysisConfig set, getDistinctEntriesForUAZAttributefixed project failed for {}", id); throw new WifInvalidInputException( "No analysisConfig set, getDistinctEntriesForUAZAttributefixed project failed for " + id); } } catch (final Exception e) { if (e instanceof InvalidEntityIdException) { LOGGER .error("getDistinctEntriesForUAZAttributefixed failed for {}", id); throw new InvalidEntityIdException( "getDistinctEntriesForUAZAttributefixed project failed " + e.toString()); } else if (e instanceof NumberFormatException) { LOGGER .error( "NumberFormatException getDistinctEntriesForUAZAttributefixed a project failed for {}", id); throw new WifInvalidInputException( "NumberFormatException getDistinctEntriesForUAZAttributefixed project failed " + e.toString()); } else { LOGGER.error( "getDistinctEntriesForUAZAttributefixed a project failed for {}", id); throw new WifInvalidInputException( "getDistinctEntriesForUAZAttributefixed a project failed " + id); } } } @RequestMapping(method = RequestMethod.GET, value = "/{id}/unionAttributes/{attr}/colorsold", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody List<String> getDistinctColorsForUAZAttributeold( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id, @PathVariable("attr") final String attr) throws WifInvalidInputException { LOGGER .info( "*******>> getDistinctColorsForUAZAttribute on Project id ={} and attr ={}", id, attr); try { final WifProject project = projectService.getProjectNoMapping(id); final SuitabilityConfig suitabilityConfig = project .getSuitabilityConfig(); if (suitabilityConfig != null) { final String uazTbl = suitabilityConfig.getUnifiedAreaZone(); return geodataFinder.getDistinctColorsForUAZAttribute(uazTbl, attr); } else { LOGGER .error( "No analysisConfig set, getDistinctColorsForUAZAttribute project failed for {}", id); throw new WifInvalidInputException( "No analysisConfig set, getDistinctColorsForUAZAttribute project failed for " + id); } } catch (final Exception e) { if (e instanceof InvalidEntityIdException) { LOGGER.error("getDistinctColorsForUAZAttribute failed for {}", id); throw new InvalidEntityIdException( "getDistinctColorsForUAZAttribute project failed " + e.toString()); } else if (e instanceof NumberFormatException) { LOGGER .error( "NumberFormatException getDistinctColorsForUAZAttribute a project failed for {}", id); throw new WifInvalidInputException( "NumberFormatException getDistinctColorsForUAZAttribute project failed " + e.toString()); } else { // LOGGER.error( // "getDistinctColorsForUAZAttribute a project failed for {}", id); // throw new WifInvalidInputException( // "getDistinctColorsForUAZAttribute a project failed " + id); return null; } } } @RequestMapping(method = RequestMethod.GET, value = "/{id}/unionAttributes/colorsforaluconfig", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody List<String> getDistinctColorsForAluConfig( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException { LOGGER.info("*******>> colorsforaluconfig on Project id ={} ", id); try { final WifProject project = projectService.getProjectNoMapping(id); final String attr = project.getExistingLUAttributeName(); final SuitabilityConfig suitabilityConfig = project .getSuitabilityConfig(); if (suitabilityConfig != null) { final String uazTbl = suitabilityConfig.getUnifiedAreaZone(); return geodataFinder.getDistinctColorsForALUConfig(uazTbl, attr); } else { LOGGER .error( "No analysisConfig set, getDistinctColorsForAluConfig project failed for {}", id); throw new WifInvalidInputException( "No analysisConfig set, getDistinctColorsForAluConfig project failed for " + id); } } catch (final Exception e) { if (e instanceof InvalidEntityIdException) { LOGGER.error("getDistinctColorsForUAZAttribute failed for {}", id); throw new InvalidEntityIdException( "getDistinctColorsForUAZAttribute project failed " + e.toString()); } else if (e instanceof NumberFormatException) { LOGGER .error( "NumberFormatException getDistinctColorsForAluConfig a project failed for {}", id); throw new WifInvalidInputException( "NumberFormatException getDistinctColorsForAluConfig project failed " + e.toString()); } else { // LOGGER.error( // "getDistinctColorsForUAZAttribute a project failed for {}", id); // throw new WifInvalidInputException( // "getDistinctColorsForUAZAttribute a project failed " + id); return null; } } } @RequestMapping(method = RequestMethod.GET, value = "/{id}/unionAttributes/{attr}/colors", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody List<String> getDistinctColorsForUAZAttribute( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id, @PathVariable("attr") final String attr) throws WifInvalidInputException { LOGGER .info( "*******>> getDistinctColorsForUAZAttribute on Project id ={} and attr ={}", id, attr); try { final List<String> lst = new ArrayList<String>(); WifProject project = projectService.getProjectNoMapping(id); project = projectParser.parse(project); AllocationConfigs AllocationConfigs = null; final String AllocationConfigsId = project.getAllocationConfigsId(); if (AllocationConfigsId != null) { LOGGER.info("getting the AllocationConfig with ID={}", AllocationConfigsId); AllocationConfigs = AllocationConfigsDao .findAllocationConfigsById(AllocationConfigsId); if (AllocationConfigs.getColorALUs().size() != 0) { for (final ColorALU color : AllocationConfigs.getColorALUs()) { lst.add('F' + color.getLabel() + '@' + color.getAssociatedColors()); } } } return lst; } catch (final Exception e) { if (e instanceof InvalidEntityIdException) { LOGGER.error("getDistinctColorsForUAZAttribute failed for {}", id); throw new InvalidEntityIdException( "getDistinctColorsForUAZAttribute project failed " + e.toString()); } else if (e instanceof NumberFormatException) { LOGGER .error( "NumberFormatException getDistinctColorsForUAZAttribute a project failed for {}", id); throw new WifInvalidInputException( "NumberFormatException getDistinctColorsForUAZAttribute project failed " + e.toString()); } else { // LOGGER.error( // "getDistinctColorsForUAZAttribute a project failed for {}", id); // throw new WifInvalidInputException( // "getDistinctColorsForUAZAttribute a project failed " + id); return null; } } } /** * Update uaz. * * @param roleId * the role id * @param id * the id * @param optionalColumns * the optional columns * @throws WifInvalidInputException * the wif invalid input exception * @throws BindException * the bind exception * @throws UAZAlreadyCreatedException * the uAZ already created exception * @throws IncompleteSuitabilityLUConfigException * the incomplete suitability lu config exception * @throws FactoryException * the factory exception * @throws DataStoreUnavailableException * the data store unavailable exception * @throws WifInvalidConfigException * the wif invalid config exception * @throws GeoServerConfigException * @throws DataStoreCreationException */ @RequestMapping(method = RequestMethod.PUT, value = "/{id}/UAZ", consumes = "application/json") @ResponseStatus(HttpStatus.OK) public void updateUAZ(@RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id, @RequestBody final List<String> optionalColumns) throws WifInvalidInputException, BindException, UAZAlreadyCreatedException, IncompleteSuitabilityLUConfigException, FactoryException, DataStoreUnavailableException, WifInvalidConfigException, GeoServerConfigException, DataStoreCreationException { final String msg = "updateUAZ failed: {}"; LOGGER.info("*******>> updateUAZ request for project id ={}", id); try { projectService.convertUnionToUAZ(id, optionalColumns, roleId); LOGGER .info(" finalized setup process for project id ={} <<*******>>", id); } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } catch (final UAZAlreadyCreatedException e) { LOGGER.error(msg, e.getMessage()); throw new UAZAlreadyCreatedException(msg, e); } catch (final IncompleteSuitabilityLUConfigException e) { LOGGER.error(msg, e.getMessage()); throw new IncompleteSuitabilityLUConfigException(msg, e); } catch (final DataStoreUnavailableException e) { LOGGER.error(msg, e.getMessage()); throw new DataStoreUnavailableException(msg, e); } catch (final FactoryException e) { LOGGER.error(msg, e.getMessage()); throw new FactoryException(msg, e); } catch (final GeoServerConfigException e) { LOGGER.error(msg, e.getMessage()); throw new GeoServerConfigException(msg, e); } } /** * Restore project. * * @param roleId * the role id * @param projectReport * the project report * @param response * the response * @return the wif project * @throws WifInvalidInputException * the wif invalid input exception * @throws WifInvalidConfigException * the wif invalid config exception * @throws ParsingException */ @RequestMapping(method = RequestMethod.POST, value = "/restore", consumes = "application/json", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public @ResponseBody WifProject restoreProject( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @RequestBody final ProjectReport projectReport, final HttpServletResponse response) throws WifInvalidInputException, WifInvalidConfigException, ParsingException { LOGGER.info("*******>> restoreProject request for projectReport label ={}", projectReport.getLabel()); final String msg = "restoreProject failed: {}"; try { final WifProject wifProject = projectService .restoreProjectConfiguration(projectReport); LOGGER .info("*******>> project restored with ID ={} ", wifProject.getId()); response.setHeader("Location", OWIURLs.PROJECT_SVC_URI + "/" + wifProject.getId()); return wifProject; } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } } /** * Delete project configuration. * * @param roleId * the role id * @param id * the id * @throws WifInvalidInputException * the wif invalid input exception * @throws WifInvalidConfigException * the wif invalid config exception */ @RequestMapping(method = RequestMethod.DELETE, value = "/{id}/keepUAZ") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteProjectConfiguration( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException, WifInvalidConfigException { LOGGER .info( "*******>> deleteProjectconfiguration only request for project id ={}", id); final String msg = "deleteProjectconfiguration failed: {}"; try { projectService.deleteProject(id, false); } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } } /** * Gets the project report. * * @param roleId * the role id * @param id * the id * @return the project report * @throws WifInvalidConfigException * the wif invalid config exception * @throws WifInvalidInputException * the wif invalid input exception * @throws ParsingException * the parsing exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/report", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody ProjectReport getProjectReport( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidConfigException, WifInvalidInputException, ParsingException { LOGGER.info("*******>> getProjectReport request for project id ={}", id); final String msg = "getProjectReport failed: {}"; try { final WifProject project = projectService.getProjectConfiguration(id); /////for deleting extra factor types. projectService.updateProject(project); factorService.deleteFactorTypesExtra(id); ///// return reportService.getProjectReport(project); } catch (final WifInvalidInputException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } catch (final ParsingException e) { LOGGER.error(msg, e.getMessage()); throw new ParsingException(msg, e); } } /** * Upload uaz async. * * @param roleId * the role id * @param id * the id * @throws WifInvalidInputException * the wif invalid input exception * @throws DataStoreUnavailableException * the data store unavailable exception * @throws WifInvalidConfigException * the wif invalid config exception * @throws WifIOException * the wif io exception * @throws ProjectNotReadyException * the project not ready exception * @throws DataStoreCreationException * @throws IOException * @throws MiddlewarePersistentException */ @RequestMapping(method = RequestMethod.POST, value = "/{id}/upload") @ResponseStatus(HttpStatus.OK) public void uploadUAZAsync( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException, DataStoreUnavailableException, WifInvalidConfigException, WifIOException, ProjectNotReadyException, IOException, DataStoreCreationException, MiddlewarePersistentException { LOGGER.info("*******>> uploadUAZAsync request for project id ={}", id); final WifProject project = projectService.getProject(id); if (project.getReady()) { final Future<String> future = asyncProjectService.uploadUAZAsync(project, roleId); uploadsPool.put(project.getId(), future); } else { final String msg = "Project is not ready for uploading UAZ"; LOGGER.error(msg); throw new ProjectNotReadyException(msg); } } /** * Gets the upload status. * * @param roleId * the role id * @param id * the id * @return the upload status * @throws WifInvalidInputException * the wif invalid input exception * @throws WifInvalidConfigException * the wif invalid config exception * @throws ProjectSetupFailedException * the project setup failed exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/upload/status", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody HashMap<String, String> getUploadStatus( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException, WifInvalidConfigException, ProjectSetupFailedException { LOGGER.info("*******>> getUploadStatus request for project id ={}", id); if (id == null) { LOGGER.error("getUploadStatus failed, ID is undefined", id); throw new InvalidEntityIdException("getUploadStatus failed "); } if (id.equalsIgnoreCase("undefined")) { LOGGER.error("get status failed, ID is undefined", id); throw new InvalidEntityIdException("getUploadStatus failed "); } final HashMap<String, String> answer = new HashMap<String, String>(2); answer.put(WifKeys.SETUP_PROCESS_KEY, WifKeys.PROCESS_STATE_SETUP); String statusMessage = WifKeys.PROCESS_STATE_NA; final WifProject project = projectService.getProjectNoMapping(id); if (project.getReady()) { statusMessage = WifKeys.PROCESS_STATE_SUCCESS; } else { final String msge = "getUploadStatus failed: {}"; try { final Future<String> result = uploadsPool.get(id); if (result == null) { LOGGER.error("id not found in futuresPool for {}", id); throw new WifInvalidInputException("id not found in futuresPool"); } if (result.isDone()) { try { final String msg = result.get(); LOGGER.info("process ended with result: {}", msg); } catch (final ExecutionException e) { statusMessage = WifKeys.PROCESS_STATE_FAILED; final String errorMessage = "project uploadUAZ synchronous failed"; answer.put(WifKeys.STATUS_KEY, statusMessage); LOGGER.info("Status is = {}", answer.get(WifKeys.STATUS_KEY)); LOGGER.error(errorMessage, e); uploadsPool.remove(id); throw new ProjectSetupFailedException(errorMessage, e); } statusMessage = WifKeys.PROCESS_STATE_SUCCESS; uploadsPool.remove(id); } else { statusMessage = WifKeys.PROCESS_STATE_RUNNING; } } catch (final Exception e) { if (e instanceof InterruptedException) { LOGGER.error("Interrupted asynchronous upload of UAZ " + msge, e.getMessage()); throw new ProjectSetupFailedException(msge, e); } else { LOGGER.error(msge, e.getMessage()); throw new ProjectSetupFailedException(msge, e); } } } answer.put(WifKeys.STATUS_KEY, statusMessage); LOGGER.info("Status is ={}", answer.get(WifKeys.STATUS_KEY)); return answer; } /** * Gets the uAZ uri. * * @param roleId * the role id * @param id * the id * @return the uAZ uri * @throws WifInvalidInputException * the wif invalid input exception * @throws DataStoreUnavailableException * the data store unavailable exception * @throws WifInvalidConfigException * the wif invalid config exception * @throws WifIOException * the wif io exception * @throws ProjectNotReadyException * the project not ready exception */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/upload") @ResponseStatus(HttpStatus.OK) public String getUAZUri( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id) throws WifInvalidInputException, DataStoreUnavailableException, WifInvalidConfigException, WifIOException, ProjectNotReadyException { LOGGER.info("*******>> getUAZUri request for project id ={}", id); final WifProject project = projectService.getProjectNoMapping(id); return project.getUploadUAZDatatoreUri(); } /** * Gets the all project names. * * @param roleId * the role id * @return * @return the all projects names * @throws WifInvalidConfigException * the wif invalid config exception * @throws WifInvalidInputException * the wif invalid input exception * @throws NoSuchAuthorityCodeException * the no such authority code exception * @throws FactoryException * the factory exception * @throws TransformException * the transform exception * @throws ParseException * the parse exception * @throws CQLException * the cQL exception */ @RequestMapping(method = RequestMethod.GET, value = "/projectNames") @ResponseStatus(HttpStatus.OK) @SuppressWarnings({ "unchecked", "rawtypes" }) public @ResponseBody List<String> getAllProjectNames( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, final HttpServletResponse response) throws WifInvalidConfigException, WifInvalidInputException, NoSuchAuthorityCodeException, FactoryException, TransformException, ParseException, CQLException { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE"); response.setHeader("Access-Control-Allow-Headers", HEADER_USER_ID_KEY); response .setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); LOGGER.info("*******>> getAllProject names"); final List<String> lst = new ArrayList<String>(); try { final List<WifProject> prjList = projectService.getAllProjects(roleId); for (final WifProject wif : prjList) { lst.add(wif.getLabel()); } return lst; } catch (final Exception e) { LOGGER.error("getAllProject names {}"); throw new WifInvalidInputException("find a project failed {}"); } } @RequestMapping(method = RequestMethod.GET, value = "/{id}/MakeLUsforUnionAttributes/{attr}/makeLU", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody List<AllocationLU> MakeLUsforUnionAttributes( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, @PathVariable("id") final String id, @PathVariable("attr") final String attr) throws WifInvalidInputException { LOGGER .info( "*******>> MakeLUsforUnionAttributes on Project id ={} and attr ={}", id, attr); try { final WifProject project = projectService.getProjectNoMapping(id); final SuitabilityConfig suitabilityConfig = project .getSuitabilityConfig(); //////////////// if (suitabilityConfig != null) { final String uazTbl = suitabilityConfig.getUnifiedAreaZone(); final List<String> lst= geodataFinder.getDistinctEntriesForUAZAttribute(uazTbl, attr); for (final String str: lst) { final AllocationLU allocationLU = new AllocationLU(); allocationLU.setProjectId(project.getId()); allocationLU.setLabel(str); allocationLU.setFeatureFieldName(str); allocationLUService.createAllocationLU(allocationLU, project.getId()); } return allocationLUService.getAllocationLUs(id); } else { LOGGER .error( "No analysisConfig set, getDistinctEntriesForUAZAttribute project failed for {}", id); throw new WifInvalidInputException( "No analysisConfig set, getDistinctEntriesForUAZAttribute project failed for " + id); } } catch (final Exception e) { if (e instanceof InvalidEntityIdException) { LOGGER.error("MakeLUsforUnionAttributes failed for {}", id); throw new InvalidEntityIdException( "MakeLUsforUnionAttributes project failed " + e.toString()); } else if (e instanceof NumberFormatException) { LOGGER .error( "NumberFormatException MakeLUsforUnionAttributes a project failed for {}", id); throw new WifInvalidInputException( "NumberFormatException MakeLUsforUnionAttributes project failed " + e.toString()); } else { LOGGER.error( "MakeLUsforUnionAttributes a project failed for {}", id); throw new WifInvalidInputException( "MakeLUsforUnionAttributes a project failed " + id); } } } @RequestMapping(method = RequestMethod.GET, value = "/{user_id}/copydemo", produces = "application/json") @ResponseStatus(HttpStatus.OK) public @ResponseBody String CopyDemoProject( @RequestHeader(HEADER_USER_ID_KEY) final String roleId ,@PathVariable("user_id") final String user_id) throws WifInvalidConfigException, WifInvalidInputException, ParsingException, NoSuchAuthorityCodeException, FactoryException { final String msg = "getProjectReport failed: {}"; String out =""; String id = ""; String dbName=""; CoordinateReferenceSystem crs = null; try { Boolean lsw=false; final List<WifProject> wifProjectsRole = projectService.getAllProjects(roleId); for (final WifProject prjRole:wifProjectsRole) { if (prjRole.getRoleOwner().toLowerCase().equals(roleId)) { final String prjName = "Demo_for_" + roleId; if (prjRole.getLabel().toLowerCase().equals(prjName.toLowerCase())) { lsw = true; } } } if (lsw == false) { final List<WifProject> wifProjects = projectService.getAllProjects(WifKeys.SHIB_ROLE_NAME); for (final WifProject prj:wifProjects) { if (prj.getRoleOwner().toLowerCase().equals(WifKeys.SHIB_ROLE_NAME.toLowerCase())) { if (prj.getLabel().toLowerCase().equals(WifKeys.DEMO_PROJECT_NAME_ADMIN.toLowerCase())) { id = prj.getId(); dbName = prj.getSuitabilityConfig().getUnifiedAreaZone(); crs = CRS.decode(prj.getSrs()); } } } if (!id.equals("")) { LOGGER.info("*******>> copydemo request for project id ={}", id); } if (!dbName.equals("")) { //copydb geodataFinder.CopyDemoTable("wanneroofor" + user_id, dbName); final WifProject project = projectService.getProjectConfiguration(id); /////for deleting extra factor types. projectService.updateProject(project); factorService.deleteFactorTypesExtra(id); //// final ProjectReport projectReport= reportService.getProjectReport(project); final WifProject wifProject = projectService.restoreProjectConfiguration(projectReport); LOGGER.info("*******>> project restored with ID ={} ", wifProject.getId()); final WifProject newProject = projectService.getProject(wifProject.getId()); newProject.setName("Demo_for_" + roleId); newProject.setRoleOwner(roleId); newProject.getSuitabilityConfig().setUnifiedAreaZone("wanneroofor" + user_id); projectService.updateProject(newProject); //pubish Geoserver layer crs = CRS.decode(newProject.getSrs()); projectService.PublishWMSLayer( newProject .getSuitabilityConfig().getUnifiedAreaZone(), crs, newProject.getId()); out ="copied"; } } } catch (final WifInvalidInputException e) { out ="failed"; LOGGER.error(msg, e.getMessage()); throw new WifInvalidInputException(msg, e); } catch (final WifInvalidConfigException e) { out ="failed"; LOGGER.error(msg, e.getMessage()); throw new WifInvalidConfigException(msg, e); } catch (final ParsingException e) { out ="failed"; LOGGER.error(msg, e.getMessage()); throw new ParsingException(msg, e); } return out; } /** * Gets the report projects. * * @param roleId * the role id * @return the all projects * @throws WifInvalidConfigException * the wif invalid config exception * @throws WifInvalidInputException * the wif invalid input exception * @throws NoSuchAuthorityCodeException * the no such authority code exception * @throws FactoryException * the factory exception * @throws TransformException * the transform exception * @throws ParseException * the parse exception * @throws CQLException * the cQL exception */ @RequestMapping(method = RequestMethod.GET, value = "/getReportProjects") @ResponseStatus(HttpStatus.OK) public @ResponseBody List<String> getReportProjects( @RequestHeader(HEADER_USER_ID_KEY) final String roleId, final HttpServletResponse response) throws WifInvalidConfigException, WifInvalidInputException, NoSuchAuthorityCodeException, FactoryException, TransformException, ParseException, CQLException { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE"); response.setHeader("Access-Control-Allow-Headers", HEADER_USER_ID_KEY); response .setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); LOGGER.info("*******>> getReportProjects"); final List<String> lst = new ArrayList<String>(); try { final List<WifProject> prjs= projectService.getAllProjects(roleId); for (final WifProject prj : prjs) { final SimpleDateFormat mdyFormat = new SimpleDateFormat("dd/MM/yyyy"); lst.add(prj.getRoleOwner() + "|" + prj.getName() + "|" + mdyFormat.format(prj.getCreationDate())); } return lst; } catch (final Exception e) { LOGGER.error("getReportProjects failed {}"); throw new WifInvalidInputException("getReportProjects failed {}"); } } }
mit
ChioriGreene/ChioriWebServer
src/main/groovy/com/chiorichan/factory/parsers/BasicParser.java
1768
/** * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * Copyright (c) 2017 Joel Greene <joel.greene@penoaks.com> * Copyright (c) 2017 Penoaks Publishing LLC <development@penoaks.com> * * All Rights Reserved. */ package com.chiorichan.factory.parsers; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.chiorichan.utils.UtilStrings; import org.apache.commons.lang3.Validate; /** * Used for basic parsing of code blocks, e.g., < !-- this_is_a_method(argument) --> */ public abstract class BasicParser { private Pattern p1; private Pattern p2; public BasicParser( String patternOne, String patternTwo ) { Validate.notEmpty( patternOne ); Validate.notEmpty( patternTwo ); p1 = Pattern.compile( patternOne ); p2 = Pattern.compile( patternTwo ); } public String runParser( String source ) throws Exception { if ( source == null || source.isEmpty() ) return ""; Matcher m1 = p1.matcher( source ); Matcher m2 = p2.matcher( source ); while ( m1.find() && m2.find() ) { String[] args = m1.group( 1 ).split( "[ ]?,[ ]?" ); String[] args2 = new String[args.length + 1]; args2[0] = m1.group( 0 ); for ( int i = 0; i < args.length; i++ ) args2[i + 1] = UtilStrings.trimAll( args[i].trim(), '"' ); String result = resolveMethod( args2 ); if ( result == null ) result = ""; source = new StringBuilder( source ).replace( m2.start( 1 ), m2.end( 1 ), result ).toString(); // We have to reset the matcher since the source changes with each loop m1 = p1.matcher( source ); m2 = p2.matcher( source ); } return source; } public abstract String resolveMethod( String... args ) throws Exception; }
mit
davetrux/1DevDayDetroit-2014
android/ToDo/app/src/main/java/com/onedevdaydetroit/todo/data/ToDo.java
1404
package com.onedevdaydetroit.todo.data; import android.os.Parcel; import android.os.Parcelable; public class ToDo implements Parcelable { private Long mId; private String mTitle; /* * Default constructor for general object creation */ public ToDo() { } /* * Constructor needed for parcelable object creation */ public ToDo(Parcel item) { mId = item.readLong(); mTitle = item.readString(); } public Long getId() { return mId; } public void setId(Long id) { this.mId = id; } public String getTitle() { return mTitle; } public void setTitle(String title) { this.mTitle = title; } /* * Used to generate parcelable classes from a parcel */ public static final Parcelable.Creator<ToDo> CREATOR = new Parcelable.Creator<ToDo>() { public ToDo createFromParcel(Parcel in) { return new ToDo(in); } public ToDo[] newArray(int size) { return new ToDo[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { if(mId != null) { parcel.writeLong(mId); } else { parcel.writeLong(-1); } parcel.writeString(mTitle); } }
mit
stingchang/CS_Java
src/question_301/Q344_Reverse_String.java
366
package question_301; public class Q344_Reverse_String { public String reverseString(String s) { char[] arr = s.toCharArray(); int len = arr.length; for(int i =0 ; i< len/2; i++){ char c = arr[i]; arr[i] = arr[len-1-i]; arr[len-1-i] = c; } return String.valueOf(arr); } }
mit
TzuChieh/Photon-v2
PhotonStudio/Source/jsdl/MatteOpaqueMaterialCreator.java
612
// ======================================== // NOTE: THIS FILE CONTAINS GENERATED CODE // DO NOT MODIFY // ======================================== // last generated: 2019-01-01 17:46:28.920325 package jsdl; public class MatteOpaqueMaterialCreator extends SDLCreatorCommand { @Override public String getFullType() { return "material(matte-opaque)"; } public void setAlbedo(SDLReal data) { setInput("albedo", data); } public void setAlbedo(SDLVector3 data) { setInput("albedo", data); } public void setAlbedo(SDLImage data) { setInput("albedo", data); } }
mit
Musician101/MineTanks
minetanks-sponge/src/main/java/io/musician101/minetanks/sponge/SpongeMineTanks.java
2675
package io.musician101.minetanks.sponge; import io.musician101.minetanks.common.CommonReference; import io.musician101.minetanks.common.CommonReference.CommonCommands; import io.musician101.minetanks.sponge.battlefield.SpongeBattleFieldStorage; import io.musician101.minetanks.sponge.command.MTSpongeCommands; import io.musician101.minetanks.sponge.util.SpongeInventoryStorage; import io.musician101.musicianlibrary.java.minecraft.AbstractConfig; import io.musician101.musicianlibrary.java.minecraft.sponge.AbstractSpongePlugin; import io.musician101.musicianlibrary.java.minecraft.sponge.command.MLCommandCallable; import java.io.File; import org.slf4j.Logger; import org.spongepowered.api.Sponge; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GameStartingServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.plugin.PluginContainer; @Plugin(id = CommonReference.ID, name = CommonReference.NAME, version = CommonReference.VERSION, description = CommonReference.DESCRIPTION) public class SpongeMineTanks extends AbstractSpongePlugin<AbstractConfig> { private final File configDir = new File(CommonReference.NAME); private SpongeBattleFieldStorage fieldStorage; private SpongeInventoryStorage inventoryStorage; public static PluginContainer getPluginContainer() { return Sponge.getPluginManager().getPlugin(CommonReference.ID).get(); } public static SpongeMineTanks instance() { return (SpongeMineTanks) getPluginContainer().getInstance().get(); } public SpongeBattleFieldStorage getFieldStorage() { return fieldStorage; } public SpongeInventoryStorage getInventoryStorage() { return inventoryStorage; } @Override public Logger getLogger() { return getPluginContainer().getLogger(); } //TODO write AbstractMTSpongeCommand and implement it, refer to AbstractMTSpigotCommand @Listener public void onServerStart(GameStartingServerEvent event) { fieldStorage = new SpongeBattleFieldStorage(configDir); fieldStorage.loadFromFiles(); inventoryStorage = new SpongeInventoryStorage(configDir); Sponge.getCommandManager().register(this, new MLCommandCallable<>(getPluginContainer(), MTSpongeCommands.mt()), CommonCommands.MT_CMD.replace("/", "")); getLogger().info(CommonReference.MOVIN_ON_OUT); } @Listener public void onServerStop(GameStoppingServerEvent event) { fieldStorage.saveToFiles(); getLogger().info(CommonReference.PACK_IT_UP); } }
mit
ilves/finance
src/main/java/ee/golive/finants/chart/Value.java
416
package ee.golive.finants.chart; /** * Created by taavi.ilves on 14.10.2014. */ public class Value { public String id; public long value; public String color; public Value(String id, long value, String color) { this.id = id; this.value = value; this.color = color; } public Value(String id, long value) { this.id = id; this.value = value; } }
mit
Qordobacode/api-sdk-java
QordobaLib/src/com/qordoba/developers/http/request/HttpBodyRequest.java
2152
/* * QordobaLib * * by Qordoba BETA v2.0 on 02/25/2016 */ package com.qordoba.developers.http.request; import com.qordoba.developers.http.request.HttpMethod; import java.util.Map; public class HttpBodyRequest extends HttpRequest { /** * Private store for properties */ private String body; /** * Body for the http request */ public String getBody() { return body; } /** * Create a request with explicit body * * @param _method The HTTP method to use. Can be PUT, POST, DELETE and PATCH * @param _queryUrl The http url to create the HTTP Request. Expect a fully qualified absolute Url * @param _headers The key-value map of all http headers to be sent * @param _body The object to be sent as body after serialization * @return Http request initialized with the given method, url, headers and request body */ public HttpBodyRequest(HttpMethod _method, String _queryUrl, Map<String, String> _headers, String _body) { super(_method, _queryUrl, _headers, null); this.body = _body!=null ? _body : ""; } /** * Create a request with explicit body * * @param _method The HTTP method to use. Can be PUT, POST, DELETE and PATCH * @param _queryUrl The http url to create the HTTP Request. Expect a fully qualified absolute Url * @param _headers The key-value map of all http headers to be sent * @param _body The object to be sent as body after serialization * @param _username Username for basic authentication * @param _password Password for basic authentication * @return Http request initialized with the given method, url, headers and request body */ public HttpBodyRequest(HttpMethod _method, String _queryUrl, Map<String, String> _headers, String _body, String _username, String _password) { super(_method, _queryUrl, _headers, null, _username, _password); this.body = _body!=null ? _body : ""; } }
mit
TwilioDevEd/api-snippets
notifications/rest/bindings/list-binding/list-binding.8.x.java
1192
// NOTE: This example uses the next generation Twilio helper library - for more // information on how to download and install this version, visit // https://www.twilio.com/docs/libraries/java import com.twilio.Twilio; import com.twilio.base.ResourceSet; import com.twilio.rest.notify.v1.service.Binding; import java.time.LocalDate; public class Example { // Find your Account Sid and Token at twilio.com/user/account // To set up environment variables, see http://twil.io/secure public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID"); public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN"); public static final String SERVICE_SID = System.getenv("TWILIO_SERVICE_SID"); public static void main(String args[]) { // Initialize the client Twilio.init(ACCOUNT_SID, AUTH_TOKEN); // List the bindings ResourceSet<Binding> bindings = Binding.reader(SERVICE_SID) .setStartDate(LocalDate.of(2005, 8, 18)) .setTag("new user") .read(); for (Binding binding : bindings) { System.out.println(binding.getEndpoint()); } } }
mit
oaplatform/oap
oap-stdlib/src/test/java/oap/json/schema/JsonDiffTest.java
14429
/* * The MIT License (MIT) * * Copyright (c) Open Application Platform Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package oap.json.schema; import org.testng.annotations.Test; import java.util.List; import java.util.Optional; import static java.util.Optional.empty; import static java.util.Optional.of; import static org.assertj.core.api.Assertions.assertThat; public class JsonDiffTest extends AbstractSchemaTest { @Test public void newString() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"string\"" + "}" + "}}"; assertThat( diff( schema, "{}", "{\"test\":\"new value\"}" ) ).containsOnly( newF( "test", "\"new value\"" ) ); } @Test public void delString() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"string\"" + "}" + "}}"; assertThat( diff( schema, "{\"test\":\"old value\"}", "{}" ) ).containsOnly( delF( "test", "\"old value\"" ) ); } @Test public void updString() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"string\"" + "}" + "}}"; assertThat( diff( schema, "{\"test\":\"old value\"}", "{\"test\":\"new value\"}" ) ) .containsOnly( updF( "test", "\"old value\"", "\"new value\"" ) ); } @Test public void updStringNested() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"object\"," + " \"properties\":{" + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":{\"testin\":\"old value\"}}", "{\"test\":{\"testin\":\"new value\"}}" ) ) .containsOnly( updF( "test.testin", "\"old value\"", "\"new value\"" ) ); } @Test public void newNested() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"object\"," + " \"properties\":{" + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{}", "{\"test\":{\"testin\":\"new value\"}}" ) ) .containsOnly( newO( "test", "{\"testin\":\"new value\"}" ) ); } @Test public void delNested() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"object\"," + " \"properties\":{" + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":{\"testin\":\"new value\"}}", "{}" ) ) .containsOnly( delO( "test", "{\"testin\":\"new value\"}" ) ); } @Test public void newArray() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"items\":{" + " \"type\":\"string\"" + " }" + " }" + "}}"; assertThat( diff( schema, "{}", "{\"test\":[\"new value\"]}" ) ).containsOnly( newA( "test", "[\"new value\"]" ) ); } @Test public void newArrayItem() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"items\":{" + " \"type\":\"string\"" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[\"old value\"]}", "{\"test\":[\"old value\",\"new value\"]}" ) ) .containsOnly( newA( "test", "[\"new value\"]" ) ); } @Test public void emptyArrays() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"items\":{" + " \"type\":\"string\"" + " }" + " }" + "}}"; assertThat( diff( schema, "{}", "{}" ) ).isEmpty(); } @Test public void delArrayItem() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"items\":{" + " \"type\":\"string\"" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[\"old value\", \"old value 2\"]}", "{\"test\":[\"old value 2\"]}" ) ) .containsOnly( delA( "test", "[\"old value\"]" ) ); } @Test public void updateArrayItem() { final String schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"items\":{" + " \"type\":\"string\"" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[\"old value\", \"old value 2\"]}", "{\"test\":[\"old value 2\", \"new value\"]}" ) ) .containsOnly( updA( "test", "[\"old value\"]", "[\"new value\"]" ) ); } @Test public void updStringIntoArrayObject() { var schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"id\":\"test\"," + " \"items\":{" + " \"type\":\"object\"," + " \"properties\":{" + " \"test\":{" + " \"type\":\"string\"" + " }," + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[{\"test\":\"id\",\"testin\":\"old value\"}]}", "{\"test\":[{\"test\":\"id\",\"testin\":\"new value\"}]}" ) ) .containsOnly( updF( "test[id].testin", "\"old value\"", "\"new value\"" ) ); } @Test public void addArrayObject() { var schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"id\":\"test\"," + " \"items\":{" + " \"type\":\"object\"," + " \"properties\":{" + " \"test\":{" + " \"type\":\"string\"" + " }," + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[]}", "{\"test\":[{\"test\":\"id\",\"testin\":\"new value\"}]}" ) ) .containsOnly( newO( "test[id]", "{\"test\":\"id\",\"testin\":\"new value\"}" ) ); } @Test public void removeArrayObject() { var schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"id\":\"test\"," + " \"items\":{" + " \"type\":\"object\"," + " \"properties\":{" + " \"test\":{" + " \"type\":\"string\"" + " }," + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[{\"test\":\"id\",\"testin\":\"new value\"}]}", "{\"test\":[]}" ) ) .containsOnly( delO( "test[id]", "{\"test\":\"id\",\"testin\":\"new value\"}" ) ); } @Test public void updateArrayObjectWithoutId() { var schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"id\":\"{index}\"," + " \"items\":{" + " \"type\":\"object\"," + " \"properties\":{" + " \"test\":{" + " \"type\":\"string\"" + " }," + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[{\"test\":\"id\",\"testin\":\"old value\"}]}", "{\"test\":[{\"test\":\"id\",\"testin\":\"new value\"}]}" ) ) .containsOnly( updF( "test[0].testin", "\"old value\"", "\"new value\"" ) ); } @Test public void addArrayObjectWithoutId() { var schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"id\":\"{index}\"," + " \"items\":{" + " \"type\":\"object\"," + " \"properties\":{" + " \"test\":{" + " \"type\":\"string\"" + " }," + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[{}]}", "{\"test\":[{}, {\"test\":\"id\",\"testin\":\"new value\"}]}" ) ) .containsOnly( newO( "test[1]", "{\"test\":\"id\",\"testin\":\"new value\"}" ) ); } @Test public void removeArrayObjectWithoutId() { var schema = "{" + "\"type\":\"object\"," + "\"properties\":{" + " \"test\": {" + " \"type\":\"array\"," + " \"id\":\"{index}\"," + " \"items\":{" + " \"type\":\"object\"," + " \"properties\":{" + " \"test\":{" + " \"type\":\"string\"" + " }," + " \"testin\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + " }" + "}}"; assertThat( diff( schema, "{\"test\":[{\"test\":\"id\",\"testin\":\"new value\"}]}", "{\"test\":[]}" ) ) .containsOnly( delO( "test[0]", "{\"test\":\"id\",\"testin\":\"new value\"}" ) ); } private List<JsonDiff.Line> diff( String schema, String from, String to ) { return JsonDiff.diff( from, to, schema( schema ) ).getDiff(); } private JsonDiff.Line newF( String path, String value ) { return newX( path, value, JsonDiff.Line.LineType.FIELD ); } private JsonDiff.Line newO( String path, String value ) { return newX( path, value, JsonDiff.Line.LineType.OBJECT ); } private JsonDiff.Line newA( String path, String value ) { return newX( path, value, JsonDiff.Line.LineType.ARRAY ); } private JsonDiff.Line newX( String path, String value, JsonDiff.Line.LineType lineType ) { return new JsonDiff.Line( path, lineType, empty(), of( value ) ); } private JsonDiff.Line delF( String path, String value ) { return del( path, JsonDiff.Line.LineType.FIELD, of( value ), empty() ); } private JsonDiff.Line delO( String path, String value ) { return del( path, JsonDiff.Line.LineType.OBJECT, of( value ), empty() ); } private JsonDiff.Line delA( String path, String value ) { return del( path, JsonDiff.Line.LineType.ARRAY, of( value ), empty() ); } private JsonDiff.Line del( String path, JsonDiff.Line.LineType object, Optional<String> value2, Optional<String> empty ) { return new JsonDiff.Line( path, object, value2, empty ); } private JsonDiff.Line updF( String path, String oldValue, String newValue ) { return upd( path, oldValue, newValue, JsonDiff.Line.LineType.FIELD ); } private JsonDiff.Line updA( String path, String oldValue, String newValue ) { return upd( path, oldValue, newValue, JsonDiff.Line.LineType.ARRAY ); } private JsonDiff.Line upd( String path, String oldValue, String newValue, JsonDiff.Line.LineType lineType ) { return new JsonDiff.Line( path, lineType, of( oldValue ), of( newValue ) ); } }
mit
jessezwd/News
okserver/src/main/java/com/lzy/okserver/download/DownloadService.java
1778
package com.lzy.okserver.download; import android.app.ActivityManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import com.lzy.okgo.OkGo; import java.util.List; /** * ================================================ * 作 者:廖子尧 * 版 本:1.0 * 创建日期:2016/1/25 * 描 述: * 修订历史: * ================================================ */ public class DownloadService extends Service { @Override public IBinder onBind(Intent intent) { return null; } private static DownloadManager DOWNLOAD_MANAGER; /** start 方式开启服务,保存全局的下载管理对象 */ public static DownloadManager getDownloadManager() { Context context = OkGo.getContext(); if (!DownloadService.isServiceRunning(context)) context.startService(new Intent(context, DownloadService.class)); if (DownloadService.DOWNLOAD_MANAGER == null) DownloadService.DOWNLOAD_MANAGER = DownloadManager.getInstance(); return DOWNLOAD_MANAGER; } public static boolean isServiceRunning(Context context) { boolean isRunning = false; ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE); if (serviceList == null || serviceList.size() == 0) return false; for (int i = 0; i < serviceList.size(); i++) { if (serviceList.get(i).service.getClassName().equals(DownloadService.class.getName())) { isRunning = true; break; } } return isRunning; } }
mit
jakubkolar/autobuilder
src/main/java/com/github/jakubkolar/autobuilder/impl/BeanResolver.java
5985
/* * The MIT License (MIT) * * Copyright (c) 2016 Jakub Kolar * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.jakubkolar.autobuilder.impl; import com.github.jakubkolar.autobuilder.spi.ValueResolver; import com.google.common.base.Preconditions; import org.objenesis.Objenesis; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Inject; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; class BeanResolver implements ValueResolver { private final Objenesis objenesis; @Nullable private ValueResolver fieldsResolver; @Inject public BeanResolver(Objenesis objenesis) { this.objenesis = objenesis; } @Nullable @Override public <T> T resolve(Class<T> type, Optional<Type> typeInfo, String name, Collection<Annotation> annotations) { // Objects should be resolved by Built-in resolvers, otherwise we are trying // to resolve some non-reifiable type and we can only say that is of type Object // (e.g. type variable T) if (Objects.equals(type, Object.class)) { throw new UnsupportedOperationException( String.format( "Cannot resolve value for non-reifiable type '%s' with name %s " + "annotated with %s because the actual class to be resolved cannot be " + "determined at runtime (at least in a safe way that would avoid " + "ClassCastException)", typeInfo.get(), name, annotations.toString())); } try { T instance = objenesis.newInstance(type); // TODO: unsupported operation exception here? Preconditions.checkNotNull(instance); // Now try to initialize the fields for (Field field : getAllFields(type)) { // Do not touch static fields if (Modifier.isStatic(field.getModifiers())) { continue; } // Groovy will initialize this in the getter if (isGroovyMetaClass(type, field)) { continue; } field.setAccessible(true); // TODO: try to catch field related exceptions? Object fieldValue = resolveField(name, field); field.set(instance, fieldValue); } return instance; } // Any kind of exceptions can happen here, because with Objenesis, // reflection and who-knows-what-other hacks are involved catch (Exception | InstantiationError e) { //TODO: catch the Inst.Error or not? throw new UnsupportedOperationException( String.format( "Cannot resolve value for type %s with name %s annotated with %s because of %s: %s", type.toString(), name, annotations.toString(), e.getClass().getSimpleName(), e.getMessage()), e); } } private static <T> Collection<Field> getAllFields(Class<T> type) { Collection<Field> result = new ArrayList<>(); Class<?> currentType = type; while (currentType != null && !currentType.equals(Object.class)) { result.addAll(Arrays.asList(currentType.getDeclaredFields())); currentType = currentType.getSuperclass(); } return result; } private static boolean isGroovyMetaClass(Class<?> resolvedType, Field field) { if (field.getType().getName().equals("groovy.lang.MetaClass") && field.getName().equals("metaClass")) { // Java-based groovy objects if (field.getDeclaringClass().getName().equals("groovy.lang.GroovyObjectSupport")) { return true; } // Groovy objects compiled with groovyc if (field.getDeclaringClass().equals(resolvedType) && field.isSynthetic()) { return true; } } return false; } @Nullable private Object resolveField(String beanName, Field field) { Preconditions.checkNotNull(fieldsResolver, "Field resolver was not properly initialized!"); Class<?> fieldType = field.getType(); String fieldName = field.getName(); List<Annotation> annotations = Arrays.asList(field.getAnnotations()); return fieldsResolver.resolve( fieldType, Optional.ofNullable(field.getGenericType()), beanName + '.' + fieldName, annotations); } public void setFieldsResolver(@Nonnull ValueResolver fieldsResolver) { this.fieldsResolver = fieldsResolver; } }
mit
lagerspetz/getopt-scala
src/main/java/Dummy.java
85
/** This is included to pass the javadoc check on Nexus. */ public class Dummy{ }
mit
AaricChen/qxcmp-framework
qxcmp-core/src/main/java/com/qxcmp/web/view/elements/grid/InternallyCelledGrid.java
390
package com.qxcmp.web.view.elements.grid; import lombok.Getter; import lombok.Setter; /** * 内部单元格网格 * <p> * 该网格会在单元格内部显示边框 * * @author Aaric */ @Getter @Setter public class InternallyCelledGrid extends AbstractGrid { @Override public String getClassContent() { return super.getClassContent() + " internally celled"; } }
mit
SergeyStaroletov/Patterns17
AnanievFastPI41/Ananiev/CourseWork/src/cw/EventListener.java
6226
package cw; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import cw.gui.MainFrame; import cw.gui.form.FormBuilder; import cw.gui.form.FormBuilder.FormType; import cw.model.*; // Обработчик событий, приходящих от основной формы public class EventListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { MainFrame frame = Main.getMainFrame(); switch(e.getActionCommand()) { case "menu-exit": System.exit(0); break; case "disease-selection": case "patient-selection": onListSelectionChanged((JList<?>)e.getSource()); break; case "disease-add": Disease d = new FormBuilder<Disease>(new Disease(), FormType.NEW).show(); if(d != null) Main.getMainFrame().getDiseases().addElement(d); break; case "disease-edit": Disease o = new FormBuilder<Disease>(frame.getDiseases().getElementAt(frame.getDiseasesList().getSelectedIndex()), FormType.EDIT).show(); if(o != null) frame.getDiseasesList().repaint(); break; case "disease-remove": if(confirmDelete()) frame.getDiseases().remove(frame.getDiseasesList().getSelectedIndex()); break; case "patient-add": Patient p = new FormBuilder<Patient>(new Patient(), FormType.NEW).show(); if(p != null) Main.getMainFrame().getPatients().addElement(p); break; case "patient-edit": Patient a = new FormBuilder<Patient>(frame.getPatients().getElementAt(frame.getPatientsList().getSelectedIndex()), FormType.EDIT).show(); if(a != null) frame.getPatientsList().repaint(); break; case "patient-remove": if(confirmDelete()) frame.getPatients().remove(frame.getPatientsList().getSelectedIndex()); break; case "menu-save": File f = Main.getFile() != null ? Main.getFile() : Main.getFileIO().getSaveFile(); if(f != null) { Main.getFileIO().saveToFile(f); Main.setFile(f); } break; case "menu-save-as": File save = Main.getFileIO().getSaveFile(); if(save != null) { Main.getFileIO().saveToFile(save); Main.setFile(save); } break; case "menu-load": File load = Main.getFileIO().getOpenFile(); if(load != null) if(Main.getFileIO().readFromFile(load)) { Main.setFile(load); } else { JOptionPane.showMessageDialog(Main.getMainFrame(), "При чтении выбранного файла возникла ошибка!", "Ошибка", JOptionPane.ERROR_MESSAGE); } break; case "work-positive": case "work-negative": DefaultListModel<Patient> list = Main.getMainFrame().getPatients(); for(int i = 0; i < list.size(); i++) { Patient pa = list.getElementAt(i); pa.setSelected(false); if(pa.getResult() > 0 && e.getActionCommand().endsWith("-positive")) pa.setSelected(true); if(pa.getResult() < 0 && e.getActionCommand().endsWith("-negative")) pa.setSelected(true); } Main.getMainFrame().getPatientsList().repaint(); break; case "work-means": ArrayList<AbstractMeans> popular = new ArrayList<AbstractMeans>(); int pop = 0; for(AbstractMeans m : Main.getMeansAsList()) { int u = m.getUsesCount(); if(popular.isEmpty() || pop < u) { popular.clear(); popular.add(m); pop = u; } else if(pop == u) { popular.add(m); } m.setSelected(false); } for(AbstractMeans m : popular) m.setSelected(true); Main.getMainFrame().getShelves().repaint(); break; case "work-diseases": DefaultListModel<Disease> dis = Main.getMainFrame().getDiseases(); for(int i = 0; i < dis.size(); i++) dis.getElementAt(i).setSelected(dis.getElementAt(i).isPositive()); Main.getMainFrame().getDiseasesList().repaint(); break; case "work-reset": DefaultListModel<Patient> l = Main.getMainFrame().getPatients(); for(int i = 0; i < l.size(); i++) l.getElementAt(i).setSelected(false); DefaultListModel<Disease> j = Main.getMainFrame().getDiseases(); for(int i = 0; i < j.size(); i++) j.getElementAt(i).setSelected(false); for(AbstractMeans m : Main.getMeansAsList()) m.setSelected(false); Main.getMainFrame().repaint(); break; default: System.out.println(e.getActionCommand()); } } public void onCanvasClick(int x, int y) { if(Main.getMeans()[x][y] == null) { String[] options = new String[] {"Травяной сбор", "Настойка"}; String selected = (String) JOptionPane.showInputDialog(Main.getMainFrame(), "Выберите тип добавляемого средства", "Добавление средства", JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if(selected != null) { AbstractMeans m = null; if(selected.equals(options[1])) { m = new FormBuilder<Tincture>(new Tincture(), FormType.NEW).show(); } else { m = new FormBuilder<Herbal>(new Herbal(), FormType.NEW).show(); } if(m != null) { m.setLocation(x, y); Main.getMeans()[x][y] = m; Main.getMainFrame().getShelves().reloadSlot(x, y); } } } else { Object o = new FormBuilder<AbstractMeans>(Main.getMeans()[x][y], FormType.EDIT_DELETE).show(); if(o == null) { Main.getMeans()[x][y] = null; Main.getMainFrame().getShelves().reloadSlot(x, y); } } } private void onListSelectionChanged(JList<?> list) { JPanel buttonsPanel = (JPanel)list.getParent().getParent().getParent().getComponents()[1]; for(Component c : buttonsPanel.getComponents()) if(c instanceof JButton) { JButton b = (JButton)c; if(b.getActionCommand().endsWith("-edit") || b.getActionCommand().endsWith("-remove")) b.setEnabled(list.getSelectedIndex() != -1); } } public static boolean confirmDelete() { return JOptionPane.showConfirmDialog(Main.getMainFrame(), "Вы действительно хотите удалить запись?", "Подтверждение", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; } }
mit
umireon/sw_library
src/main/java/info/umireon/sw_library/ControlMaterial.java
3701
/* * The MIT License * * Copyright 2014 umireon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package info.umireon.sw_library; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * 資料を管理するコントロールです. * @author Kaito Udagawa */ public class ControlMaterial { /** * 貸出可能日数です. */ public static final int DUE_DAYS = 14; /** * 資料の一覧です. */ private final Map<String, EntityMaterial> materials; /** * 空の資料管理を作成します. */ public ControlMaterial() { materials = new HashMap<>(); } /** * 資料一覧を取得します. * @return 資料一覧itirann */ public final Collection<EntityMaterial> getMaterials() { return materials.values(); } /** * 資料名から, 資料を取得します. * @param name 資料名 * @return 利用者名に対応する利用者, 存在しない場合は <code>null</code> */ public final EntityMaterial getMaterial(final String name) { return materials.get(name); } /** * 資料を追加します. * @param material 追加する資料 */ public final void addMaterial(final EntityMaterial material) { materials.put(material.getName(), material); } /** * 資料を貸出します. * @param materialName 資料名 * @param borrower 貸出する利用者 * @throws UnknownMaterialException 資料が存在しない場合 * @throws UnavailableMaterialException 資料が利用可能ではない場合 * @throws ReservedMaterialException 資料が予約されていて, 利用可能ではない場合 */ public final void lendMaterial(final String materialName, final EntityUser borrower) throws UnknownMaterialException, UnavailableMaterialException, ReservedMaterialException { EntityMaterial material; material = getMaterial(materialName); if (material == null) { throw new UnknownMaterialException(); } if (material.getStatus() != null) { throw new UnavailableMaterialException(); } if (material.isReserved()) { if (material.peekReservation().getReserver() == borrower) { material.pollReservation(); } else { throw new ReservedMaterialException(); } } EntityDate today, due; today = new EntityDate(); due = today.addDays(DUE_DAYS); material.setStatus(new EntityLoan(borrower, due)); } }
mit
martinb741/Recommender
src/main/i5/las2peer/services/recommender/librec/rating/LLORMA.java
9313
package i5.las2peer.services.recommender.librec.rating; import java.util.List; import i5.las2peer.services.recommender.librec.data.DenseMatrix; import i5.las2peer.services.recommender.librec.data.DenseVector; import i5.las2peer.services.recommender.librec.data.MatrixEntry; import i5.las2peer.services.recommender.librec.data.SparseMatrix; import i5.las2peer.services.recommender.librec.intf.IterativeRecommender; import i5.las2peer.services.recommender.librec.intf.Recommender; import i5.las2peer.services.recommender.librec.util.KernelSmoothing; import i5.las2peer.services.recommender.librec.util.Logs; /** * <h3>Local Low-Rank Matrix Approximation</h3> * <p> * This implementation refers to the method proposed by Lee et al. at ICML 2013. * <p> * <strong>Lcoal Structure:</strong> Joonseok Lee, <strong>Local Low-Rank Matrix * Approximation </strong>, ICML. 2013: 82-90. * * @author wubin */ public class LLORMA extends IterativeRecommender { private static int localNumFactors; private static int localNumIters; private static int multiThreadCount; protected static float localRegU, localRegI; private float localLRate; private SparseMatrix predictMatrix; private static int modelMax; private static SparseMatrix testIndexMatrix;// test index matrix for predict private SparseMatrix cumPrediction, cumWeight; public LLORMA(SparseMatrix trainMatrix, SparseMatrix testMatrix, int fold) { super(trainMatrix, testMatrix, fold); algoOptions = cf.getParamOptions("LLORMA"); localNumFactors = algoOptions.getInt("-lnf", 20); multiThreadCount = algoOptions.getInt("-mtc", 4); modelMax = algoOptions.getInt("-mm", 50); multiThreadCount = multiThreadCount > modelMax ? modelMax : multiThreadCount; localNumIters = algoOptions.getInt("-lni", 100); localLRate = algoOptions.getFloat("-lr", 0.01f); localRegI = algoOptions.getFloat("-lu", 0.001f); localRegU = algoOptions.getFloat("-li", 0.001f); predictMatrix = new SparseMatrix(testMatrix); } @Override protected void initModel() throws Exception { testIndexMatrix = new SparseMatrix(testMatrix); for (MatrixEntry me : testIndexMatrix) { int u = me.row(); int i = me.column(); testIndexMatrix.set(u, i, 0.0); } // global svd P Q to calculate the kernel value between users (or items) P = new DenseMatrix(numUsers, numFactors); Q = new DenseMatrix(numItems, numFactors); // initialize model if (initByNorm) { P.init(initMean, initStd); Q.init(initMean, initStd); } else { P.init(); // P.init(smallValue); Q.init(); // Q.init(smallValue); } this.buildGlobalModel(); } // global svd P Q private void buildGlobalModel() throws Exception { for (int iter = 1; iter <= numIters; iter++) { for (MatrixEntry me : trainMatrix) { int u = me.row(); // user int i = me.column(); // item double rui = me.get(); double pui = DenseMatrix.rowMult(P, u, Q, i); double eui = rui - pui; // update factors for (int f = 0; f < numFactors; f++) { double puf = P.get(u, f), qif = Q.get(i, f); P.add(u, f, lRate * (eui * qif - regU * puf)); Q.add(i, f, lRate * (eui * puf - regI * qif)); } } } // end of training } @Override protected void buildModel() throws Exception { // Pre-calculating similarity: int completeModelCount = 0; LLORMAUpdater[] learners = new LLORMAUpdater[multiThreadCount]; int[] anchorUser = new int[modelMax]; int[] anchorItem = new int[modelMax]; int modelCount = 0; int[] runningThreadList = new int[multiThreadCount]; int runningThreadCount = 0; int waitingThreadPointer = 0; int nextRunningSlot = 0; cumPrediction = new SparseMatrix(testIndexMatrix); cumWeight = new SparseMatrix(testIndexMatrix); // Parallel training: while (completeModelCount < modelMax) { int u_t = (int) Math.floor(Math.random() * numUsers); List<Integer> itemList = trainMatrix.getColumns(u_t); if (itemList != null) { if (runningThreadCount < multiThreadCount && modelCount < modelMax) { // Selecting a new anchor point: int idx = (int) Math.floor(Math.random() * itemList.size()); int i_t = itemList.get(idx); anchorUser[modelCount] = u_t; anchorItem[modelCount] = i_t; // Preparing weight vectors: DenseVector w = kernelSmoothing(numUsers, u_t, KernelSmoothing.EPANECHNIKOV_KERNEL, 0.8, false); DenseVector v = kernelSmoothing(numItems, i_t, KernelSmoothing.EPANECHNIKOV_KERNEL, 0.8, true); // Starting a new local model learning: learners[nextRunningSlot] = new LLORMAUpdater(modelCount, localNumFactors, numUsers, numItems, u_t, i_t, localLRate, localRegU, localRegI, localNumIters, w, v, trainMatrix); learners[nextRunningSlot].start(); runningThreadList[runningThreadCount] = modelCount; runningThreadCount++; modelCount++; nextRunningSlot++; } else if (runningThreadCount > 0) { // Joining a local model which was done with learning: try { learners[waitingThreadPointer].join(); } catch (InterruptedException ie) { System.out.println("Join failed: " + ie); } int mp = waitingThreadPointer; int mc = completeModelCount; completeModelCount++; // Predicting with the new local model and all previous // models: predictMatrix = new SparseMatrix(testIndexMatrix); for (MatrixEntry me : testMatrix) { int u = me.row(); int i = me.column(); double weight = KernelSmoothing.kernelize(getUserSimilarity(anchorUser[mc], u), 0.8, KernelSmoothing.EPANECHNIKOV_KERNEL) * KernelSmoothing.kernelize(getItemSimilarity(anchorItem[mc], i), 0.8, KernelSmoothing.EPANECHNIKOV_KERNEL); double newPrediction = (learners[mp].getUserFeatures().row(u) .inner(learners[mp].getItemFeatures().row(i))) * weight; cumWeight.set(u, i, cumWeight.get(u, i) + weight); cumPrediction.set(u, i, cumPrediction.get(u, i) + newPrediction); double prediction = cumPrediction.get(u, i) / cumWeight.get(u, i); if (Double.isNaN(prediction) || prediction == 0.0) { prediction = globalMean; } if (prediction < minRate) { prediction = minRate; } else if (prediction > maxRate) { prediction = maxRate; } predictMatrix.set(u, i, prediction); } if (completeModelCount % 5 == 0) { Logs.debug("{}{} iter {}:[MAE,RMSE,NMAE,rMAE,rRMSE,MPE] {}", algoName, foldInfo, completeModelCount, "[" + Recommender.getEvalInfo(evalRatings()) + "]"); } nextRunningSlot = waitingThreadPointer; waitingThreadPointer = (waitingThreadPointer + 1) % multiThreadCount; runningThreadCount--; } } } } /** * Calculate similarity between two users, based on the global base SVD. * * @param idx1 * The first user's ID. * @param idx2 * The second user's ID. * @return The similarity value between two users idx1 and idx2. */ private double getUserSimilarity(int idx1, int idx2) { double sim; DenseVector u_vec = P.row(idx1); DenseVector v_vec = P.row(idx2); sim = 1 - 2.0 / Math.PI * Math.acos(u_vec.inner(v_vec) / (Math.sqrt(u_vec.inner(u_vec)) * Math.sqrt(v_vec.inner(v_vec)))); if (Double.isNaN(sim)) { sim = 0.0; } return sim; } /** * Calculate similarity between two items, based on the global base SVD. * * @param idx1 * The first item's ID. * @param idx2 * The second item's ID. * @return The similarity value between two items idx1 and idx2. */ private double getItemSimilarity(int idx1, int idx2) { double sim; DenseVector i_vec = Q.row(idx1); DenseVector j_vec = Q.row(idx2); sim = 1 - 2.0 / Math.PI * Math.acos(i_vec.inner(j_vec) / (Math.sqrt(i_vec.inner(i_vec)) * Math.sqrt(j_vec.inner(j_vec)))); if (Double.isNaN(sim)) { sim = 0.0; } return sim; } /** * Given the similarity, it applies the given kernel. This is done either * for all users or for all items. * * @param size * The length of user or item vector. * @param id * The identifier of anchor point. * @param kernelType * The type of kernel. * @param width * Kernel width. * @param isItemFeature * return item kernel if yes, return user kernel otherwise. * @return The kernel-smoothed values for all users or all items. */ private DenseVector kernelSmoothing(int size, int id, int kernelType, double width, boolean isItemFeature) { DenseVector newFeatureVector = new DenseVector(size); newFeatureVector.set(id, 1.0); for (int i = 0; i < size; i++) { double sim; if (isItemFeature) { sim = getItemSimilarity(i, id); } else { sim = getUserSimilarity(i, id); } newFeatureVector.set(i, KernelSmoothing.kernelize(sim, width, kernelType)); } return newFeatureVector; } @Override protected double predict(int u, int i) throws Exception { return predictMatrix.get(u, i); } }
cc0-1.0
hugomanguinhas/europeana
edm-shapes/src/main/java/eu/europeana/edm/shapes/ShapesUtils.java
2046
/** * */ package eu.europeana.edm.shapes; import java.io.InputStream; import java.io.PrintStream; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ResIterator; import org.apache.jena.rdf.model.Resource; import org.apache.jena.util.FileUtils; import org.topbraid.shacl.vocabulary.SH; import org.topbraid.spin.util.JenaUtil; import static eu.europeana.edm.shapes.ShapesConstants.*; import static eu.europeana.edm.shapes.SHACLNamespace.*; import static eu.europeana.edm.EDMNamespace.*; /** * @author Hugo Manguinhas <hugo.manguinhas@europeana.eu> * @since 8 Dec 2015 */ public class ShapesUtils { /*************************************************************************** * Public Methods **************************************************************************/ public static Model getSHACL() { Model m = JenaUtil.createDefaultModel(); InputStream is = SH.class.getResourceAsStream("/etc/shacl.ttl"); m.read(is, SH.BASE_URI, FileUtils.langTurtle); return m; } // Load the shapes Model (here, includes the dataModel // because that has templates in it) public static Model getShapesModel(InputStream is) { Class c = ShapesUtils.class; Model model = JenaUtil.createMemoryModel(); model.read(is, "urn:dummy", FileUtils.langTurtle); return model; } public static Model getShapesForEDMExternal() { Class c = ShapesUtils.class; InputStream is = c.getResourceAsStream(EDM_EXTERNAL_SHAPES_LOCATION); return getShapesModel(is); } public static void print(Model results, PrintStream ps) { ps.println(results); ResIterator iter = results.listResourcesWithProperty( results.getProperty(RDF_TYPE) , results.getResource(SHACL_RESULT)); while(iter.hasNext()) { print(iter.nextResource(), ps); } } private static void print(Resource r, PrintStream ps) { System.out.println(r); } }
cc0-1.0
rolandweber/pityoulish
src/main/java/pityoulish/jrmi/api/RemoteTicketIssuer.java
1806
/* * This work is released into the Public Domain under the * terms of the Creative Commons CC0 1.0 Universal license. * https://creativecommons.org/publicdomain/zero/1.0/ */ package pityoulish.jrmi.api; import java.rmi.Remote; import java.rmi.RemoteException; /** * Remote API for managing tickets. * On the caller side, tickets are represented by their token, a string. */ public interface RemoteTicketIssuer extends Remote { /** * Obtains a ticket. * * @param username the username for which to obtain the ticket * * @return the token of a newly issued ticket for the given user. * If the request is denied, an exception is thrown. * * @throws APIException in case of an application-level problem * @throws RemoteException in case of an infrastructure problem */ public String obtainTicket(String username) throws RemoteException, APIException ; /** * Returns and invalidates a ticket. * * @param ticket the {@link #obtainTicket token} of the ticket to return * * @throws APIException in case of an application-level problem * @throws RemoteException in case of an infrastructure problem */ public void returnTicket(String ticket) throws RemoteException, APIException ; /** * Replaces a valid ticket. * * @param ticket the {@link #obtainTicket token} of the ticket to replace * * @return the token of a newly issued ticket for the same user. * If the request is denied, an exception is thrown. * * @throws APIException in case of an application-level problem * @throws RemoteException in case of an infrastructure problem */ public String replaceTicket(String ticket) throws RemoteException, APIException ; }
cc0-1.0
ZagasTales/HistoriasdeZagas
src Graf/es/thesinsprods/zagastales/juegozagas/jugar/master/InfoWeap2NPC.java
8529
package es.thesinsprods.zagastales.juegozagas.jugar.master; import java.awt.Color; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import es.thesinsprods.resources.font.MorpheusFont; public class InfoWeap2NPC { private JFrame frame; public JFrame getFrame() { return frame; } public void setFrame(JFrame frame) { this.frame = frame; } private final JPanel contentPanel = new JPanel(); private JTextField txtDescripcin; private JTextField textField_1; private JTextField textField; private JTextField txtesArrojadiza; private JTextField textField_3; private JTextField txtposesin; private JTextField textField_4; private JLabel lblNewLabel; MorpheusFont mf = new MorpheusFont(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { InfoWeap2NPC window = new InfoWeap2NPC(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public InfoWeap2NPC() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.getContentPane().setBackground(new Color(205, 133, 63)); frame.setIconImage(Toolkit.getDefaultToolkit().getImage( ArmasNPC.class .getResource("/images/Historias de Zagas, logo.png"))); frame.setTitle("Historias de Zagas"); frame.setBounds(100, 100, 380, 301); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setResizable(false); frame.getContentPane().setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(135, 51, 221, 99); frame.getContentPane().add(scrollPane); JTextArea textArea = new JTextArea(); textArea.setBackground(Color.WHITE); textArea.setFont(mf.MyFont(0, 13)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setEditable(false); scrollPane.setViewportView(textArea); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(135, 153, 221, 99); frame.getContentPane().add(scrollPane_1); JTextArea textArea_1 = new JTextArea(); textArea_1.setBackground(Color.WHITE); textArea_1.setWrapStyleWord(true); textArea_1.setText(""); textArea_1.setLineWrap(true); textArea_1.setFont(mf.MyFont(0, 13)); textArea_1.setEditable(false); scrollPane_1.setViewportView(textArea_1); if (ModificarEquipo.weapon2.isPosesion() == true ||ModificarEquipo.weapon2.isLegendaria() == true) { ArrayList<String> pos = ModificarEquipo.weapon2.getPossesion().getPos(); for (int i = 0; i < pos.size(); i++) { if (pos.get(i) != ("-Propiedad-")) { textArea_1.append(pos.get(i) + "\n"); } } } txtDescripcin = new JTextField(); txtDescripcin.setOpaque(false); txtDescripcin.setForeground(Color.WHITE); txtDescripcin.setBackground(new Color(205, 133, 63)); txtDescripcin.setText("Descripci\u00F3n:"); txtDescripcin.setFont(mf.MyFont(0, 13)); txtDescripcin.setEditable(false); txtDescripcin.setColumns(10); txtDescripcin.setBorder(null); txtDescripcin.setBounds(135, 20, 90, 20); frame.getContentPane().add(txtDescripcin); textField_1 = new JTextField(); textField_1.setOpaque(false); textField_1.setForeground(Color.WHITE); textField_1.setBackground(new Color(205, 133, 63)); textField_1.setText("Tipo de Arma:"); textField_1.setFont(mf.MyFont(0, 13)); textField_1.setEditable(false); textField_1.setColumns(10); textField_1.setBorder(null); textField_1.setBounds(10, 20, 90, 20); frame.getContentPane().add(textField_1); textField = new JTextField(); textField.setBackground(Color.WHITE); textField.setEditable(false); textField.setFont(mf.MyFont(0, 11)); textField.setColumns(10); textField.setBounds(10, 51, 115, 20); frame.getContentPane().add(textField); final JButton btnVolver = new JButton(""); btnVolver.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { btnVolver.setIcon(new ImageIcon(InfoAcc1NPC.class .getResource("/images/boton atras2.png"))); } public void mouseReleased(MouseEvent e) { btnVolver.setIcon(new ImageIcon(InfoAcc1NPC.class .getResource("/images/boton atras.png"))); } }); btnVolver.setIcon(new ImageIcon(InfoWeap2NPC.class .getResource("/images/boton atras.png"))); btnVolver.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null)); btnVolver.setForeground(new Color(255, 255, 255)); btnVolver.setBackground(new Color(139, 69, 19)); btnVolver.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); } }); btnVolver.setFont(mf.MyFont(0, 15)); btnVolver.setBounds(10, 206, 99, 45); btnVolver.setBorderPainted(false); btnVolver.setContentAreaFilled(false); btnVolver.setFocusPainted(false); btnVolver.setOpaque(false); frame.getContentPane().add(btnVolver); txtesArrojadiza = new JTextField(); txtesArrojadiza.setOpaque(false); txtesArrojadiza.setForeground(Color.WHITE); txtesArrojadiza.setBackground(new Color(205, 133, 63)); txtesArrojadiza.setText("Subclase:"); txtesArrojadiza.setFont(mf.MyFont(0, 13)); txtesArrojadiza.setEditable(false); txtesArrojadiza.setColumns(10); txtesArrojadiza.setBorder(null); txtesArrojadiza.setBounds(10, 82, 90, 20); txtesArrojadiza.setText(ModificarEquipo.weapon2.getTipo()); frame.getContentPane().add(txtesArrojadiza); textField_3 = new JTextField(); textField_3.setBackground(Color.WHITE); textField_3.setFont(mf.MyFont(0, 11)); textField_3.setEditable(false); textField_3.setColumns(10); textField_3.setText(ModificarEquipo.weapon2.getTipo()); textField_3.setBounds(10, 113, 115, 20); frame.getContentPane().add(textField_3); if (ModificarEquipo.weapon2.getClass().getSimpleName().equals("OneHanded")) { textField.setText("Arma de una mano"); } if (ModificarEquipo.weapon2.getClass().getSimpleName().equals("TwoHanded")) { textField.setText("Arma de dos manos"); } if (ModificarEquipo.weapon2.getClass().getSimpleName().equals("Pole")) { textField.setText("Arma de asta"); } if (ModificarEquipo.weapon2.getClass().getSimpleName().equals("Ranged")) { textField.setText("Arma a Distancia"); } if (ModificarEquipo.weapon2.getClass().getSimpleName().equals("Shields")) { textField.setText("Escudo"); } textArea.setText(ModificarEquipo.weapon2.getDescription()); txtposesin = new JTextField(); txtposesin.setOpaque(false); txtposesin.setForeground(Color.WHITE); txtposesin.setBackground(new Color(205, 133, 63)); txtposesin.setText("\u00BFPosesi\u00F3n?"); txtposesin.setFont(mf.MyFont(0, 13)); txtposesin.setEditable(false); txtposesin.setColumns(10); txtposesin.setBorder(null); txtposesin.setBounds(10, 144, 90, 20); frame.getContentPane().add(txtposesin); textField_4 = new JTextField(); textField_4.setBackground(Color.WHITE); textField_4.setFont(mf.MyFont(0, 11)); if (ModificarEquipo.weapon2.isPosesion() == true) { textField_4.setText("Posesión"); } if (ModificarEquipo.weapon2.isPosesion() == false) { textField_4.setText("Normal"); } if (ModificarEquipo.weapon2.isLegendaria() == true) { textField_4.setText("Legendario"); } textField_4.setEditable(false); textField_4.setColumns(10); textField_4.setBounds(10, 175, 115, 20); frame.getContentPane().add(textField_4); lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon(InfoWeap2NPC.class .getResource("/images/background-infos.jpg"))); lblNewLabel.setBounds(0, 0, 374, 273); frame.getContentPane().add(lblNewLabel); txtesArrojadiza.setText("Subclase:"); } }
cc0-1.0
gorkem/java-language-server
org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/hover/JavaElementLabelComposer.java
45179
/******************************************************************************* * Copyright (c) 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ls.core.internal.hover; import java.util.jar.Attributes.Name; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.BindingKey; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IAnnotation; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ILocalVariable; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMemberValuePair; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeParameter; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.SourceRange; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; import org.eclipse.jdt.ls.core.internal.javadoc.JavaElementLinks; import org.eclipse.osgi.util.NLS; /** * Implementation of {@link JavaElementLabels}. * * @since 3.5 */ public class JavaElementLabelComposer { /** * An adapter for builder supported by the label composer. */ public static abstract class FlexibleBuilder { /** * Appends the string representation of the given character to the builder. * * @param ch the character to append * @return a reference to this object */ public abstract FlexibleBuilder append(char ch); /** * Appends the given string to the builder. * * @param string the string to append * @return a reference to this object */ public abstract FlexibleBuilder append(String string); /** * Returns the length of the the builder. * * @return the length of the current string */ public abstract int length(); } public static class FlexibleStringBuilder extends FlexibleBuilder { private final StringBuilder builder; public FlexibleStringBuilder(StringBuilder builder) { this.builder= builder; } @Override public FlexibleBuilder append(char ch) { builder.append(ch); return this; } @Override public FlexibleBuilder append(String string) { builder.append(string); return this; } @Override public int length() { return builder.length(); } @Override public String toString() { return builder.toString(); } } final static long QUALIFIER_FLAGS= JavaElementLabels.P_COMPRESSED | JavaElementLabels.USE_RESOLVED; /* * Package name compression */ private static String fgPkgNamePrefix; private static String fgPkgNamePostfix; private static int fgPkgNameChars; private static int fgPkgNameLength= -1; protected final FlexibleBuilder fBuilder; protected static final boolean getFlag(long flags, long flag) { return (flags & flag) != 0; } /** * Creates a new java element composer based on the given builder. * * @param builder the builder */ public JavaElementLabelComposer(FlexibleBuilder builder) { fBuilder= builder; } /** * Creates a new java element composer based on the given builder. * * @param builder the builder */ public JavaElementLabelComposer(StringBuilder builder) { this(new FlexibleStringBuilder(builder)); } /** * Appends the label for a Java element with the flags as defined by this class. * * @param element the element to render * @param flags the rendering flags. */ public void appendElementLabel(IJavaElement element, long flags) { int type= element.getElementType(); IPackageFragmentRoot root= null; if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT && type != IJavaElement.PACKAGE_FRAGMENT_ROOT) { root= JavaModelUtil.getPackageFragmentRoot(element); } if (root != null && getFlag(flags, JavaElementLabels.PREPEND_ROOT_PATH)) { appendPackageFragmentRootLabel(root, JavaElementLabels.ROOT_QUALIFIED); fBuilder.append(JavaElementLabels.CONCAT_STRING); } switch (type) { case IJavaElement.METHOD: appendMethodLabel((IMethod) element, flags); break; case IJavaElement.FIELD: appendFieldLabel((IField) element, flags); break; case IJavaElement.LOCAL_VARIABLE: appendLocalVariableLabel((ILocalVariable) element, flags); break; case IJavaElement.TYPE_PARAMETER: appendTypeParameterLabel((ITypeParameter) element, flags); break; case IJavaElement.INITIALIZER: appendInitializerLabel((IInitializer) element, flags); break; case IJavaElement.TYPE: appendTypeLabel((IType) element, flags); break; case IJavaElement.CLASS_FILE: appendClassFileLabel((IClassFile) element, flags); break; case IJavaElement.COMPILATION_UNIT: appendCompilationUnitLabel((ICompilationUnit) element, flags); break; case IJavaElement.PACKAGE_FRAGMENT: appendPackageFragmentLabel((IPackageFragment) element, flags); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: appendPackageFragmentRootLabel((IPackageFragmentRoot) element, flags); break; case IJavaElement.IMPORT_CONTAINER: case IJavaElement.IMPORT_DECLARATION: case IJavaElement.PACKAGE_DECLARATION: appendDeclarationLabel(element, flags); break; case IJavaElement.JAVA_PROJECT: case IJavaElement.JAVA_MODEL: fBuilder.append(element.getElementName()); break; default: fBuilder.append(element.getElementName()); } if (root != null && getFlag(flags, JavaElementLabels.APPEND_ROOT_PATH)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendPackageFragmentRootLabel(root, JavaElementLabels.ROOT_QUALIFIED); } } /** * Appends the label for a method. Considers the M_* flags. * * @param method the element to render * @param flags the rendering flags. Flags with names starting with 'M_' are considered. */ public void appendMethodLabel(IMethod method, long flags) { try { BindingKey resolvedKey= getFlag(flags, JavaElementLabels.USE_RESOLVED) && method.isResolved() ? new BindingKey(method.getKey()) : null; String resolvedSig= (resolvedKey != null) ? resolvedKey.toSignature() : null; // type parameters if (getFlag(flags, JavaElementLabels.M_PRE_TYPE_PARAMETERS)) { if (resolvedKey != null) { if (resolvedKey.isParameterizedMethod()) { String[] typeArgRefs= resolvedKey.getTypeArguments(); if (typeArgRefs.length > 0) { appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags); fBuilder.append(' '); } } else { String[] typeParameterSigs= Signature.getTypeParameters(resolvedSig); if (typeParameterSigs.length > 0) { appendTypeParameterSignaturesLabel(typeParameterSigs, flags); fBuilder.append(' '); } } } else if (method.exists()) { ITypeParameter[] typeParameters= method.getTypeParameters(); if (typeParameters.length > 0) { appendTypeParametersLabels(typeParameters, flags); fBuilder.append(' '); } } } // return type if (getFlag(flags, JavaElementLabels.M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) { String returnTypeSig= resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType(); appendTypeSignatureLabel(method, returnTypeSig, flags); fBuilder.append(' '); } // qualification if (getFlag(flags, JavaElementLabels.M_FULLY_QUALIFIED)) { appendTypeLabel(method.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuilder.append('.'); } fBuilder.append(getElementName(method)); // constructor type arguments if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS) && method.exists() && method.isConstructor()) { if (resolvedSig != null && resolvedKey.isParameterizedType()) { BindingKey declaringType= resolvedKey.getDeclaringType(); if (declaringType != null) { String[] declaringTypeArguments= declaringType.getTypeArguments(); appendTypeArgumentSignaturesLabel(method, declaringTypeArguments, flags); } } } // parameters fBuilder.append('('); String[] declaredParameterTypes= method.getParameterTypes(); if (getFlag(flags, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES)) { String[] types= null; int nParams= 0; boolean renderVarargs= false; boolean isPolymorphic= false; if (getFlag(flags, JavaElementLabels.M_PARAMETER_TYPES)) { if (resolvedSig != null) { types= Signature.getParameterTypes(resolvedSig); } else { types= declaredParameterTypes; } nParams= types.length; renderVarargs= method.exists() && Flags.isVarargs(method.getFlags()); if (renderVarargs && resolvedSig != null && declaredParameterTypes.length == 1 && JavaModelUtil.isPolymorphicSignature(method)) { renderVarargs= false; isPolymorphic= true; } } String[] names= null; if (getFlag(flags, JavaElementLabels.M_PARAMETER_NAMES) && method.exists()) { names= method.getParameterNames(); if (isPolymorphic) { // handled specially below } else if (types == null) { nParams= names.length; } else { // types != null if (nParams != names.length) { if (resolvedSig != null && types.length > names.length) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=99137 nParams= names.length; String[] typesWithoutSyntheticParams= new String[nParams]; System.arraycopy(types, types.length - nParams, typesWithoutSyntheticParams, 0, nParams); types= typesWithoutSyntheticParams; } else { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=101029 // JavaPlugin.logErrorMessage("JavaElementLabels: Number of param types(" + nParams + ") != number of names(" + names.length + "): " + method.getElementName()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ names= null; // no names rendered } } } } ILocalVariable[] annotatedParameters= null; if (nParams > 0 && getFlag(flags, JavaElementLabels.M_PARAMETER_ANNOTATIONS)) { annotatedParameters= method.getParameters(); } for (int i= 0; i < nParams; i++) { if (i > 0) { fBuilder.append(JavaElementLabels.COMMA_STRING); } if (annotatedParameters != null && i < annotatedParameters.length) { appendAnnotationLabels(annotatedParameters[i].getAnnotations(), flags); } if (types != null) { String paramSig= types[i]; if (renderVarargs && (i == nParams - 1)) { int newDim= Signature.getArrayCount(paramSig) - 1; appendTypeSignatureLabel(method, Signature.getElementType(paramSig), flags); for (int k= 0; k < newDim; k++) { fBuilder.append('[').append(']'); } fBuilder.append(JavaElementLabels.ELLIPSIS_STRING); } else { appendTypeSignatureLabel(method, paramSig, flags); } } if (names != null) { if (types != null) { fBuilder.append(' '); } if (isPolymorphic) { fBuilder.append(names[0] + i); } else { fBuilder.append(names[i]); } } } } else { if (declaredParameterTypes.length > 0) { fBuilder.append(JavaElementLabels.ELLIPSIS_STRING); } } fBuilder.append(')'); if (getFlag(flags, JavaElementLabels.M_EXCEPTIONS)) { String[] types; if (resolvedKey != null) { types= resolvedKey.getThrownExceptions(); } else { types= method.exists() ? method.getExceptionTypes() : new String[0]; } if (types.length > 0) { fBuilder.append(" throws "); //$NON-NLS-1$ for (int i= 0; i < types.length; i++) { if (i > 0) { fBuilder.append(JavaElementLabels.COMMA_STRING); } appendTypeSignatureLabel(method, types[i], flags); } } } if (getFlag(flags, JavaElementLabels.M_APP_TYPE_PARAMETERS)) { if (resolvedKey != null) { if (resolvedKey.isParameterizedMethod()) { String[] typeArgRefs= resolvedKey.getTypeArguments(); if (typeArgRefs.length > 0) { fBuilder.append(' '); appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags); } } else { String[] typeParameterSigs= Signature.getTypeParameters(resolvedSig); if (typeParameterSigs.length > 0) { fBuilder.append(' '); appendTypeParameterSignaturesLabel(typeParameterSigs, flags); } } } else if (method.exists()) { ITypeParameter[] typeParameters= method.getTypeParameters(); if (typeParameters.length > 0) { fBuilder.append(' '); appendTypeParametersLabels(typeParameters, flags); } } } if (getFlag(flags, JavaElementLabels.M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) { fBuilder.append(JavaElementLabels.DECL_STRING); String returnTypeSig= resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType(); appendTypeSignatureLabel(method, returnTypeSig, flags); } // post qualification if (getFlag(flags, JavaElementLabels.M_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendTypeLabel(method.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("", e); // NotExistsException will not reach this point } } protected void appendAnnotationLabels(IAnnotation[] annotations, long flags) throws JavaModelException { for (int j= 0; j < annotations.length; j++) { IAnnotation annotation= annotations[j]; appendAnnotationLabel(annotation, flags); fBuilder.append(' '); } } public void appendAnnotationLabel(IAnnotation annotation, long flags) throws JavaModelException { fBuilder.append('@'); appendTypeSignatureLabel(annotation, Signature.createTypeSignature(annotation.getElementName(), false), flags); IMemberValuePair[] memberValuePairs= annotation.getMemberValuePairs(); if (memberValuePairs.length == 0) { return; } fBuilder.append('('); for (int i= 0; i < memberValuePairs.length; i++) { if (i > 0) { fBuilder.append(JavaElementLabels.COMMA_STRING); } IMemberValuePair memberValuePair= memberValuePairs[i]; fBuilder.append(getMemberName(annotation, annotation.getElementName(), memberValuePair.getMemberName())); fBuilder.append('='); appendAnnotationValue(annotation, memberValuePair.getValue(), memberValuePair.getValueKind(), flags); } fBuilder.append(')'); } public void appendAnnotationValue(IAnnotation annotation, Object value, int valueKind, long flags) throws JavaModelException { // Note: To be bug-compatible with Javadoc from Java 5/6/7, we currently don't escape HTML tags in String-valued annotations. if (value instanceof Object[]) { fBuilder.append('{'); Object[] values= (Object[]) value; for (int j= 0; j < values.length; j++) { if (j > 0) { fBuilder.append(JavaElementLabels.COMMA_STRING); } value= values[j]; appendAnnotationValue(annotation, value, valueKind, flags); } fBuilder.append('}'); } else { switch (valueKind) { case IMemberValuePair.K_CLASS: appendTypeSignatureLabel(annotation, Signature.createTypeSignature((String) value, false), flags); fBuilder.append(".class"); //$NON-NLS-1$ break; case IMemberValuePair.K_QUALIFIED_NAME: String name = (String) value; int lastDot= name.lastIndexOf('.'); if (lastDot != -1) { String type= name.substring(0, lastDot); String field= name.substring(lastDot + 1); appendTypeSignatureLabel(annotation, Signature.createTypeSignature(type, false), flags); fBuilder.append('.'); fBuilder.append(getMemberName(annotation, type, field)); break; } // case IMemberValuePair.K_SIMPLE_NAME: // can't implement, since parent type is not known //$FALL-THROUGH$ case IMemberValuePair.K_ANNOTATION: appendAnnotationLabel((IAnnotation) value, flags); break; case IMemberValuePair.K_STRING: fBuilder.append(ASTNodes.getEscapedStringLiteral((String) value)); break; case IMemberValuePair.K_CHAR: fBuilder.append(ASTNodes.getEscapedCharacterLiteral(((Character) value).charValue())); break; default: fBuilder.append(String.valueOf(value)); break; } } } /** * Appends labels for type parameters from type binding array. * * @param typeParameters the type parameters * @param flags flags with render options * @throws JavaModelException ... */ private void appendTypeParametersLabels(ITypeParameter[] typeParameters, long flags) throws JavaModelException { if (typeParameters.length > 0) { fBuilder.append(getLT()); for (int i = 0; i < typeParameters.length; i++) { if (i > 0) { fBuilder.append(JavaElementLabels.COMMA_STRING); } appendTypeParameterWithBounds(typeParameters[i], flags); } fBuilder.append(getGT()); } } /** * Appends the style label for a field. Considers the F_* flags. * * @param field the element to render * @param flags the rendering flags. Flags with names starting with 'F_' are considered. */ public void appendFieldLabel(IField field, long flags) { try { if (getFlag(flags, JavaElementLabels.F_PRE_TYPE_SIGNATURE) && field.exists() && !Flags.isEnum(field.getFlags())) { if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && field.isResolved()) { appendTypeSignatureLabel(field, new BindingKey(field.getKey()).toSignature(), flags); } else { appendTypeSignatureLabel(field, field.getTypeSignature(), flags); } fBuilder.append(' '); } // qualification if (getFlag(flags, JavaElementLabels.F_FULLY_QUALIFIED)) { appendTypeLabel(field.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuilder.append('.'); } fBuilder.append(getElementName(field)); if (getFlag(flags, JavaElementLabels.F_APP_TYPE_SIGNATURE) && field.exists() && !Flags.isEnum(field.getFlags())) { fBuilder.append(JavaElementLabels.DECL_STRING); if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && field.isResolved()) { appendTypeSignatureLabel(field, new BindingKey(field.getKey()).toSignature(), flags); } else { appendTypeSignatureLabel(field, field.getTypeSignature(), flags); } } // post qualification if (getFlag(flags, JavaElementLabels.F_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendTypeLabel(field.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("", e); // NotExistsException will not reach this point } } /** * Appends the styled label for a local variable. * * @param localVariable the element to render * @param flags the rendering flags. Flags with names starting with 'F_' are considered. */ public void appendLocalVariableLabel(ILocalVariable localVariable, long flags) { if (getFlag(flags, JavaElementLabels.F_PRE_TYPE_SIGNATURE)) { appendTypeSignatureLabel(localVariable, localVariable.getTypeSignature(), flags); fBuilder.append(' '); } if (getFlag(flags, JavaElementLabels.F_FULLY_QUALIFIED)) { appendElementLabel(localVariable.getDeclaringMember(), JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuilder.append('.'); } fBuilder.append(getElementName(localVariable)); if (getFlag(flags, JavaElementLabels.F_APP_TYPE_SIGNATURE)) { fBuilder.append(JavaElementLabels.DECL_STRING); appendTypeSignatureLabel(localVariable, localVariable.getTypeSignature(), flags); } // post qualification if (getFlag(flags, JavaElementLabels.F_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendElementLabel(localVariable.getDeclaringMember(), JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); } } /** * Appends the styled label for a type parameter. * * @param typeParameter the element to render * @param flags the rendering flags. Flags with names starting with 'T_' are considered. */ public void appendTypeParameterLabel(ITypeParameter typeParameter, long flags) { try { appendTypeParameterWithBounds(typeParameter, flags); // post qualification if (getFlag(flags, JavaElementLabels.TP_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); IMember declaringMember= typeParameter.getDeclaringMember(); appendElementLabel(declaringMember, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("", e); // NotExistsException will not reach this point } } private void appendTypeParameterWithBounds(ITypeParameter typeParameter, long flags) throws JavaModelException { fBuilder.append(getElementName(typeParameter)); if (typeParameter.exists()) { String[] bounds= typeParameter.getBoundsSignatures(); if (bounds.length > 0 && ! (bounds.length == 1 && "Ljava.lang.Object;".equals(bounds[0]))) { //$NON-NLS-1$ fBuilder.append(" extends "); //$NON-NLS-1$ for (int j= 0; j < bounds.length; j++) { if (j > 0) { fBuilder.append(" & "); //$NON-NLS-1$ } appendTypeSignatureLabel(typeParameter, bounds[j], flags); } } } } /** * Appends the label for a initializer. Considers the I_* flags. * * @param initializer the element to render * @param flags the rendering flags. Flags with names starting with 'I_' are considered. */ public void appendInitializerLabel(IInitializer initializer, long flags) { // qualification if (getFlag(flags, JavaElementLabels.I_FULLY_QUALIFIED)) { appendTypeLabel(initializer.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuilder.append('.'); } fBuilder.append("{...}"); // post qualification if (getFlag(flags, JavaElementLabels.I_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendTypeLabel(initializer.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); } } protected void appendTypeSignatureLabel(IJavaElement enclosingElement, String typeSig, long flags) { int sigKind= Signature.getTypeSignatureKind(typeSig); switch (sigKind) { case Signature.BASE_TYPE_SIGNATURE: fBuilder.append(Signature.toString(typeSig)); break; case Signature.ARRAY_TYPE_SIGNATURE: appendTypeSignatureLabel(enclosingElement, Signature.getElementType(typeSig), flags); for (int dim= Signature.getArrayCount(typeSig); dim > 0; dim--) { fBuilder.append('[').append(']'); } break; case Signature.CLASS_TYPE_SIGNATURE: String baseType= getSimpleTypeName(enclosingElement, typeSig); fBuilder.append(baseType); String[] typeArguments= Signature.getTypeArguments(typeSig); appendTypeArgumentSignaturesLabel(enclosingElement, typeArguments, flags); break; case Signature.TYPE_VARIABLE_SIGNATURE: fBuilder.append(getSimpleTypeName(enclosingElement, typeSig)); break; case Signature.WILDCARD_TYPE_SIGNATURE: char ch= typeSig.charAt(0); if (ch == Signature.C_STAR) { //workaround for bug 85713 fBuilder.append('?'); } else { if (ch == Signature.C_EXTENDS) { fBuilder.append("? extends "); //$NON-NLS-1$ appendTypeSignatureLabel(enclosingElement, typeSig.substring(1), flags); } else if (ch == Signature.C_SUPER) { fBuilder.append("? super "); //$NON-NLS-1$ appendTypeSignatureLabel(enclosingElement, typeSig.substring(1), flags); } } break; case Signature.CAPTURE_TYPE_SIGNATURE: appendTypeSignatureLabel(enclosingElement, typeSig.substring(1), flags); break; case Signature.INTERSECTION_TYPE_SIGNATURE: String[] typeBounds= Signature.getIntersectionTypeBounds(typeSig); appendTypeBoundsSignaturesLabel(enclosingElement, typeBounds, flags); break; default: // unknown } } /** * Returns the simple name of the given type signature. * * @param enclosingElement the enclosing element in which to resolve the signature * @param typeSig a {@link Signature#CLASS_TYPE_SIGNATURE} or {@link Signature#TYPE_VARIABLE_SIGNATURE} * @return the simple name of the given type signature */ protected String getSimpleTypeName(IJavaElement enclosingElement, String typeSig) { return Signature.getSimpleName(Signature.toString(Signature.getTypeErasure(typeSig))); } /** * Returns the simple name of the given member. * * @param enclosingElement the enclosing element * @param typeName the name of the member's declaring type * @param memberName the name of the member * @return the simple name of the member */ protected String getMemberName(IJavaElement enclosingElement, String typeName, String memberName) { return memberName; } private void appendTypeArgumentSignaturesLabel(IJavaElement enclosingElement, String[] typeArgsSig, long flags) { if (typeArgsSig.length > 0) { fBuilder.append(getLT()); for (int i = 0; i < typeArgsSig.length; i++) { if (i > 0) { fBuilder.append(JavaElementLabels.COMMA_STRING); } appendTypeSignatureLabel(enclosingElement, typeArgsSig[i], flags); } fBuilder.append(getGT()); } } private void appendTypeBoundsSignaturesLabel(IJavaElement enclosingElement, String[] typeArgsSig, long flags) { for (int i = 0; i < typeArgsSig.length; i++) { if (i > 0) { fBuilder.append(" | "); //$NON-NLS-1$ } appendTypeSignatureLabel(enclosingElement, typeArgsSig[i], flags); } } /** * Appends labels for type parameters from a signature. * * @param typeParamSigs the type parameter signature * @param flags flags with render options */ private void appendTypeParameterSignaturesLabel(String[] typeParamSigs, long flags) { if (typeParamSigs.length > 0) { fBuilder.append(getLT()); for (int i = 0; i < typeParamSigs.length; i++) { if (i > 0) { fBuilder.append(JavaElementLabels.COMMA_STRING); } fBuilder.append(Signature.getTypeVariable(typeParamSigs[i])); } fBuilder.append(getGT()); } } /** * Returns the string for rendering the '<code>&lt;</code>' character. * * @return the string for rendering '<code>&lt;</code>' */ protected String getLT() { return "<"; //$NON-NLS-1$ } /** * Returns the string for rendering the '<code>&gt;</code>' character. * * @return the string for rendering '<code>&gt;</code>' */ protected String getGT() { return ">"; //$NON-NLS-1$ } /** * Appends the label for a type. Considers the T_* flags. * * @param type the element to render * @param flags the rendering flags. Flags with names starting with 'T_' are considered. */ public void appendTypeLabel(IType type, long flags) { if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) { IPackageFragment pack= type.getPackageFragment(); if (!pack.isDefaultPackage()) { appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS)); fBuilder.append('.'); } } IJavaElement parent= type.getParent(); if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) { IType declaringType= type.getDeclaringType(); if (declaringType != null) { appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuilder.append('.'); } int parentType= parent.getElementType(); if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) { // anonymous or local appendElementLabel(parent, 0); fBuilder.append('.'); } } String typeName; boolean isAnonymous= false; if (type.isLambda()) { typeName= "() -> {...}"; //$NON-NLS-1$ try { String[] superInterfaceSignatures= type.getSuperInterfaceTypeSignatures(); if (superInterfaceSignatures.length > 0) { typeName= typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]); } } catch (JavaModelException e) { //ignore } } else { typeName= getElementName(type); try { isAnonymous= type.isAnonymous(); } catch (JavaModelException e1) { // should not happen, but let's play safe: isAnonymous= typeName.length() == 0; } if (isAnonymous) { try { if (parent instanceof IField && type.isEnum()) { typeName= '{' + JavaElementLabels.ELLIPSIS_STRING + '}'; } else { String supertypeName= null; String[] superInterfaceSignatures= type.getSuperInterfaceTypeSignatures(); if (superInterfaceSignatures.length > 0) { supertypeName= getSimpleTypeName(type, superInterfaceSignatures[0]); } else { String supertypeSignature= type.getSuperclassTypeSignature(); if (supertypeSignature != null) { supertypeName= getSimpleTypeName(type, supertypeSignature); } } if (supertypeName == null) { typeName= "new Anonymous"; } else { typeName= NLS.bind("new {0}() '{'...}", supertypeName); } } } catch (JavaModelException e) { //ignore typeName= "new Anonymous"; } } } fBuilder.append(typeName); if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) { if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) { BindingKey key= new BindingKey(type.getKey()); if (key.isParameterizedType()) { String[] typeArguments= key.getTypeArguments(); appendTypeArgumentSignaturesLabel(type, typeArguments, flags); } else { String[] typeParameters= Signature.getTypeParameters(key.toSignature()); appendTypeParameterSignaturesLabel(typeParameters, flags); } } else if (type.exists()) { try { appendTypeParametersLabels(type.getTypeParameters(), flags); } catch (JavaModelException e) { // ignore } } } // post qualification if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); IType declaringType= type.getDeclaringType(); if (declaringType == null && type.isBinary() && isAnonymous) { // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type String tqn= type.getTypeQualifiedName(); int lastDollar= tqn.lastIndexOf('$'); if (lastDollar != 1) { String declaringTypeCF= tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$ declaringType= type.getPackageFragment().getClassFile(declaringTypeCF).getType(); try { ISourceRange typeSourceRange= type.getSourceRange(); if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) { IJavaElement realParent= declaringType.getTypeRoot().getElementAt(typeSourceRange.getOffset() - 1); if (realParent != null) { parent= realParent; } } } catch (JavaModelException e) { // ignore } } } if (declaringType != null) { appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); int parentType= parent.getElementType(); if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) { // anonymous or local fBuilder.append('.'); appendElementLabel(parent, 0); } } else { appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS); } } } /** * Returns the string for rendering the {@link IJavaElement#getElementName() element name} of * the given element. * <p> * <strong>Note:</strong> This class only calls this helper for those elements where ( * {@link JavaElementLinks}) has the need to render the name differently. * </p> * * @param element the element to render * @return the string for rendering the element name */ protected String getElementName(IJavaElement element) { return element.getElementName(); } /** * Appends the label for a import container, import or package declaration. Considers the D_* flags. * * @param declaration the element to render * @param flags the rendering flags. Flags with names starting with 'D_' are considered. */ public void appendDeclarationLabel(IJavaElement declaration, long flags) { if (getFlag(flags, JavaElementLabels.D_QUALIFIED)) { IJavaElement openable= (IJavaElement) declaration.getOpenable(); if (openable != null) { appendElementLabel(openable, JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuilder.append('/'); } } if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) { fBuilder.append("import declarations"); } else { fBuilder.append(getElementName(declaration)); } // post qualification if (getFlag(flags, JavaElementLabels.D_POST_QUALIFIED)) { IJavaElement openable= (IJavaElement) declaration.getOpenable(); if (openable != null) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendElementLabel(openable, JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED | (flags & QUALIFIER_FLAGS)); } } } /** * Appends the label for a class file. Considers the CF_* flags. * * @param classFile the element to render * @param flags the rendering flags. Flags with names starting with 'CF_' are considered. */ public void appendClassFileLabel(IClassFile classFile, long flags) { if (getFlag(flags, JavaElementLabels.CF_QUALIFIED)) { IPackageFragment pack= (IPackageFragment) classFile.getParent(); if (!pack.isDefaultPackage()) { appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS)); fBuilder.append('.'); } } fBuilder.append(classFile.getElementName()); if (getFlag(flags, JavaElementLabels.CF_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendPackageFragmentLabel((IPackageFragment) classFile.getParent(), flags & QUALIFIER_FLAGS); } } /** * Appends the label for a compilation unit. Considers the CU_* flags. * * @param cu the element to render * @param flags the rendering flags. Flags with names starting with 'CU_' are considered. */ public void appendCompilationUnitLabel(ICompilationUnit cu, long flags) { if (getFlag(flags, JavaElementLabels.CU_QUALIFIED)) { IPackageFragment pack= (IPackageFragment) cu.getParent(); if (!pack.isDefaultPackage()) { appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS)); fBuilder.append('.'); } } fBuilder.append(cu.getElementName()); if (getFlag(flags, JavaElementLabels.CU_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendPackageFragmentLabel((IPackageFragment) cu.getParent(), flags & QUALIFIER_FLAGS); } } /** * Appends the label for a package fragment. Considers the P_* flags. * * @param pack the element to render * @param flags the rendering flags. Flags with names starting with P_' are considered. */ public void appendPackageFragmentLabel(IPackageFragment pack, long flags) { if (getFlag(flags, JavaElementLabels.P_QUALIFIED)) { appendPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), JavaElementLabels.ROOT_QUALIFIED); fBuilder.append('/'); } if (pack.isDefaultPackage()) { fBuilder.append(JavaElementLabels.DEFAULT_PACKAGE); } else if (getFlag(flags, JavaElementLabels.P_COMPRESSED)) { appendCompressedPackageFragment(pack); } else { fBuilder.append(getElementName(pack)); } if (getFlag(flags, JavaElementLabels.P_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); appendPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), JavaElementLabels.ROOT_QUALIFIED); } } private void appendCompressedPackageFragment(IPackageFragment pack) { appendCompressedPackageFragment(pack.getElementName()); } private void appendCompressedPackageFragment(String elementName) { if (fgPkgNameLength < 0) { fBuilder.append(elementName); return; } String name= elementName; int start= 0; int dot= name.indexOf('.', start); while (dot > 0) { if (dot - start > fgPkgNameLength-1) { fBuilder.append(fgPkgNamePrefix); if (fgPkgNameChars > 0) { fBuilder.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot))); } fBuilder.append(fgPkgNamePostfix); } else { fBuilder.append(name.substring(start, dot + 1)); } start= dot + 1; dot= name.indexOf('.', start); } fBuilder.append(name.substring(start)); } /** * Appends the label for a package fragment root. Considers the ROOT_* flags. * * @param root the element to render * @param flags the rendering flags. Flags with names starting with ROOT_' are considered. */ public void appendPackageFragmentRootLabel(IPackageFragmentRoot root, long flags) { // Handle variables different if (getFlag(flags, JavaElementLabels.ROOT_VARIABLE) && appendVariableLabel(root, flags)) { return; } if (root.isArchive()) { appendArchiveLabel(root, flags); } else { appendFolderLabel(root, flags); } } private void appendArchiveLabel(IPackageFragmentRoot root, long flags) { boolean external= root.isExternal(); if (external) { appendExternalArchiveLabel(root, flags); } else { appendInternalArchiveLabel(root, flags); } } private boolean appendVariableLabel(IPackageFragmentRoot root, long flags) { try { IClasspathEntry rawEntry= root.getRawClasspathEntry(); if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { IClasspathEntry entry= JavaModelUtil.getClasspathEntry(root); if (entry.getReferencingEntry() != null) { return false; // not the variable entry itself, but a referenced entry } IPath path= rawEntry.getPath().makeRelative(); if (getFlag(flags, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED)) { int segements= path.segmentCount(); if (segements > 0) { fBuilder.append(path.segment(segements - 1)); if (segements > 1) { fBuilder.append(JavaElementLabels.CONCAT_STRING); fBuilder.append(path.removeLastSegments(1).toOSString()); } } else { fBuilder.append(path.toString()); } } else { fBuilder.append(path.toString()); } fBuilder.append(JavaElementLabels.CONCAT_STRING); if (root.isExternal()) { fBuilder.append(root.getPath().toOSString()); } else { fBuilder.append(root.getPath().makeRelative().toString()); } return true; } } catch (JavaModelException e) { // problems with class path, ignore (bug 202792) return false; } return false; } private void appendExternalArchiveLabel(IPackageFragmentRoot root, long flags) { IPath path; IClasspathEntry classpathEntry= null; try { classpathEntry= JavaModelUtil.getClasspathEntry(root); IPath rawPath= classpathEntry.getPath(); if (classpathEntry.getEntryKind() != IClasspathEntry.CPE_CONTAINER && !rawPath.isAbsolute()) { path= rawPath; } else { path= root.getPath(); } } catch (JavaModelException e) { path= root.getPath(); } if (getFlag(flags, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED)) { int segments= path.segmentCount(); if (segments > 0) { fBuilder.append(path.segment(segments - 1)); if (segments > 1 || path.getDevice() != null) { fBuilder.append(JavaElementLabels.CONCAT_STRING); fBuilder.append(path.removeLastSegments(1).toOSString()); } if (classpathEntry != null) { IClasspathEntry referencingEntry= classpathEntry.getReferencingEntry(); if (referencingEntry != null) { fBuilder.append(NLS.bind(" (from {0} of {1})", new Object[] { Name.CLASS_PATH.toString(), referencingEntry.getPath().lastSegment() })); } } } else { fBuilder.append(path.toOSString()); } } else { fBuilder.append(path.toOSString()); } } private void appendInternalArchiveLabel(IPackageFragmentRoot root, long flags) { IResource resource= root.getResource(); boolean rootQualified= getFlag(flags, JavaElementLabels.ROOT_QUALIFIED); if (rootQualified) { fBuilder.append(root.getPath().makeRelative().toString()); } else { fBuilder.append(root.getElementName()); boolean referencedPostQualified= getFlag(flags, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED); if (referencedPostQualified && isReferenced(root)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); fBuilder.append(resource.getParent().getFullPath().makeRelative().toString()); } else if (getFlag(flags, JavaElementLabels.ROOT_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); fBuilder.append(root.getParent().getPath().makeRelative().toString()); } if (referencedPostQualified) { try { IClasspathEntry referencingEntry= JavaModelUtil.getClasspathEntry(root).getReferencingEntry(); if (referencingEntry != null) { fBuilder.append(NLS.bind(" (from {0} of {1})", new Object[] { Name.CLASS_PATH.toString(), referencingEntry.getPath().lastSegment() })); } } catch (JavaModelException e) { // ignore } } } } private void appendFolderLabel(IPackageFragmentRoot root, long flags) { IResource resource= root.getResource(); if (resource == null) { appendExternalArchiveLabel(root, flags); return; } boolean rootQualified= getFlag(flags, JavaElementLabels.ROOT_QUALIFIED); boolean referencedQualified= getFlag(flags, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED) && isReferenced(root); if (rootQualified) { fBuilder.append(root.getPath().makeRelative().toString()); } else { IPath projectRelativePath= resource.getProjectRelativePath(); if (projectRelativePath.segmentCount() == 0) { fBuilder.append(resource.getName()); referencedQualified= false; } else { fBuilder.append(projectRelativePath.toString()); } if (referencedQualified) { fBuilder.append(JavaElementLabels.CONCAT_STRING); fBuilder.append(resource.getProject().getName()); } else if (getFlag(flags, JavaElementLabels.ROOT_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); fBuilder.append(root.getParent().getElementName()); } else { return; } } } /** * Returns <code>true</code> if the given package fragment root is * referenced. This means it is a descendant of a different project but is referenced * by the root's parent. Returns <code>false</code> if the given root * doesn't have an underlying resource. * * @param root the package fragment root * @return returns <code>true</code> if the given package fragment root is referenced */ private boolean isReferenced(IPackageFragmentRoot root) { IResource resource= root.getResource(); if (resource != null) { IProject jarProject= resource.getProject(); IProject container= root.getJavaProject().getProject(); return !container.equals(jarProject); } return false; } }
epl-1.0
Snickermicker/openhab2
bundles/org.openhab.binding.elerotransmitterstick/src/main/java/org/openhab/binding/elerotransmitterstick/internal/stick/TransmitterStick.java
16350
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.elerotransmitterstick.internal.stick; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import java.util.concurrent.BlockingQueue; import java.util.concurrent.DelayQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.openhab.binding.elerotransmitterstick.internal.config.EleroTransmitterStickConfig; import org.openhab.binding.elerotransmitterstick.internal.handler.StatusListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Volker Bier - Initial contribution */ public class TransmitterStick { private final Logger logger = LoggerFactory.getLogger(TransmitterStick.class); private final HashMap<Integer, ArrayList<StatusListener>> allListeners = new HashMap<>(); private final StickListener listener; private EleroTransmitterStickConfig config; private CommandWorker worker; public TransmitterStick(StickListener l) { listener = l; } public synchronized void initialize(EleroTransmitterStickConfig stickConfig, ScheduledExecutorService scheduler) { logger.debug("Initializing Transmitter Stick..."); config = stickConfig; worker = new CommandWorker(); scheduler.schedule(worker, 0, TimeUnit.MILLISECONDS); logger.debug("Transmitter Stick initialized, worker running."); } public synchronized void dispose() { logger.debug("Disposing Transmitter Stick..."); worker.terminateUpdates(); worker = null; config = null; logger.debug("Transmitter Stick disposed."); } public synchronized ArrayList<Integer> getKnownIds() { if (worker != null) { return worker.validIds; } return new ArrayList<>(); } public synchronized void sendCommand(CommandType cmd, List<Integer> channelIds) { if (worker != null) { worker.executeCommand(cmd, channelIds); } } public synchronized void requestUpdate(List<Integer> channelIds) { if (worker != null) { worker.requestUpdates(channelIds); } } public void addStatusListener(int channelId, StatusListener listener) { synchronized (allListeners) { ArrayList<StatusListener> listeners = allListeners.get(channelId); if (listeners == null) { listeners = new ArrayList<>(); allListeners.put(channelId, listeners); } listeners.add(listener); } } public void removeStatusListener(int channelId, StatusListener listener) { synchronized (allListeners) { ArrayList<StatusListener> listeners = allListeners.get(channelId); if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { allListeners.remove(channelId); } } } } private void notifyListeners(int channelId, ResponseStatus status) { synchronized (allListeners) { ArrayList<StatusListener> listeners = allListeners.get(channelId); if (listeners != null) { for (StatusListener l : listeners) { l.statusChanged(channelId, status); } } } } /** * Make sure we have * - only one INFO for the same channel ids * - only one other command for the same channel ids */ private static boolean prepareAddition(Command newCmd, Collection<Command> coll) { Iterator<Command> queuedCommands = coll.iterator(); while (queuedCommands.hasNext()) { Command existingCmd = queuedCommands.next(); if (Arrays.equals(newCmd.getChannelIds(), existingCmd.getChannelIds())) { // remove pending INFOs for same channel ids if (newCmd.getCommandType() == CommandType.INFO && existingCmd.getCommandType() == CommandType.INFO) { if (existingCmd.getPriority() < newCmd.priority) { // we have an older INFO command with same or lower priority, remove queuedCommands.remove(); } else { // existing has higher priority, skip addition return false; } } if (newCmd.getCommandType() != CommandType.INFO && existingCmd.getCommandType() != CommandType.INFO) { // we have an older command for the same channels, remove queuedCommands.remove(); } } } return true; } static class DueCommandSet extends TreeSet<Command> { private static final long serialVersionUID = -3216360253151368826L; public DueCommandSet() { super(new Comparator<Command>() { /** * Due commands are sorted by priority first and then by delay. */ @Override public int compare(Command o1, Command o2) { if (o1.equals(o2)) { return 0; } int d = o2.getPriority() - o1.getPriority(); if (d < 0) { return -1; } if (d == 0 && o1.getDelay(TimeUnit.MILLISECONDS) < o2.getDelay(TimeUnit.MILLISECONDS)) { return -1; } return 1; } }); } @Override public boolean add(Command e) { if (TransmitterStick.prepareAddition(e, this)) { return super.add(e); } return false; } } class CommandWorker implements Runnable { private ArrayList<Integer> validIds = new ArrayList<>(); private final AtomicBoolean terminated = new AtomicBoolean(); private final int updateInterval; private final SerialConnection connection; private final BlockingQueue<Command> cmdQueue = new DelayQueue<Command>() { @Override public boolean add(Command e) { if (TransmitterStick.prepareAddition(e, this)) { return super.add(e); } return false; } }; CommandWorker() { connection = new SerialConnection(config.portName); updateInterval = config.updateInterval; } void terminateUpdates() { terminated.set(true); // add a NONE command to make the thread exit from the call to take() cmdQueue.add(new Command(CommandType.NONE)); } void requestUpdates(List<Integer> channelIds) { // this is a workaround for a bug in the stick firmware that does not // handle commands that are sent to multiple channels correctly if (channelIds.size() > 1) { for (int channelId : channelIds) { requestUpdates(Collections.singletonList(channelId)); } } else if (!channelIds.isEmpty()) { final Integer[] ids = channelIds.toArray(new Integer[channelIds.size()]); logger.debug("adding INFO command for channel id {} to queue...", Arrays.toString(ids)); cmdQueue.add(new DelayedCommand(CommandType.INFO, 0, Command.FAST_INFO_PRIORITY, ids)); } } void executeCommand(CommandType command, List<Integer> channelIds) { // this is a workaround for a bug in the stick firmware that does not // handle commands that are sent to multiple channels correctly if (channelIds.size() > 1) { for (int channelId : channelIds) { executeCommand(command, Collections.singletonList(channelId)); } } else if (!channelIds.isEmpty()) { final Integer[] ids = channelIds.toArray(new Integer[channelIds.size()]); logger.debug("adding command {} for channel ids {} to queue...", command, Arrays.toString(ids)); cmdQueue.add(new Command(command, ids)); } } @Override public void run() { try { queryChannels(); doWork(); } catch (Throwable t) { logger.error("Worker stopped by unexpected exception", t); } finally { connection.close(); } } private void doWork() { // list of due commands sorted by priority final DueCommandSet dueCommands = new DueCommandSet(); logger.debug("worker started."); while (!terminated.get()) { waitConnected(); try { // in case we have no commands that are currently due, wait for a new one if (dueCommands.size() == 0) { logger.debug("No due commands, invoking take on queue..."); dueCommands.add(cmdQueue.take()); logger.trace("take returned {}", dueCommands.first()); } if (!terminated.get()) { // take all commands that are due from the queue logger.trace("Draining all available commands..."); Command cmd; int drainCount = 0; while ((cmd = cmdQueue.poll()) != null) { drainCount++; dueCommands.remove(cmd); dueCommands.add(cmd); } logger.trace("Drained {} commands, active queue size is {}, queue size is {}", drainCount, dueCommands.size(), cmdQueue.size()); // process the command with the highest priority cmd = dueCommands.first(); logger.debug("active command is {}", cmd); if (cmd.getCommandType() != CommandType.NONE) { Response response = connection.sendPacket(CommandUtil.createPacket(cmd)); // remove the command now we know it has been correctly processed dueCommands.pollFirst(); if (response != null && response.hasStatus()) { for (int id : response.getChannelIds()) { notifyListeners(id, response.getStatus()); } } if (cmd instanceof TimedCommand) { long delay = 1000 * ((TimedCommand) cmd).getDuration(); logger.debug("adding timed command STOP for channel ids {} to queue with delay {}...", cmd.getChannelIds(), delay); cmdQueue.add(new DelayedCommand(CommandType.STOP, delay, Command.TIMED_PRIORITY, cmd.getChannelIds())); } else if (response != null && response.isMoving()) { logger.debug("adding timed command INFO for channel ids {} to queue with delay 2000...", cmd.getChannelIds()); cmdQueue.add(new DelayedCommand(CommandType.INFO, 2000, Command.FAST_INFO_PRIORITY, cmd.getChannelIds())); } else if (cmd.getCommandType() == CommandType.INFO) { logger.debug("adding timed command INFO for channel ids {} to queue with delay {}...", cmd.getChannelIds(), updateInterval * 1000); cmdQueue.add(new DelayedCommand(CommandType.INFO, updateInterval * 1000, Command.INFO_PRIORITY, cmd.getChannelIds())); } } else { logger.trace("ignoring NONE command."); } } } catch (InterruptedException e) { logger.error("Got interrupt while waiting for next command time", e); Thread.currentThread().interrupt(); } catch (IOException e) { logger.error("Got IOException communicating with the stick", e); listener.connectionDropped(e); connection.close(); } } logger.debug("worker finished."); } private void queryChannels() { logger.debug("querying available channels..."); while (!terminated.get()) { waitConnected(); try { Response r = null; while (r == null && !terminated.get() && connection.isOpen()) { logger.debug("sending CHECK packet..."); r = connection.sendPacket(CommandUtil.createPacket(CommandType.CHECK)); if (r == null) { Thread.sleep(2000); } } if (r != null) { int[] knownIds = r.getChannelIds(); logger.debug("Worker found channels: {} ", Arrays.toString(knownIds)); for (int id : knownIds) { if (!validIds.contains(id)) { validIds.add(id); } } requestUpdates(validIds); break; } } catch (IOException e) { logger.error("Got IOException communicating with the stick", e); listener.connectionDropped(e); connection.close(); } catch (InterruptedException e) { logger.error("Got interrupt while waiting for next command time", e); Thread.currentThread().interrupt(); } } } private void waitConnected() { if (!connection.isOpen()) { while (!connection.isOpen() && !terminated.get()) { try { connection.open(); listener.connectionEstablished(); } catch (ConnectException e1) { listener.connectionDropped(e1); } if (!connection.isOpen() && !terminated.get()) { try { Thread.sleep(2000); } catch (InterruptedException e) { logger.error("Got interrupt while waiting for next command time", e); Thread.currentThread().interrupt(); } } } } logger.trace("finished waiting. connection open={}, terminated={}", connection.isOpen(), terminated.get()); } } public interface StickListener { void connectionEstablished(); void connectionDropped(Exception e); } }
epl-1.0
sleshchenko/che
plugins/plugin-nodejs-debugger/che-plugin-nodejs-debugger-server/src/main/java/org/eclipse/che/plugin/nodejsdbg/server/parser/NodeJsStepParser.java
1737
/* * 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.nodejsdbg.server.parser; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.che.api.debug.shared.model.Location; import org.eclipse.che.api.debug.shared.model.impl.LocationImpl; import org.eclipse.che.plugin.nodejsdbg.server.NodeJsOutput; import org.eclipse.che.plugin.nodejsdbg.server.exception.NodeJsDebuggerParseException; /** * {@code backtrace} command parser. * * @author Anatoliy Bazko */ public class NodeJsStepParser implements NodeJsOutputParser<Location> { public static final NodeJsStepParser INSTANCE = new NodeJsStepParser(); public static final Pattern PATTERN = Pattern.compile("^break in (.*):([0-9]+)"); private NodeJsStepParser() {} @Override public boolean match(NodeJsOutput nodeJsOutput) { return nodeJsOutput.getOutput().startsWith("break in"); } @Override public Location parse(NodeJsOutput nodeJsOutput) throws NodeJsDebuggerParseException { String output = nodeJsOutput.getOutput(); for (String line : output.split("\n")) { Matcher matcher = PATTERN.matcher(line); if (matcher.find()) { String file = matcher.group(1); String lineNumber = matcher.group(2); return new LocationImpl(file, Integer.parseInt(lineNumber)); } } throw new NodeJsDebuggerParseException(Location.class, output); } }
epl-1.0
xiaohanz/softcontroller
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/mapping/CompositeAttributeMappingStrategy.java
2953
/* * Copyright (c) 2013 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.netconf.confignetconfconnector.mapping.attributes.mapping; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import org.opendaylight.controller.netconf.confignetconfconnector.util.Util; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenType; import java.util.Map; import java.util.Set; public class CompositeAttributeMappingStrategy extends AbstractAttributeMappingStrategy<Map<String, Object>, CompositeType> { private final Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies; private final Map<String, String> jmxToJavaNameMapping; public CompositeAttributeMappingStrategy(CompositeType compositeType, Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies, Map<String, String> jmxToJavaNameMapping) { super(compositeType); this.innerStrategies = innerStrategies; this.jmxToJavaNameMapping = jmxToJavaNameMapping; } @Override public Optional<Map<String, Object>> mapAttribute(Object value) { if (value == null) return Optional.absent(); Util.checkType(value, CompositeDataSupport.class); CompositeDataSupport compositeData = (CompositeDataSupport) value; CompositeType currentType = compositeData.getCompositeType(); CompositeType expectedType = getOpenType(); Set<String> expectedCompositeTypeKeys = expectedType.keySet(); Set<String> currentCompositeTypeKeys = currentType.keySet(); Preconditions.checkArgument(expectedCompositeTypeKeys.equals(currentCompositeTypeKeys), "Composite type mismatch, expected composite type with attributes " + expectedCompositeTypeKeys + " but was " + currentCompositeTypeKeys); Map<String, Object> retVal = Maps.newHashMap(); for (String jmxName : jmxToJavaNameMapping.keySet()) { String innerAttrJmxName = jmxName; Object innerValue = compositeData.get(innerAttrJmxName); AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = innerStrategies .get(innerAttrJmxName); Optional<?> mapAttribute = attributeMappingStrategy.mapAttribute(innerValue); if (mapAttribute.isPresent()) retVal.put(jmxToJavaNameMapping.get(innerAttrJmxName), mapAttribute.get()); } return Optional.of(retVal); } }
epl-1.0
peterkir/org.eclipse.oomph
plugins/org.eclipse.oomph.setup/src/org/eclipse/oomph/setup/Trigger.java
8015
/* * Copyright (c) 2014, 2015 Eike Stepper (Berlin, Germany) 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: * Eike Stepper - initial API and implementation */ package org.eclipse.oomph.setup; import org.eclipse.emf.common.util.Enumerator; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Trigger</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see org.eclipse.oomph.setup.SetupPackage#getTrigger() * @model * @generated */ public enum Trigger implements Enumerator { /** * The '<em><b>BOOTSTRAP</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #BOOTSTRAP_VALUE * @generated * @ordered */ BOOTSTRAP(0, "BOOTSTRAP", "BOOTSTRAP"), /** * The '<em><b>STARTUP</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #STARTUP_VALUE * @generated * @ordered */ STARTUP(1, "STARTUP", "STARTUP"), /** * The '<em><b>MANUAL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #MANUAL_VALUE * @generated * @ordered */ MANUAL(2, "MANUAL", "MANUAL"); /** * The '<em><b>BOOTSTRAP</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>BOOTSTRAP</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #BOOTSTRAP * @model * @generated * @ordered */ public static final int BOOTSTRAP_VALUE = 0; /** * The '<em><b>STARTUP</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>STARTUP</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #STARTUP * @model * @generated * @ordered */ public static final int STARTUP_VALUE = 1; /** * The '<em><b>MANUAL</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>MANUAL</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #MANUAL * @model * @generated * @ordered */ public static final int MANUAL_VALUE = 2; /** * An array of all the '<em><b>Trigger</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final Trigger[] VALUES_ARRAY = new Trigger[] { BOOTSTRAP, STARTUP, MANUAL, }; /** * A public read-only list of all the '<em><b>Trigger</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<Trigger> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Trigger</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static Trigger get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { Trigger result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Trigger</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static Trigger getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { Trigger result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Trigger</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static Trigger get(int value) { switch (value) { case BOOTSTRAP_VALUE: return BOOTSTRAP; case STARTUP_VALUE: return STARTUP; case MANUAL_VALUE: return MANUAL; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private Trigger(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } public static Set<Trigger> toSet(Trigger... triggers) { return intern(new HashSet<Trigger>(Arrays.asList(triggers))); } public static Set<Trigger> intern(Set<Trigger> triggerSet) { return CANONICAL_TRIGGER_SETS.get(triggerSet); } private static final Map<Set<Trigger>, Set<Trigger>> CANONICAL_TRIGGER_SETS = new HashMap<Set<Trigger>, Set<Trigger>>(); public static final Map<Set<Trigger>, String> LITERALS; static { Map<Set<Trigger>, String> literals = new LinkedHashMap<Set<Trigger>, String>(); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 2; ++k) { Set<Trigger> value = new LinkedHashSet<Trigger>() { private static final long serialVersionUID = 1L; @Override public String toString() { StringBuilder result = new StringBuilder(); for (Trigger trigger : this) { if (result.length() != 0) { result.append(' '); } result.append(trigger); } return result.toString(); } }; if (i == 1) { value.add(Trigger.BOOTSTRAP); } if (j == 1) { value.add(Trigger.STARTUP); } if (k == 1) { value.add(Trigger.MANUAL); } value = Collections.unmodifiableSet(value); literals.put(value, value.toString()); CANONICAL_TRIGGER_SETS.put(value, value); } } } LITERALS = Collections.unmodifiableMap(literals); } public static final Set<Trigger> ALL_TRIGGERS = toSet(values()); public static final Set<Trigger> IDE_TRIGGERS = toSet(Trigger.STARTUP, Trigger.MANUAL); } // Trigger
epl-1.0
jmini/org.eclipsescout.rt.ui.fx
org.eclipsescout.rt.ui.fx/src/org/eclipsescout/rt/ui/fx/basic/chart/functions/AbstractFunction.java
2557
/******************************************************************************* * Copyright (c) 2014 BSI Business Systems Integration 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 * * Contributors: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ package org.eclipsescout.rt.ui.fx.basic.chart.functions; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; /** * */ public abstract class AbstractFunction implements IFunction { /** * */ public AbstractFunction() { super(); } @Override public Number calculate(List<Object> list) { Class<?> dataType = null; for (Object object : list) { if (object != null) { dataType = object.getClass(); } } if (dataType == null) { return null; } return calculate(list, dataType); } @Override public final Number calculate(List<Object> list, Class<?> dataType) { if (!Number.class.isAssignableFrom(dataType)) { return null; } Number result = null; if (dataType == Long.class) { result = calculateLong(list); } else if (dataType == Short.class) { result = calculateShort(list); } else if (dataType == Integer.class) { result = calculateInteger(list); } else if (dataType == Byte.class) { result = calculateByte(list); } else if (dataType == Double.class) { result = calculateDouble(list); } else if (dataType == Float.class) { result = calculateFloat(list); } else if (dataType == BigInteger.class) { result = calculateBigInteger(list); } else if (dataType == BigDecimal.class) { result = calculateBigDecimal(list); } return result; } protected abstract Number calculateShort(List<Object> list); protected abstract Number calculateByte(List<Object> list); protected abstract Number calculateInteger(List<Object> list); protected abstract Number calculateLong(List<Object> list); protected abstract Number calculateFloat(List<Object> list); protected abstract Number calculateDouble(List<Object> list); protected abstract Number calculateBigInteger(List<Object> list); protected abstract Number calculateBigDecimal(List<Object> list); }
epl-1.0
Charling-Huang/birt
data/org.eclipse.birt.data.tests/test/org/eclipse/birt/data/engine/odaconsumer/ParameterHintTest.java
30446
/* * **************************************************************************** * Copyright (c) 2004, 2007 Actuate Corporation. 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: * Actuate Corporation - initial API and implementation * * ***************************************************************************** */ package org.eclipse.birt.data.engine.odaconsumer; import java.sql.Types; import java.util.Collection; import java.util.Iterator; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.i18n.DataResourceHandle; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.datatools.connectivity.oda.IBlob; import org.eclipse.datatools.connectivity.oda.IClob; import testutil.JDBCOdaDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.*; public class ParameterHintTest extends ConnectionTest { private DataResourceHandle resourceHandle = DataResourceHandle.getInstance( ); @Test public void testNameToPositionInSingleParameterHint( ) throws Exception { PreparedStatement statement = getConnection( ).prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); ParameterHint hint = new ParameterHint( "ParamName", true, false ); hint.setPosition( 1 ); statement.addParameterHint( hint ); statement.setParameterValue( "ParamName", new Integer( 4 ) ); assertTrue( statement.execute( ) ); ResultSet resultset = statement.getResultSet( ); int count = 0; while ( resultset.fetch( ) != null ) count++; assertEquals( 1, count ); } @Test public void testNameToPositionInParameterHints( ) throws Exception { String command = "select \"intColumn\" from \"testtable\" where \"intColumn\" = ? OR \"stringColumn\" = ?"; PreparedStatement statement = getConnection( ).prepareStatement( command, JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); statement.addParameterHint( hint ); hint = new ParameterHint( "ParamName2", true, false ); hint.setPosition( 2 ); statement.addParameterHint( hint ); statement.setParameterValue( "ParamName1", new Integer( 0 ) ); statement.setParameterValue( "ParamName2", "blah blah blah" ); assertTrue( statement.execute( ) ); ResultSet resultset = statement.getResultSet( ); int count = 0; while ( resultset.fetch( ) != null ) count++; assertEquals( 2, count ); } @Test public void testValidateParameterHints1( ) throws Exception { try { PreparedStatement statement = getConnection( ).prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); statement.addParameterHint( hint ); // conflicting hint on same parameter name hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 2 ); statement.addParameterHint( hint ); fail( ); } catch ( DataException ex ) { String msg = resourceHandle.getMessage( ResourceConstants.SAME_PARAM_NAME_FOR_DIFFERENT_HINTS, new Object[]{ "ParamName1" } ); assertEquals( msg, ex.getMessage( ) ); } } @Test public void testValidateInputParameterHints2( ) throws Exception { PreparedStatement statement = getConnection( ).prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); statement.addParameterHint( hint ); hint = new ParameterHint( "PName1", true, false ); hint.setPosition( 1 ); try { statement.addParameterHint( hint ); fail( ); // should have an exception } catch ( DataException ex ) { String msg = resourceHandle.getMessage( ResourceConstants.DIFFERENT_PARAM_NAME_FOR_SAME_POSITION, new Object[]{ "ParamName1", new Integer( 1 ) } ); assertEquals( msg, ex.getMessage( ) ); } } @Test public void testValidateOutputParameterHints( ) throws Exception { PreparedStatement statement = getConnection( ).prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); ParameterHint outputHint = new ParameterHint( "ParamName1", false, true ); outputHint.setPosition( 2 ); statement.addParameterHint( outputHint ); ParameterHint hint = new ParameterHint( "PName1", true, false ); hint.setPosition( 2 ); try { statement.addParameterHint( hint ); fail( ); } catch ( DataException ex ) { String msg = resourceHandle.getMessage( ResourceConstants.DIFFERENT_PARAM_NAME_FOR_SAME_POSITION, new Object[]{ "ParamName1", new Integer( 2 ) } ); assertEquals( msg, ex.getMessage( ) ); } } @Test public void testValidateInputParameterHintsSucceed( ) throws Exception { PreparedStatement statement = getConnection( ).prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); // 2 hints with different model names and positions, but same native name ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setNativeName( "sameNativeName" ); statement.addParameterHint( hint ); hint = new ParameterHint( "ParamName2", true, false ); hint.setPosition( 2 ); hint.setNativeName( "sameNativeName" ); try { statement.addParameterHint( hint ); assertTrue( true ); // no exception, test succeeded } catch ( DataException ex ) { fail( ); } } @Test public void testGetParameterMetaData1( ) throws Exception { PreparedStatement statement = getConnection( ).prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = statement.getParameterMetaData( ); assertNotNull( parameterMetaData ); assertEquals( 1, parameterMetaData.size( ) ); Iterator iter = parameterMetaData.iterator( ); while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); checkDefaultMetaData( metadata, 1 ); } } @Test public void testGetParameterMetaData2( ) throws Exception { PreparedStatement statement = getConnection( ).prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" < ? AND \"intColumn\" > ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = statement.getParameterMetaData( ); assertNotNull( parameterMetaData ); assertEquals( 2, parameterMetaData.size( ) ); Iterator iter = parameterMetaData.iterator( ); int count = 1; while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); checkDefaultMetaData( metadata, count++ ); } } private void checkDefaultMetaData( ParameterMetaData metadata, int index ) { //the following code specified for derby database JDBC driver returned // metadata assertEquals( index, metadata.getPosition( ) ); assertEquals( Types.INTEGER, metadata.getDataType() ); assertEquals( null, metadata.getName( ) ); assertEquals( null, metadata.getDefaultValue( ) ); assertEquals( "INTEGER", metadata.getNativeTypeName() ); assertEquals( 0, metadata.getScale( ) ); assertEquals( 10, metadata.getPrecision() ); assertEquals( Boolean.TRUE, metadata.isInputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOutputMode( ) ); assertEquals( null, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } @Test public void testGetParameterMetaData3( ) throws Exception { PreparedStatement statement = getConnection( ).prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = statement.getParameterMetaData( ); assertNotNull( parameterMetaData ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setNativeName( "paramNativeName" ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); statement.addParameterHint( hint ); Collection parameterMetaData1 = statement.getParameterMetaData( ); assertNotNull( parameterMetaData1 ); assertNotSame( parameterMetaData, parameterMetaData1 ); Iterator iter = parameterMetaData1.iterator( ); while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); assertEquals( 1, metadata.getPosition( ) ); //This expected value only suitable for Derby Database assertEquals( Types.INTEGER, metadata.getDataType( ) ); assertEquals( "ParamName1", metadata.getName( ) ); assertEquals( "paramNativeName", metadata.getNativeName( ) ); assertEquals( null, metadata.getDefaultValue( ) ); //This expected value only suitable for Derby Database assertEquals( "INTEGER", metadata.getNativeTypeName( ) ); assertEquals( 0, metadata.getScale( ) ); //This expected value only suitable for Derby Database assertEquals( 10, metadata.getPrecision( ) ); assertEquals( Boolean.TRUE, metadata.isInputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOutputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } } @Ignore("Ignore tests that require manual setup") @Test public void testUnsupportedRuntimeParameterMetaData( ) throws Exception { // uses mySQL that does not provide runtime parameterMetaData Connection connection = getMySqlConnection( ); PreparedStatement statement = connection.prepareStatement( "SELECT \"intColumn\", \"doubleColumn\" FROM \"testtable\" WHERE \"intColumn\" > ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = null; try { parameterMetaData = statement.getParameterMetaData( ); } catch( DataException e ) { // ignore } assertNull( parameterMetaData ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); statement.addParameterHint( hint ); ParameterHint hint2 = new ParameterHint( "ParamName2", true, false ); hint2.setDataType( Double.class ); statement.addParameterHint( hint2 ); Collection parameterMetaData1 = statement.getParameterMetaData( ); assertNotNull( parameterMetaData1 ); Iterator iter = parameterMetaData1.iterator( ); int paramNumInCollection = 1; while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); if ( paramNumInCollection++ == 1 ) { assertEquals( 1, metadata.getPosition( ) ); assertEquals( Types.INTEGER, metadata.getDataType( ) ); assertEquals( "ParamName1", metadata.getName( ) ); assertEquals( null, metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); assertEquals( Boolean.TRUE, metadata.isInputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOutputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } else { assertEquals( -1, metadata.getPosition( ) ); assertEquals( Types.DOUBLE, metadata.getDataType( ) ); assertEquals( "ParamName2", metadata.getName( ) ); assertEquals( null, metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); assertEquals( Boolean.TRUE, metadata.isInputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOutputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } } } @Ignore("Ignore tests that require manual setup") @Test public void testMultipleHintsOnSameParameterName( ) throws Exception { Connection connection = getMySqlConnection( ); PreparedStatement statement = connection.prepareStatement( "SELECT \"intColumn\", \"doubleColumn\" FROM \"testtable\" WHERE \"intColumn\" > ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = null; try { parameterMetaData = statement.getParameterMetaData( ); } catch( DataException e ) { // ignore } assertNull( parameterMetaData ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setNativeName( "paramNativeName1" ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); statement.addParameterHint( hint ); ParameterHint hint2 = new ParameterHint( "ParamName2", false, true ); hint2.setDataType( Double.class ); statement.addParameterHint( hint2 ); // another hint to change the design metadata of the first parameter ParameterHint hint3 = new ParameterHint( "ParamName1", false, true ); hint3.setNativeName( "paramNativeName3" ); statement.addParameterHint( hint3 ); Collection parameterMetaData1 = statement.getParameterMetaData( ); assertNotNull( parameterMetaData1 ); Iterator iter = parameterMetaData1.iterator( ); int paramNumInCollection = 1; while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); if ( paramNumInCollection++ == 1 ) { assertEquals( 1, metadata.getPosition( ) ); assertEquals( Types.INTEGER, metadata.getDataType( ) ); assertEquals( "ParamName1", metadata.getName( ) ); // last hint's nativeName is effective assertEquals( "paramNativeName3", metadata.getNativeName() ); assertEquals( null, metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); // should have md from the third hint assertEquals( Boolean.FALSE, metadata.isInputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOutputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } else { assertEquals( -1, metadata.getPosition( ) ); assertEquals( Types.DOUBLE, metadata.getDataType( ) ); assertEquals( "ParamName2", metadata.getName( ) ); assertEquals( null, metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); assertEquals( Boolean.FALSE, metadata.isInputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOutputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } } } @Ignore("Ignore tests that require manual setup") @Test public void testUnsupportedRuntimeParameterMetaData2( ) throws Exception { // uses mySQL that does not provide runtime parameterMetaData Connection connection = getMySqlConnection( ); PreparedStatement statement = connection.prepareStatement( "SELECT \"intColumn\", \"doubleColumn\" FROM \"testtable\" WHERE \"intColumn\" > ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = null; try { parameterMetaData = statement.getParameterMetaData( ); } catch( DataException e ) { // ignore } assertNull( parameterMetaData ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); hint.setDefaultInputValue( "123" ); statement.addParameterHint( hint ); ParameterHint hint2 = new ParameterHint( "ParamName2", true, false ); hint2.setDataType( Double.class ); hint2.setDefaultInputValue( "456" ); statement.addParameterHint( hint2 ); Collection parameterMetaData1 = statement.getParameterMetaData( ); assertNotNull( parameterMetaData1 ); Iterator iter = parameterMetaData1.iterator( ); int paramNumInCollection = 1; while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); if ( paramNumInCollection++ == 1 ) { assertEquals( 1, metadata.getPosition( ) ); assertEquals( Types.INTEGER, metadata.getDataType( ) ); assertEquals( "ParamName1", metadata.getName( ) ); assertEquals( "123", metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); assertEquals( Boolean.TRUE, metadata.isInputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOutputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } else { assertEquals( -1, metadata.getPosition( ) ); assertEquals( Types.DOUBLE, metadata.getDataType( ) ); assertEquals( "ParamName2", metadata.getName( ) ); assertEquals( "456", metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); assertEquals( Boolean.TRUE, metadata.isInputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOutputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } } } @Test public void testUnsupportedParameterDataTypes( ) throws Exception { ParameterHint inputHint = new ParameterHint( "InputParameter", true, true ); boolean isErrorCaught = false; try { inputHint.setDataType( IBlob.class ); } catch( IllegalArgumentException e ) { isErrorCaught = true; } assertTrue( isErrorCaught ); isErrorCaught = false; try { inputHint.setDataType( IClob.class ); } catch( IllegalArgumentException e ) { isErrorCaught = true; } assertTrue( isErrorCaught ); } @Ignore("Ignore tests that require manual setup") @Test public void testMergeParamHints( ) throws Exception { // uses mySQL that does not provide runtime parameterMetaData Connection connection = getMySqlConnection( ); PreparedStatement statement = connection.prepareStatement( "SELECT \"intColumn\", \"doubleColumn\" FROM \"testtable\" WHERE \"intColumn\" > ?", JDBCOdaDataSource.DATA_SET_TYPE ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); statement.addParameterHint( hint ); // another hint on same parameter name, but as output parameter mode ParameterHint outputHint = new ParameterHint( "ParamName1", false, true ); outputHint.setPosition( 1 ); outputHint.setDataType( Integer.class ); statement.addParameterHint( outputHint ); Collection parameterMetaData = statement.getParameterMetaData( ); assertTrue( parameterMetaData != null && parameterMetaData.size( ) == 1 ); Iterator iter = parameterMetaData.iterator( ); while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); assertEquals( 1, metadata.getPosition( ) ); assertEquals( Types.INTEGER, metadata.getDataType( ) ); assertEquals( "ParamName1", metadata.getName( ) ); assertEquals( null, metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); assertEquals( Boolean.FALSE, metadata.isInputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOutputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } } @Ignore("Ignore tests that require manual setup") @Test public void testMergeParamHints1( ) throws Exception { // uses mySQL that does not provide runtime parameterMetaData Connection connection = getMySqlConnection( ); PreparedStatement statement = connection.prepareStatement( "SELECT \"intColumn\", \"doubleColumn\" FROM \"testtable\" WHERE \"intColumn\" > ?", JDBCOdaDataSource.DATA_SET_TYPE ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); statement.addParameterHint( hint ); // another hint on same parameter name, with additional metadata attributes hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setNativeName( "paramNativeName" ); hint.setDataType( Integer.class ); statement.addParameterHint( hint ); Collection parameterMetaData = statement.getParameterMetaData( ); assertTrue( parameterMetaData != null && parameterMetaData.size( ) == 1 ); Iterator iter = parameterMetaData.iterator( ); while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); assertEquals( 1, metadata.getPosition( ) ); assertEquals( Types.INTEGER, metadata.getDataType( ) ); assertEquals( "ParamName1", metadata.getName( ) ); assertEquals( "paramNativeName", metadata.getNativeName( ) ); assertEquals( null, metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); assertEquals( Boolean.TRUE, metadata.isInputMode( ) ); assertEquals( Boolean.FALSE, metadata.isOutputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } } @Ignore("Ignore tests that require manual setup") @Test public void testConflictingParamHints( ) throws Exception { try { // uses mySQL that does not provide runtime parameterMetaData Connection connection = getMySqlConnection( ); PreparedStatement statement = connection.prepareStatement( "SELECT \"intColumn\", \"doubleColumn\" FROM \"testtable\" WHERE \"intColumn\" > ?", JDBCOdaDataSource.DATA_SET_TYPE ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); statement.addParameterHint( hint ); ParameterHint outputHint = new ParameterHint( "ParamName1", false, true ); outputHint.setPosition( 2 ); outputHint.setDataType( Integer.class ); statement.addParameterHint( outputHint ); fail( ); } catch ( DataException ex ) { String msg = resourceHandle.getMessage( ResourceConstants.SAME_PARAM_NAME_FOR_DIFFERENT_HINTS, new Object[]{ "ParamName1" } ); assertEquals( msg, ex.getMessage( ) ); } } @Ignore("Ignore tests that require manual setup") @Test public void testMergeParamHints3( ) throws Exception { // uses mySQL that does not provide runtime parameterMetaData Connection connection = getMySqlConnection( ); PreparedStatement statement = connection.prepareStatement( "SELECT \"intColumn\", \"doubleColumn\" FROM \"testtable\" WHERE \"intColumn\" > ?", JDBCOdaDataSource.DATA_SET_TYPE ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); statement.addParameterHint( hint ); ParameterHint outputHint = new ParameterHint( "ParamName1", false, true ); outputHint.setDataType( Double.class ); statement.addParameterHint( outputHint ); Collection parameterMetaData = statement.getParameterMetaData( ); assertTrue( parameterMetaData != null && parameterMetaData.size( ) == 1 ); Iterator iter = parameterMetaData.iterator( ); while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); assertEquals( 1, metadata.getPosition( ) ); assertEquals( Types.DOUBLE, metadata.getDataType( ) ); assertEquals( "ParamName1", metadata.getName( ) ); assertEquals( null, metadata.getDefaultValue( ) ); assertEquals( null, metadata.getNativeTypeName( ) ); assertEquals( -1, metadata.getScale( ) ); assertEquals( -1, metadata.getPrecision( ) ); assertEquals( Boolean.FALSE, metadata.isInputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOutputMode( ) ); assertEquals( Boolean.TRUE, metadata.isOptional( ) ); assertEquals( Boolean.TRUE, metadata.isNullable( ) ); } } @Test public void testMergeParamHintsWithRuntimeMd() throws Exception { PreparedStatement statement = getConnection().prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = statement.getParameterMetaData(); assertNotNull( parameterMetaData ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setNativeName( "myParam1" ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); statement.addParameterHint( hint ); Collection parameterMetaData1 = statement.getParameterMetaData(); assertNotNull( parameterMetaData1 ); assertNotSame( parameterMetaData, parameterMetaData1 ); Iterator iter = parameterMetaData1.iterator(); while( iter.hasNext() ) { ParameterMetaData metadata = (ParameterMetaData) iter.next(); assertEquals( 1, metadata.getPosition() ); assertEquals( Types.INTEGER, metadata.getDataType() ); assertEquals( "ParamName1", metadata.getName() ); assertEquals( "myParam1", metadata.getNativeName() ); assertEquals( null, metadata.getDefaultValue() ); // assertEquals( "INTEGER", metadata.getNativeTypeName() ); assertEquals( 0, metadata.getScale() ); assertEquals( 10, metadata.getPrecision() ); assertEquals( Boolean.TRUE, metadata.isInputMode() ); assertEquals( Boolean.FALSE, metadata.isOutputMode() ); assertEquals( Boolean.FALSE, metadata.isOptional() ); assertEquals( Boolean.TRUE, metadata.isNullable() ); } } @Test public void testMergeParamHintsWithDefaultValue() throws Exception { PreparedStatement statement = getConnection().prepareStatement( "select \"intColumn\" from \"testtable\" where \"intColumn\" = ?", JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = statement.getParameterMetaData(); assertNotNull( parameterMetaData ); ParameterHint hint = new ParameterHint( "ParamName1", true, false ); hint.setPosition( 1 ); hint.setDataType( Integer.class ); hint.setIsInputOptional( false ); hint.setDefaultInputValue( "123" ); statement.addParameterHint( hint ); Collection parameterMetaData1 = statement.getParameterMetaData(); assertNotNull( parameterMetaData1 ); assertNotSame( parameterMetaData, parameterMetaData1 ); Iterator iter = parameterMetaData1.iterator(); while( iter.hasNext() ) { ParameterMetaData metadata = (ParameterMetaData) iter.next(); assertEquals( 1, metadata.getPosition() ); assertEquals( Types.INTEGER, metadata.getDataType() ); assertEquals( "ParamName1", metadata.getName() ); assertEquals( "123", metadata.getDefaultValue() ); assertEquals( "INTEGER", metadata.getNativeTypeName() ); assertEquals( 0, metadata.getScale() ); assertEquals( 10, metadata.getPrecision() ); assertEquals( Boolean.TRUE, metadata.isInputMode() ); assertEquals( Boolean.FALSE, metadata.isOutputMode() ); assertEquals( Boolean.FALSE, metadata.isOptional() ); assertEquals( Boolean.TRUE, metadata.isNullable() ); } } // Test that the LOB data type specified in a ParameterHint // for an output parameter gets merged with the // runtime parameter metadata. @Test public void testMergeParamHintOnLOB( ) throws Exception { String queryText = "select * from \"testtable_lob\" where \"clob1\" like ? "; PreparedStatement statement = getConnection( ).prepareStatement( queryText, JDBCOdaDataSource.DATA_SET_TYPE ); assertNotNull( statement ); Collection parameterMetaData = statement.getParameterMetaData( ); assertNotNull( parameterMetaData ); ParameterHint hint = new ParameterHint( "OutParam", false, true ); hint.setPosition( 1 ); hint.setDataType( IClob.class ); statement.addParameterHint( hint ); Collection parameterMetaData1 = statement.getParameterMetaData( ); assertNotNull( parameterMetaData1 ); assertNotSame( parameterMetaData, parameterMetaData1 ); Iterator iter = parameterMetaData1.iterator( ); while ( iter.hasNext( ) ) { ParameterMetaData metadata = (ParameterMetaData) iter.next( ); assertEquals( 1, metadata.getPosition( ) ); assertEquals( "OutParam", metadata.getName( ) ); assertEquals( Types.CLOB, metadata.getDataType( ) ); } statement.close(); } }
epl-1.0
insynctiveAutomation/insynctiveAutomation
src/main/java/insynctive/utils/reader/ChecklistReader.java
2191
package insynctive.utils.reader; import java.io.FileReader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.openqa.selenium.WebDriver; import insynctive.utils.data.Checklist; import insynctive.utils.process.Process; public class ChecklistReader { WebDriver driver; JSONParser parser = new JSONParser(); JSONArray jsonCheckList; public ChecklistReader(WebDriver driver, String checkListStringFile) { this.driver = driver; try { jsonCheckList = (JSONArray) parser.parse(new FileReader(checkListStringFile)); } catch (Exception ex) { // TODO THROW EXCEPTION } } public List<Checklist> getAllCheckLists() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { List<Checklist> checkListListToReturn = new ArrayList<Checklist>(); for (Object checklistObject : jsonCheckList) { /* CheckList */ JSONObject jsonChecklist = (JSONObject) checklistObject; JSONArray jsonChecklistProcesses = (JSONArray) jsonChecklist.get("Processes"); String checklistName = (String) jsonChecklist.get("Checklist_Name"); Checklist newChecklist = new Checklist(checklistName); /* Processes */ for (Object precessObject : jsonChecklistProcesses) { JSONObject jsonPrecess = (JSONObject) precessObject; String checklistProcessVersion = (String) jsonPrecess.get("Process_Version"); String checklistProcessName = (String) jsonPrecess.get("Process_Name"); Class<?> processClass = null; try { processClass = Class.forName("insynctive.checklist.process."+ checklistProcessName); } catch (Exception ex) { System.out.println("Exception creating object: "+ ex.getMessage()); } Process process = (Process) processClass.getDeclaredConstructor(WebDriver.class).newInstance(driver); process.setVersion(checklistProcessVersion); newChecklist.addProcess(process); } checkListListToReturn.add(newChecklist); } return checkListListToReturn; } }
epl-1.0
bendisposto/prob2-ui
src/main/java/de/prob2/ui/symbolic/SymbolicExecutor.java
5183
package de.prob2.ui.symbolic; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Injector; import de.prob.animator.command.AbstractCommand; import de.prob.check.IModelCheckJob; import de.prob.statespace.StateSpace; import de.prob2.ui.prob2fx.CurrentProject; import de.prob2.ui.prob2fx.CurrentTrace; import de.prob2.ui.project.machines.Machine; import de.prob2.ui.stats.StatsView; import de.prob2.ui.verifications.symbolicchecking.SymbolicCheckingResultHandler; import javafx.application.Platform; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; public abstract class SymbolicExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(SymbolicExecutor.class); protected final CurrentTrace currentTrace; protected final CurrentProject currentProject; protected final Injector injector; protected final ISymbolicResultHandler resultHandler; protected final List<IModelCheckJob> currentJobs; protected final ListProperty<Thread> currentJobThreads; protected List<? extends SymbolicFormulaItem> items; public SymbolicExecutor(final CurrentTrace currentTrace, final CurrentProject currentProject, final ISymbolicResultHandler resultHandler, final Injector injector) { this.currentTrace = currentTrace; this.currentProject = currentProject; this.resultHandler = resultHandler; this.injector = injector; this.currentJobs = new ArrayList<>(); this.currentJobThreads = new SimpleListProperty<>(this, "currentJobThreads", FXCollections.observableArrayList()); } public void executeCheckingItem(IModelCheckJob checker, String code, SymbolicExecutionType type, boolean checkAll) { getItems().stream() .filter(current -> current.getCode().equals(code) && current.getType().equals(type)) .findFirst() .ifPresent(item -> checkItem(checker, item, checkAll)); } public void interrupt() { List<Thread> removedThreads = new ArrayList<>(); for (Thread thread : currentJobThreads) { thread.interrupt(); removedThreads.add(thread); } List<IModelCheckJob> removedJobs = new ArrayList<>(); removedJobs.addAll(currentJobs); currentTrace.getStateSpace().sendInterrupt(); currentJobThreads.removeAll(removedThreads); currentJobs.removeAll(removedJobs); } public ListProperty<Thread> currentJobThreadsProperty() { return currentJobThreads; } public void checkItem(SymbolicFormulaItem item, AbstractCommand cmd, final StateSpace stateSpace, boolean checkAll) { final SymbolicFormulaItem currentItem = getItemIfAlreadyExists(item); Thread checkingThread = new Thread(() -> { RuntimeException exception = null; try { stateSpace.execute(cmd); } catch (RuntimeException e) { LOGGER.error("Exception during symbolic checking", e); exception = e; } Thread currentThread = Thread.currentThread(); final RuntimeException finalException = exception; Platform.runLater(() -> { injector.getInstance(StatsView.class).update(currentTrace.get()); if (finalException == null) { resultHandler.handleFormulaResult(currentItem, cmd); } else { resultHandler.handleFormulaResult(currentItem, finalException); } updateMachine(currentProject.getCurrentMachine()); if(!checkAll) { updateTrace(currentItem); } }); currentJobThreads.remove(currentThread); }, "Symbolic Formula Checking Thread"); currentJobThreads.add(checkingThread); checkingThread.start(); } public void checkItem(IModelCheckJob checker, SymbolicFormulaItem item, boolean checkAll) { Thread checkingThread = new Thread(() -> { currentJobs.add(checker); Object result; try { result = checker.call(); } catch (Exception e) { LOGGER.error("Could not check CBC Deadlock", e); result = e; } final Object finalResult = result; Platform.runLater(() -> { injector.getInstance(StatsView.class).update(currentTrace.get()); resultHandler.handleFormulaResult(item, finalResult); updateMachine(currentProject.getCurrentMachine()); if(!checkAll) { updateTrace(item); } }); currentJobs.remove(checker); currentJobThreads.remove(Thread.currentThread()); }, "Symbolic Formula Checking Thread"); currentJobThreads.add(checkingThread); checkingThread.start(); } protected abstract void updateTrace(SymbolicFormulaItem item); protected abstract void updateMachine(Machine machine); protected SymbolicFormulaItem getItemIfAlreadyExists(SymbolicFormulaItem item) { List<? extends SymbolicFormulaItem> formulas = getItems(); int index = formulas.indexOf(item); if(index > -1) { item = formulas.get(index); } return item; } private List<? extends SymbolicFormulaItem> getItems() { Machine currentMachine = currentProject.getCurrentMachine(); List<? extends SymbolicFormulaItem> formulas; if(resultHandler instanceof SymbolicCheckingResultHandler) { formulas = currentMachine.getSymbolicCheckingFormulas(); } else { formulas = currentMachine.getSymbolicAnimationFormulas(); } return formulas; } }
epl-1.0
karimhamdanali/averroes
src/averroes/util/io/Resource.java
886
/******************************************************************************* * Copyright (c) 2015 Karim Ali and Ondřej Lhoták. * 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: * Karim Ali - initial API and implementation and/or initial documentation *******************************************************************************/ package averroes.util.io; import java.io.IOException; import java.io.InputStream; /** * A resource is something to which we can open an InputStream 1 or more times. * * Similar to FoundFile in soot.SourceLocator, which is not accessible. */ public interface Resource { public InputStream open() throws IOException; }
epl-1.0
nickmain/xmind
bundles/org.xmind.ui.toolkit/src/org/xmind/ui/internal/ToolkitImages.java
3972
/* ****************************************************************************** * Copyright (c) 2006-2012 XMind Ltd. and others. * * This file is a part of XMind 3. XMind releases 3 and * above are dual-licensed under the Eclipse Public License (EPL), * which is available at http://www.eclipse.org/legal/epl-v10.html * and the GNU Lesser General Public License (LGPL), * which is available at http://www.gnu.org/licenses/lgpl.html * See http://www.xmind.net/license.html for details. * * Contributors: * XMind Ltd. - initial API and implementation *******************************************************************************/ package org.xmind.ui.internal; import java.util.HashMap; import java.util.Map; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; public class ToolkitImages { public static final String PATH_ICONS = "icons/"; //$NON-NLS-1$ public static final String PATH_ENABLED = PATH_ICONS + "e/"; //$NON-NLS-1$ public static final String PATH_DISABLED = PATH_ICONS + "d/"; //$NON-NLS-1$ public static final String ALIGN_CENTER = "align_center.png"; //$NON-NLS-1$ public static final String ALIGN_LEFT = "align_left.png"; //$NON-NLS-1$ public static final String ALIGN_RIGHT = "align_right.png"; //$NON-NLS-1$ public static final String BACKGROUND = "background.png"; //$NON-NLS-1$ public static final String BOLD = "bold.png"; //$NON-NLS-1$ public static final String FONT = "font.gif"; //$NON-NLS-1$ public static final String FOREGROUND = "foreground.png"; //$NON-NLS-1$ public static final String INDENT = "indent.png"; //$NON-NLS-1$ public static final String ITALIC = "italic.png"; //$NON-NLS-1$ public static final String OUTDENT = "outdent.png"; //$NON-NLS-1$ public static final String STRIKEOUT = "strikeout.png"; //$NON-NLS-1$ public static final String UNDERLINE = "underline.png"; //$NON-NLS-1$ public static final String SLIDER_HANDLE = "slider_handle.png"; //$NON-NLS-1$ public static final String ZOOM_IN = "zoomin.gif"; //$NON-NLS-1$ public static final String ZOOM_OUT = "zoomout.gif"; //$NON-NLS-1$ public static final String BULLET = "bullet.gif"; //$NON-NLS-1$ public static final String NUMBER = "number.gif"; //$NON-NLS-1$ private static Map<String, ImageDescriptor> cache = new HashMap<String, ImageDescriptor>(); public static ImageDescriptor getImageDescriptor(String path) { ImageDescriptor img = cache.get(path); if (img == null) { img = ToolkitPlugin .imageDescriptorFromPlugin(ToolkitPlugin.PLUGIN_ID, path); if (img != null) cache.put(path, img); } return img; } public static ImageDescriptor get(String iconName) { return getImageDescriptor(PATH_ICONS + iconName); } public static ImageDescriptor get(String iconName, boolean enabled) { return getImageDescriptor( (enabled ? PATH_ENABLED : PATH_DISABLED) + iconName); } // public static ImageDescriptor getImageDescriptor(String fileName, // boolean enabled) { // String path = (enabled ? PATH_ENABLED : PATH_DISABLED) + fileName; // return getImageDescriptor(path); // } public static Image getImage(String path) { ImageRegistry reg = ToolkitPlugin.getDefault().getImageRegistry(); Image image = reg.get(path); if (image == null) { reg.put(path, get(path)); image = reg.get(path); } return image; } // public static Image getImage(String fileName, boolean enabled) { // String path = (enabled ? PATH_ENABLED : PATH_DISABLED) + fileName; // return getImage(path); // } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/eclipselink.extension.nosql.test/src/org/eclipse/persistence/testing/oxm/mappings/onetomany/keyontarget/Team.java
2605
/******************************************************************************* * 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.oxm.mappings.onetomany.keyontarget; import java.util.Vector; public class Team { private int id; private Vector employees; private Vector projects; public Team() { employees = new Vector(); projects = new Vector(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public void addProject(Project project) { projects.add(project); } public void addEmployee(Employee employee) { employees.add(employee); } public Vector getProjects() { return projects; } public Vector getEmployees() { return employees; } public void setProjects(Vector newProjects) { projects = newProjects; } public void setEmployees(Vector newEmployees) { employees = newEmployees; } public String toString() { String result = "TEAM: " + this.getId(); result += "EMPLOYEES: "; for(int i=0; i<employees.size();i++) { result+= employees.elementAt(i); } result += "PROJECTS: "; for(int i=0; i<projects.size();i++) { result+= projects.elementAt(i); } return result; } public boolean equals(Object object) { if(!(object instanceof Team)) return false; Team teamObject = (Team)object; if((((this.getEmployees() == null) && (teamObject.getEmployees() == null))|| (this.getEmployees().containsAll(teamObject.getEmployees()))) && (((this.getProjects() == null) && (teamObject.getProjects() == null))|| (this.getProjects().containsAll(teamObject.getProjects()))) && (this.getId()==teamObject.getId()) ) return true; return false; } }
epl-1.0
d-s/windup
rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/model/PhantomJavaClassModel.java
377
package org.jboss.windup.rules.apps.java.model; import com.tinkerpop.frames.modules.typedgraph.TypeValue; /** * A {@link JavaClassModel} that has not yet been found. We have a reference to it, * but we have not yet found an actual ".class" or ".java" file with the code. */ @TypeValue("PhantomJavaClass") public interface PhantomJavaClassModel extends JavaClassModel { }
epl-1.0
agentlab/CoffeeNow
plugins/ru.agentlab.maia.dsl/src/ru/agentlab/maia/dsl/Atom.java
111
package ru.agentlab.maia.dsl; public abstract class Atom { public abstract Variable<?>[] getVariables(); }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/ServerXMLConfiguration.java
18326
/******************************************************************************* * Copyright (c) 2013, 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.config.xml.internal; import java.io.File; import java.io.FileFilter; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import org.osgi.framework.BundleContext; import com.ibm.websphere.config.ConfigParserException; import com.ibm.websphere.config.ConfigValidationException; import com.ibm.websphere.ras.Tr; import com.ibm.websphere.ras.TraceComponent; import com.ibm.ws.config.xml.ConfigVariables; import com.ibm.ws.config.xml.LibertyVariable; import com.ibm.ws.config.xml.internal.variables.ConfigVariableRegistry; import com.ibm.ws.ffdc.annotation.FFDCIgnore; import com.ibm.wsspi.kernel.service.location.WsLocationAdmin; import com.ibm.wsspi.kernel.service.location.WsLocationConstants; import com.ibm.wsspi.kernel.service.location.WsResource; import com.ibm.wsspi.kernel.service.utils.TimestampUtils; /** * */ class ServerXMLConfiguration { private static final TraceComponent tc = Tr.register(ServerXMLConfiguration.class, XMLConfigConstants.TR_GROUP, XMLConfigConstants.NLS_PROPS); /** The root XML document (server.xml) */ private final WsResource configRoot; private final WsResource configDropinDefaults; private final WsResource configDropinOverrides; private final BundleContext bundleContext; private ServerConfiguration serverConfiguration; private static final String CONFIG_DROPINS = "configDropins"; private static final String CONFIG_DROPIN_DEFAULTS = CONFIG_DROPINS + "/" + "defaults/"; private static final String CONFIG_DROPIN_OVERRIDES = CONFIG_DROPINS + "/" + "overrides/"; /** * last time config files(root config document and its included documents) are * read */ private volatile long configReadTime = 0; private final XMLConfigParser parser; ServerXMLConfiguration(BundleContext bundleContext, WsLocationAdmin locationService, XMLConfigParser parser) { this.bundleContext = bundleContext; this.parser = parser; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "WsLocationAdmin locations=" + locationService.printLocations(false)); } this.configRoot = locationService.resolveResource(WsLocationConstants.SYMBOL_SERVER_CONFIG_DIR + "/" + WsLocationConstants.SYMBOL_PROCESS_TYPE + ".xml"); this.configDropinDefaults = locationService.resolveResource(WsLocationConstants.SYMBOL_SERVER_CONFIG_DIR + "/" + CONFIG_DROPIN_DEFAULTS); this.configDropinOverrides = locationService.resolveResource(WsLocationConstants.SYMBOL_SERVER_CONFIG_DIR + "/" + CONFIG_DROPIN_OVERRIDES); // Determines if any of the configuration files used by current server has // been updated since the last run. this.configReadTime = getInitialConfigReadTime(bundleContext); } boolean hasConfigRoot() { return configRoot != null; } private static long getInitialConfigReadTime(BundleContext bundleContext) { if (bundleContext == null) { return 0; } File configStamp = bundleContext.getDataFile("configStamp"); if (configStamp != null && configStamp.exists() && configStamp.canRead()) { return TimestampUtils.readTimeFromFile(configStamp); } else { return 0; } } /** * This sets a server's base configuration by processing server's root * configuration document(i.e. server.cfg) * and any of its included configuration resources, but not individual * bundle's default configurations(i.e. bundle.cfg). * <P> * Generally, this should be only done once at the beginning before any of the bundle's default configurations are processed. * * @throws ConfigValidationException * @throws ConfigParserException * */ @FFDCIgnore(ConfigParserTolerableException.class) public void loadInitialConfiguration(ConfigVariableRegistry variableRegistry) throws ConfigValidationException, ConfigParserException { if (configRoot != null && configRoot.exists()) { try { serverConfiguration = loadServerConfiguration(); if (serverConfiguration == null) { // This only happens if there is a parser error and onError has been set to IGNORE or WARN. // We're just avoiding an NPE here. The user will see the server start up with a warning // that nothing has been configured. This is less than ideal in the case of IGNORE, but it's // the behavior the user has asked for. serverConfiguration = new ServerConfiguration(); } } catch (ConfigParserTolerableException ex) { // This only gets caught here if OnError = FAIL.. rethrow so the server will shut down throw ex; } catch (ConfigParserException ex) { Tr.error(tc, "error.config.update.init", ex.getMessage()); serverConfiguration = new ServerConfiguration(); if (ErrorHandler.INSTANCE.fail()) throw ex; } serverConfiguration.setDefaultConfiguration(new BaseConfiguration()); } try { variableRegistry.updateSystemVariables(getVariables()); // Register the ConfigVariables service now that we have populated the registry Hashtable<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.vendor", "IBM"); bundleContext.registerService(ConfigVariables.class, variableRegistry, properties); } catch (ConfigMergeException e) { // Rethrow if onError=FAIL. An error message has already been issued otherwise. if (ErrorHandler.INSTANCE.fail()) { throw new ConfigParserTolerableException(e); } } } public void setConfigReadTime() { setConfigReadTime(getLastResourceModifiedTime()); } public void setConfigReadTime(long time) { // Update time stamp for configReadTime on next run. TimestampUtils.writeTimeToFile(bundleContext.getDataFile("configStamp"), time); configReadTime = time; } private long getLastResourceModifiedTime() { long lastModified = configRoot.getLastModified(); if (serverConfiguration != null) { for (WsResource resource : serverConfiguration.getIncludes()) { long modified = resource.getLastModified(); if (modified > lastModified) { lastModified = modified; } } } if (configDropinDefaults != null) { File[] defaultFiles = getChildXMLFiles(configDropinDefaults); if (defaultFiles != null) { for (File f : defaultFiles) { String name = f.getName(); WsResource resource = configDropinDefaults.resolveRelative(name); long modified = resource.getLastModified(); if (modified > lastModified) { lastModified = modified; } } } } if (configDropinOverrides != null) { File[] overrideFiles = getChildXMLFiles(configDropinOverrides); if (overrideFiles != null) { for (File f : overrideFiles) { String name = f.getName(); WsResource resource = configDropinOverrides.resolveRelative(name); long modified = resource.getLastModified(); if (modified > lastModified) { lastModified = modified; } } } } return lastModified; } // Remove milliseconds from timestamp values to address inconsistencies in container file systems long reduceTimestampPrecision(long value) { return (value / 1000) * 1000; } /** * @return */ public boolean isModified() { return reduceTimestampPrecision(getLastResourceModifiedTime()) != reduceTimestampPrecision(configReadTime); } public Collection<String> getFilesToMonitor() { Collection<String> files = new HashSet<String>(); files.add(configRoot.toRepositoryPath()); for (WsResource resource : serverConfiguration.getIncludes()) { String path = resource.toRepositoryPath(); if (path != null) { files.add(path); } } return files; } /** * Get the directories that should be monitored for changes. At the moment, this is * configDropins/defaults and configDropins/overrides */ public Collection<String> getDirectoriesToMonitor() { Collection<String> files = new HashSet<String>(); if (configDropinDefaults != null) { files.add(configDropinDefaults.toRepositoryPath()); } if (configDropinOverrides != null) { files.add(configDropinOverrides.toRepositoryPath()); } return files; } /** * To maintain the same order across platforms, we have to implement our own comparator. * Otherwise, "aardvark.xml" would come before "Zebra.xml" on windows, and vice versa on unix. */ private static class AlphaComparator implements Comparator<File> { /* * (non-Javadoc) * * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(File o1, File o2) { return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase()); } } @FFDCIgnore({ ConfigParserException.class, ConfigParserTolerableException.class }) private ServerConfiguration loadServerConfiguration() throws ConfigValidationException, ConfigParserException { ServerConfiguration configuration = null; try { try { // Initialize the configuration object here, so that as the parser progresses // we maintain the information if an exception is thrown. configuration = new ServerConfiguration(); // Load files from configDropins/defaults first parseDirectoryFiles(configDropinDefaults, configuration); // Parse server.xml and its includes parser.parseServerConfiguration(configRoot, configuration); // Parse files from configDropins/overrides parseDirectoryFiles(configDropinOverrides, configuration); configuration.updateLastModified(configRoot.getLastModified()); } catch (ConfigParserTolerableException ex) { // We know what this is, so no need to retry throw ex; } catch (ConfigParserException cpe) { // Wait a short period of time and retry. This is to attempt to handle the case where we // parse the configuration in the middle of a file update. try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } finally { // Reset the server configuration so that we can start over from the beginning. configuration = new ServerConfiguration(); parser.parseServerConfiguration(configRoot, configuration); } } } catch (ConfigParserException ex) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Exception while parsing root and referenced config documents. Message=" + ex.getMessage()); } parser.handleParseError(ex, null); if (ErrorHandler.INSTANCE.fail()) { // if onError=FAIL, bubble the exception up the stack throw ex; } else if (ex instanceof ConfigParserTolerableException) { // Mark the last update for the configuration so that we don't try to load it again configuration.updateLastModified(configRoot.getLastModified()); } else { // onError isn't set to FAIL, but we can't tolerate this exception either // so null the configuration reference configuration = null; } } return configuration; } private File[] getChildXMLFiles(WsResource directory) { File defaultsDir = directory.asFile(); if (defaultsDir == null || !defaultsDir.exists()) return null; File[] defaultFiles = defaultsDir.listFiles(new FileFilter() { @Override public boolean accept(File file) { if (file != null && file.isFile()) { String name = file.getName().toLowerCase(); return name.endsWith(".xml"); } return false; } }); return defaultFiles; } /** * Parse all of the config files in a directory in platform insensitive alphabetical order */ private void parseDirectoryFiles(WsResource directory, ServerConfiguration configuration) throws ConfigParserException, ConfigValidationException { if (directory != null) { File[] defaultFiles = getChildXMLFiles(directory); if (defaultFiles == null) return; Arrays.sort(defaultFiles, new AlphaComparator()); for (int i = 0; i < defaultFiles.length; i++) { File file = defaultFiles[i]; if (!file.isFile()) continue; WsResource defaultFile = directory.resolveRelative(file.getName()); if (defaultFile == null) { // This should never happen, but it's conceivable that someone could remove a file // after listFiles and before getChild if (tc.isDebugEnabled()) { Tr.debug(tc, file.getName() + " was not found in directory " + directory.getName() + ". Ignoring. "); } continue; } Tr.audit(tc, "audit.dropin.being.processed", defaultFile.asFile()); try { parser.parseServerConfiguration(defaultFile, configuration); } catch (ConfigParserException ex) { parser.handleParseError(ex, null); if (ErrorHandler.INSTANCE.fail()) { // if onError=FAIL, bubble the exception up the stack throw ex; } else { // Mark the last update for the configuration so that we don't try to load it again configuration.updateLastModified(configRoot.getLastModified()); } } } } } @FFDCIgnore(ConfigParserTolerableException.class) ServerConfiguration loadNewConfiguration() { ServerConfiguration newConfiguration = null; if (configRoot.exists()) { try { newConfiguration = loadServerConfiguration(); setConfigReadTime(); } catch (ConfigParserTolerableException e) { // This is only thrown if OnError = FAIL String message = e.getMessage() == null ? "Parser Failure" : e.getMessage(); Tr.error(tc, "error.config.update.init", new Object[] { message }); } catch (ConfigParserException e) { Tr.error(tc, "error.config.update.init", new Object[] { e.getMessage() }); } catch (ConfigValidationException e) { Tr.warning(tc, "warn.configValidator.refreshFailed"); } if (newConfiguration == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "doRefreshConfiguration(): Error loading new configuration - leaving existing configuration unchanged"); } // Tr.error(tc, "error.config.update.init", new Object[] { e.getMessage() }); return null; } } else { newConfiguration = new ServerConfiguration(); } newConfiguration.setDefaultConfiguration(serverConfiguration.getDefaultConfiguration()); return newConfiguration; } public ServerConfiguration getConfiguration() { return serverConfiguration; } /** * @return */ public BaseConfiguration getDefaultConfiguration() { return serverConfiguration.getDefaultConfiguration(); } /** * @return * @throws ConfigMergeException */ public Map<String, LibertyVariable> getVariables() throws ConfigMergeException { return serverConfiguration.getVariables(); } /** * @param newConfiguration */ public void setNewConfiguration(ServerConfiguration newConfiguration) { this.serverConfiguration = newConfiguration; } public ServerConfiguration copyConfiguration() { ServerConfiguration copy = new ServerConfiguration(); BaseConfiguration dflt = new BaseConfiguration(); copy.add(getConfiguration()); dflt.add(getDefaultConfiguration()); copy.setDefaultConfiguration(dflt); return copy; } }
epl-1.0
ttimbul/eclipse.wst
bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/taglib/ITLDRecord.java
1131
/******************************************************************************* * Copyright (c) 2005, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * *******************************************************************************/ package org.eclipse.jst.jsp.core.taglib; import org.eclipse.core.runtime.IPath; /** * A record representing a standalone .tld file. * <p> * This interface is not intended to be implemented by clients. * </p> * * @since 1.0 */ public interface ITLDRecord extends ITaglibRecord { /** * @return Returns the path within the workspace. */ IPath getPath(); /** * @return Returns the recommended/default prefix if one was given. */ String getShortName(); /** * @deprecated - use the descriptor's URI value * @return Returns the uri. */ String getURI(); }
epl-1.0
TristanFAURE/pickerExplorer
plugins/org.topcased.pickerexplorer.ui/src/org/topcased/pickerexplorer/ui/exceptions/NullPickerException.java
643
/***************************************************************************** * Copyright (c) 2014 Atos. * * * 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.topcased.pickerexplorer.ui.exceptions; public class NullPickerException extends Exception { /** * */ private static final long serialVersionUID = 5575974417446809584L; }
epl-1.0
unverbraucht/kura
kura/org.eclipse.kura.core.comm/src/main/java/org/eclipse/kura/core/comm/CommConnectionImpl.java
10486
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech 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 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.core.comm; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Date; import javax.comm.CommPort; import javax.comm.CommPortIdentifier; import javax.comm.NoSuchPortException; import javax.comm.PortInUseException; import javax.comm.SerialPort; import javax.comm.UnsupportedCommOperationException; import org.eclipse.kura.KuraException; import org.eclipse.kura.comm.CommConnection; import org.eclipse.kura.comm.CommURI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CommConnectionImpl implements CommConnection { private static final Logger s_logger = LoggerFactory.getLogger(CommConnectionImpl.class); // set up the appropriate ext dir for RXTX extra device nodes static { String kuraExtDir = System.getProperty("kura.ext.dir"); if (kuraExtDir != null) { StringBuffer sb = new StringBuffer(); String existingDirs = System.getProperty("java.ext.dirs"); if (existingDirs != null) { if (!existingDirs.contains(kuraExtDir)) { sb.append(existingDirs).append(":").append(kuraExtDir); System.setProperty("java.ext.dirs", sb.toString()); } } else { sb.append(kuraExtDir); System.setProperty("java.ext.dirs", sb.toString()); } } } private final String m_port; private final int m_baudRate; private final int m_dataBits; private final int m_stopBits; private final int m_parity; private final int m_flowControl; private final int m_timeout; private final CommURI m_commUri; private SerialPort m_serialPort; private InputStream m_inputStream; private OutputStream m_outputStream; public CommConnectionImpl(CommURI commUri, int mode, boolean timeouts) throws IOException, NoSuchPortException, PortInUseException { this.m_commUri = commUri; this.m_serialPort = null; this.m_port = this.m_commUri.getPort(); this.m_baudRate = this.m_commUri.getBaudRate(); this.m_dataBits = this.m_commUri.getDataBits(); this.m_stopBits = this.m_commUri.getStopBits(); this.m_parity = this.m_commUri.getParity(); this.m_flowControl = this.m_commUri.getFlowControl(); this.m_timeout = this.m_commUri.getTimeout(); CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(this.m_port); CommPort commPort = commPortIdentifier.open(this.getClass().getName(), this.m_timeout); if (commPort instanceof SerialPort) { this.m_serialPort = (SerialPort) commPort; try { this.m_serialPort.setSerialPortParams(this.m_baudRate, this.m_dataBits, this.m_stopBits, this.m_parity); this.m_serialPort.setFlowControlMode(this.m_flowControl); } catch (UnsupportedCommOperationException e) { e.printStackTrace(); } } else { throw new IOException("Unsupported Port Type"); } } @Override public CommURI getURI() { return this.m_commUri; } @Override public DataInputStream openDataInputStream() throws IOException { return new DataInputStream(openInputStream()); } @Override public synchronized InputStream openInputStream() throws IOException { if (this.m_inputStream == null) { this.m_inputStream = this.m_serialPort.getInputStream(); } return this.m_inputStream; } @Override public DataOutputStream openDataOutputStream() throws IOException { return new DataOutputStream(openOutputStream()); } @Override public synchronized OutputStream openOutputStream() throws IOException { if (this.m_outputStream == null) { this.m_outputStream = this.m_serialPort.getOutputStream(); } return this.m_outputStream; } @Override public synchronized void close() throws IOException { if (this.m_serialPort != null) { this.m_serialPort.notifyOnDataAvailable(false); this.m_serialPort.removeEventListener(); if (this.m_inputStream != null) { this.m_inputStream.close(); this.m_inputStream = null; } if (this.m_outputStream != null) { this.m_outputStream.close(); this.m_outputStream = null; } this.m_serialPort.close(); this.m_serialPort = null; } } @Override public synchronized void sendMessage(byte[] message) throws KuraException, IOException { if (message != null) { s_logger.debug("sendMessage() - {}", getBytesAsString(message)); if (this.m_outputStream == null) { openOutputStream(); } this.m_outputStream.write(message, 0, message.length); this.m_outputStream.flush(); } else { throw new NullPointerException("Serial message is null"); } } @Override public synchronized byte[] sendCommand(byte[] command, int timeout) throws KuraException, IOException { if (command != null) { s_logger.debug("sendMessage() - {}", getBytesAsString(command)); if (this.m_outputStream == null) { openOutputStream(); } if (this.m_inputStream == null) { openInputStream(); } byte[] dataInBuffer = flushSerialBuffer(); if (dataInBuffer != null && dataInBuffer.length > 0) { s_logger.warn("eating bytes in the serial buffer input stream before sending command: " + getBytesAsString(dataInBuffer)); } this.m_outputStream.write(command, 0, command.length); this.m_outputStream.flush(); ByteBuffer buffer = getResponse(timeout); if (buffer != null) { byte[] response = new byte[buffer.limit()]; buffer.get(response, 0, response.length); return response; } else { return null; } } else { throw new NullPointerException("Serial command is null"); } } @Override public synchronized byte[] sendCommand(byte[] command, int timeout, int demark) throws KuraException, IOException { if (command != null) { s_logger.debug("sendMessage() - {}", getBytesAsString(command)); if (this.m_outputStream == null) { openOutputStream(); } if (this.m_inputStream == null) { openInputStream(); } byte[] dataInBuffer = flushSerialBuffer(); if (dataInBuffer != null && dataInBuffer.length > 0) { s_logger.warn("eating bytes in the serial buffer input stream before sending command: " + getBytesAsString(dataInBuffer)); } this.m_outputStream.write(command, 0, command.length); this.m_outputStream.flush(); ByteBuffer buffer = getResponse(timeout, demark); if (buffer != null) { byte[] response = new byte[buffer.limit()]; buffer.get(response, 0, response.length); return response; } else { return null; } } else { throw new NullPointerException("Serial command is null"); } } @Override public synchronized byte[] flushSerialBuffer() throws KuraException, IOException { ByteBuffer buffer = getResponse(50); if (buffer != null) { byte[] response = new byte[buffer.limit()]; buffer.get(response, 0, response.length); return response; } else { return null; } } private synchronized ByteBuffer getResponse(int timeout) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(4096); Date start = new Date(); while (this.m_inputStream.available() < 1 && new Date().getTime() - start.getTime() < timeout) { try { Thread.sleep(10); } catch (InterruptedException e) { // ignore } } while (this.m_inputStream.available() >= 1) { int c = this.m_inputStream.read(); buffer.put((byte) c); } buffer.flip(); return buffer.limit() > 0 ? buffer : null; } private synchronized ByteBuffer getResponse(int timeout, int demark) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(4096); long start = System.currentTimeMillis(); while (this.m_inputStream.available() < 1 && System.currentTimeMillis() - start < timeout) { try { Thread.sleep(10); } catch (InterruptedException e) { } } start = System.currentTimeMillis(); do { if (this.m_inputStream.available() > 0) { start = System.currentTimeMillis(); int c = this.m_inputStream.read(); buffer.put((byte) c); } } while (System.currentTimeMillis() - start < demark); buffer.flip(); return buffer.limit() > 0 ? buffer : null; } private String getBytesAsString(byte[] bytes) { if (bytes == null) { return null; } else { StringBuffer sb = new StringBuffer(); for (byte b : bytes) { sb.append("0x").append(Integer.toHexString(b)).append(" "); } return sb.toString(); } } }
epl-1.0
FTSRG/mondo-collab-framework
plugins/org.mondo.collaboration.security.lens.test.ui/src/org/mondo/collaboration/security/lens/test/ui/ExecutableExtensionFactory.java
957
/******************************************************************************* * Copyright (c) 2004-2015 Gabor Bergmann and Daniel Varro * 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: * Gabor Bergmann - initial API and implementation *******************************************************************************/ package org.mondo.collaboration.security.lens.test.ui; import org.eclipse.incquery.patternlanguage.emf.ui.EMFPatternLanguageExecutableExtensionFactory; import org.osgi.framework.Bundle; /** * @author Bergmann Gabor * */ public class ExecutableExtensionFactory extends EMFPatternLanguageExecutableExtensionFactory { @Override protected Bundle getBundle() { return Activator.getDefault().getBundle(); } }
epl-1.0
maxeler/eclipse
eclipse.jdt.core/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
25536
/******************************************************************************* * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.core; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.core.JavaModelManager.PerProjectInfo; import org.eclipse.jdt.internal.core.util.Util; /** * Keep the global states used during Java element delta processing. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class DeltaProcessingState implements IResourceChangeListener { /* * Collection of listeners for Java element deltas */ public IElementChangedListener[] elementChangedListeners = new IElementChangedListener[5]; public int[] elementChangedListenerMasks = new int[5]; public int elementChangedListenerCount = 0; /* * Collection of pre Java resource change listeners */ public IResourceChangeListener[] preResourceChangeListeners = new IResourceChangeListener[1]; public int[] preResourceChangeEventMasks = new int[1]; public int preResourceChangeListenerCount = 0; /* * The delta processor for the current thread. */ private ThreadLocal deltaProcessors = new ThreadLocal(); public void doNotUse() { // reset the delta processor of the current thread to avoid to keep it in memory // https://bugs.eclipse.org/bugs/show_bug.cgi?id=269476 this.deltaProcessors.set(null); } /* A table from IPath (from a classpath entry) to DeltaProcessor.RootInfo */ public HashMap roots = new HashMap(); /* A table from IPath (from a classpath entry) to ArrayList of DeltaProcessor.RootInfo * Used when an IPath corresponds to more than one root */ public HashMap otherRoots = new HashMap(); /* A table from IPath (from a classpath entry) to DeltaProcessor.RootInfo * from the last time the delta processor was invoked. */ public HashMap oldRoots = new HashMap(); /* A table from IPath (from a classpath entry) to ArrayList of DeltaProcessor.RootInfo * from the last time the delta processor was invoked. * Used when an IPath corresponds to more than one root */ public HashMap oldOtherRoots = new HashMap(); /* A table from IPath (a source attachment path from a classpath entry) to IPath (a root path) */ public HashMap sourceAttachments = new HashMap(); /* A table from IJavaProject to IJavaProject[] (the list of direct dependent of the key) */ public HashMap projectDependencies = new HashMap(); /* Whether the roots tables should be recomputed */ public boolean rootsAreStale = true; /* Threads that are currently running initializeRoots() */ private Set initializingThreads = Collections.synchronizedSet(new HashSet()); /* A table from file system absoulte path (String) to timestamp (Long) */ public Hashtable externalTimeStamps; /* * Map from IProject to ClasspathChange * Note these changes need to be kept on the delta processing state to ensure we don't loose them * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=271102 Java model corrupt after switching target platform) */ private HashMap classpathChanges = new HashMap(); /* A table from JavaProject to ClasspathValidation */ private HashMap classpathValidations = new HashMap(); /* A table from JavaProject to ProjectReferenceChange */ private HashMap projectReferenceChanges = new HashMap(); /* A table from JavaProject to ExternalFolderChange */ private HashMap externalFolderChanges = new HashMap(); /** * Workaround for bug 15168 circular errors not reported * This is a cache of the projects before any project addition/deletion has started. */ private HashSet javaProjectNamesCache; /* * A list of IJavaElement used as a scope for external archives refresh during POST_CHANGE. * This is null if no refresh is needed. */ private HashSet externalElementsToRefresh; /* * Need to clone defensively the listener information, in case some listener is reacting to some notification iteration by adding/changing/removing * any of the other (for example, if it deregisters itself). */ public synchronized void addElementChangedListener(IElementChangedListener listener, int eventMask) { for (int i = 0; i < this.elementChangedListenerCount; i++){ if (this.elementChangedListeners[i] == listener){ // only clone the masks, since we could be in the middle of notifications and one listener decide to change // any event mask of another listeners (yet not notified). int cloneLength = this.elementChangedListenerMasks.length; System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[cloneLength], 0, cloneLength); this.elementChangedListenerMasks[i] |= eventMask; // could be different return; } } // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end. int length; if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount){ System.arraycopy(this.elementChangedListeners, 0, this.elementChangedListeners = new IElementChangedListener[length*2], 0, length); System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[length*2], 0, length); } this.elementChangedListeners[this.elementChangedListenerCount] = listener; this.elementChangedListenerMasks[this.elementChangedListenerCount] = eventMask; this.elementChangedListenerCount++; } /* * Adds the given element to the list of elements used as a scope for external jars refresh. */ public synchronized void addForRefresh(IJavaElement externalElement) { if (this.externalElementsToRefresh == null) { this.externalElementsToRefresh = new HashSet(); } this.externalElementsToRefresh.add(externalElement); } public synchronized void addPreResourceChangedListener(IResourceChangeListener listener, int eventMask) { for (int i = 0; i < this.preResourceChangeListenerCount; i++){ if (this.preResourceChangeListeners[i] == listener) { this.preResourceChangeEventMasks[i] |= eventMask; return; } } // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end. int length; if ((length = this.preResourceChangeListeners.length) == this.preResourceChangeListenerCount) { System.arraycopy(this.preResourceChangeListeners, 0, this.preResourceChangeListeners = new IResourceChangeListener[length*2], 0, length); System.arraycopy(this.preResourceChangeEventMasks, 0, this.preResourceChangeEventMasks = new int[length*2], 0, length); } this.preResourceChangeListeners[this.preResourceChangeListenerCount] = listener; this.preResourceChangeEventMasks[this.preResourceChangeListenerCount] = eventMask; this.preResourceChangeListenerCount++; } public DeltaProcessor getDeltaProcessor() { DeltaProcessor deltaProcessor = (DeltaProcessor)this.deltaProcessors.get(); if (deltaProcessor != null) return deltaProcessor; deltaProcessor = new DeltaProcessor(this, JavaModelManager.getJavaModelManager()); this.deltaProcessors.set(deltaProcessor); return deltaProcessor; } public synchronized ClasspathChange addClasspathChange(IProject project, IClasspathEntry[] oldRawClasspath, IPath oldOutputLocation, IClasspathEntry[] oldResolvedClasspath) { ClasspathChange change = (ClasspathChange) this.classpathChanges.get(project); if (change == null) { change = new ClasspathChange((JavaProject) JavaModelManager.getJavaModelManager().getJavaModel().getJavaProject(project), oldRawClasspath, oldOutputLocation, oldResolvedClasspath); this.classpathChanges.put(project, change); } else { if (change.oldRawClasspath == null) change.oldRawClasspath = oldRawClasspath; if (change.oldOutputLocation == null) change.oldOutputLocation = oldOutputLocation; if (change.oldResolvedClasspath == null) change.oldResolvedClasspath = oldResolvedClasspath; } return change; } public synchronized ClasspathChange getClasspathChange(IProject project) { return (ClasspathChange) this.classpathChanges.get(project); } public synchronized HashMap removeAllClasspathChanges() { HashMap result = this.classpathChanges; this.classpathChanges = new HashMap(result.size()); return result; } public synchronized ClasspathValidation addClasspathValidation(JavaProject project) { ClasspathValidation validation = (ClasspathValidation) this.classpathValidations.get(project); if (validation == null) { validation = new ClasspathValidation(project); this.classpathValidations.put(project, validation); } return validation; } public synchronized void addExternalFolderChange(JavaProject project, IClasspathEntry[] oldResolvedClasspath) { ExternalFolderChange change = (ExternalFolderChange) this.externalFolderChanges.get(project); if (change == null) { change = new ExternalFolderChange(project, oldResolvedClasspath); this.externalFolderChanges.put(project, change); } } public synchronized void addProjectReferenceChange(JavaProject project, IClasspathEntry[] oldResolvedClasspath) { ProjectReferenceChange change = (ProjectReferenceChange) this.projectReferenceChanges.get(project); if (change == null) { change = new ProjectReferenceChange(project, oldResolvedClasspath); this.projectReferenceChanges.put(project, change); } } public void initializeRoots(boolean initAfterLoad) { // recompute root infos only if necessary HashMap[] rootInfos = null; if (this.rootsAreStale) { Thread currentThread = Thread.currentThread(); boolean addedCurrentThread = false; try { // if reentering initialization (through a container initializer for example) no need to compute roots again // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=47213 if (!this.initializingThreads.add(currentThread)) return; addedCurrentThread = true; // all classpaths in the workspace are going to be resolved // ensure that containers are initialized in one batch JavaModelManager.getJavaModelManager().forceBatchInitializations(initAfterLoad); rootInfos = getRootInfos(false/*don't use previous session values*/); } finally { if (addedCurrentThread) { this.initializingThreads.remove(currentThread); } } } synchronized(this) { this.oldRoots = this.roots; this.oldOtherRoots = this.otherRoots; if (this.rootsAreStale && rootInfos != null) { // double check again this.roots = rootInfos[0]; this.otherRoots = rootInfos[1]; this.sourceAttachments = rootInfos[2]; this.projectDependencies = rootInfos[3]; this.rootsAreStale = false; } } } synchronized void initializeRootsWithPreviousSession() { HashMap[] rootInfos = getRootInfos(true/*use previous session values*/); if (rootInfos != null) { this.roots = rootInfos[0]; this.otherRoots = rootInfos[1]; this.sourceAttachments = rootInfos[2]; this.projectDependencies = rootInfos[3]; this.rootsAreStale = false; } } private HashMap[] getRootInfos(boolean usePreviousSession) { HashMap newRoots = new HashMap(); HashMap newOtherRoots = new HashMap(); HashMap newSourceAttachments = new HashMap(); HashMap newProjectDependencies = new HashMap(); IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel(); IJavaProject[] projects; try { projects = model.getJavaProjects(); } catch (JavaModelException e) { // nothing can be done return null; } for (int i = 0, length = projects.length; i < length; i++) { JavaProject project = (JavaProject) projects[i]; IClasspathEntry[] classpath; try { if (usePreviousSession) { PerProjectInfo perProjectInfo = project.getPerProjectInfo(); project.resolveClasspath(perProjectInfo, true/*use previous session values*/, false/*don't add classpath change*/); classpath = perProjectInfo.resolvedClasspath; } else { classpath = project.getResolvedClasspath(); } } catch (JavaModelException e) { // continue with next project continue; } for (int j= 0, classpathLength = classpath.length; j < classpathLength; j++) { IClasspathEntry entry = classpath[j]; if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IJavaProject key = model.getJavaProject(entry.getPath().segment(0)); // TODO (jerome) reuse handle IJavaProject[] dependents = (IJavaProject[]) newProjectDependencies.get(key); if (dependents == null) { dependents = new IJavaProject[] {project}; } else { int dependentsLength = dependents.length; System.arraycopy(dependents, 0, dependents = new IJavaProject[dependentsLength+1], 0, dependentsLength); dependents[dependentsLength] = project; } newProjectDependencies.put(key, dependents); continue; } // root path IPath path = entry.getPath(); if (newRoots.get(path) == null) { newRoots.put(path, new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind())); } else { ArrayList rootList = (ArrayList)newOtherRoots.get(path); if (rootList == null) { rootList = new ArrayList(); newOtherRoots.put(path, rootList); } rootList.add(new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind())); } // source attachment path if (entry.getEntryKind() != IClasspathEntry.CPE_LIBRARY) continue; String propertyString = null; try { propertyString = Util.getSourceAttachmentProperty(path); } catch (JavaModelException e) { e.printStackTrace(); } IPath sourceAttachmentPath; if (propertyString != null) { int index= propertyString.lastIndexOf(PackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER); sourceAttachmentPath = (index < 0) ? new Path(propertyString) : new Path(propertyString.substring(0, index)); } else { sourceAttachmentPath = entry.getSourceAttachmentPath(); } if (sourceAttachmentPath != null) { newSourceAttachments.put(sourceAttachmentPath, path); } } } return new HashMap[] {newRoots, newOtherRoots, newSourceAttachments, newProjectDependencies}; } public synchronized ClasspathValidation[] removeClasspathValidations() { int length = this.classpathValidations.size(); if (length == 0) return null; ClasspathValidation[] validations = new ClasspathValidation[length]; this.classpathValidations.values().toArray(validations); this.classpathValidations.clear(); return validations; } public synchronized ExternalFolderChange[] removeExternalFolderChanges() { int length = this.externalFolderChanges.size(); if (length == 0) return null; ExternalFolderChange[] updates = new ExternalFolderChange[length]; this.externalFolderChanges.values().toArray(updates); this.externalFolderChanges.clear(); return updates; } public synchronized ProjectReferenceChange[] removeProjectReferenceChanges() { int length = this.projectReferenceChanges.size(); if (length == 0) return null; ProjectReferenceChange[] updates = new ProjectReferenceChange[length]; this.projectReferenceChanges.values().toArray(updates); this.projectReferenceChanges.clear(); return updates; } public synchronized HashSet removeExternalElementsToRefresh() { HashSet result = this.externalElementsToRefresh; this.externalElementsToRefresh = null; return result; } public synchronized void removeElementChangedListener(IElementChangedListener listener) { for (int i = 0; i < this.elementChangedListenerCount; i++){ if (this.elementChangedListeners[i] == listener){ // need to clone defensively since we might be in the middle of listener notifications (#fire) int length = this.elementChangedListeners.length; IElementChangedListener[] newListeners = new IElementChangedListener[length]; System.arraycopy(this.elementChangedListeners, 0, newListeners, 0, i); int[] newMasks = new int[length]; System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, 0, i); // copy trailing listeners int trailingLength = this.elementChangedListenerCount - i - 1; if (trailingLength > 0){ System.arraycopy(this.elementChangedListeners, i+1, newListeners, i, trailingLength); System.arraycopy(this.elementChangedListenerMasks, i+1, newMasks, i, trailingLength); } // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto // the original ones) this.elementChangedListeners = newListeners; this.elementChangedListenerMasks = newMasks; this.elementChangedListenerCount--; return; } } } public synchronized void removePreResourceChangedListener(IResourceChangeListener listener) { for (int i = 0; i < this.preResourceChangeListenerCount; i++){ if (this.preResourceChangeListeners[i] == listener){ // need to clone defensively since we might be in the middle of listener notifications (#fire) int length = this.preResourceChangeListeners.length; IResourceChangeListener[] newListeners = new IResourceChangeListener[length]; int[] newEventMasks = new int[length]; System.arraycopy(this.preResourceChangeListeners, 0, newListeners, 0, i); System.arraycopy(this.preResourceChangeEventMasks, 0, newEventMasks, 0, i); // copy trailing listeners int trailingLength = this.preResourceChangeListenerCount - i - 1; if (trailingLength > 0) { System.arraycopy(this.preResourceChangeListeners, i+1, newListeners, i, trailingLength); System.arraycopy(this.preResourceChangeEventMasks, i+1, newEventMasks, i, trailingLength); } // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto // the original ones) this.preResourceChangeListeners = newListeners; this.preResourceChangeEventMasks = newEventMasks; this.preResourceChangeListenerCount--; return; } } } public void resourceChanged(final IResourceChangeEvent event) { for (int i = 0; i < this.preResourceChangeListenerCount; i++) { // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief final IResourceChangeListener listener = this.preResourceChangeListeners[i]; if ((this.preResourceChangeEventMasks[i] & event.getType()) != 0) SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { Util.log(exception, "Exception occurred in listener of pre Java resource change notification"); //$NON-NLS-1$ } public void run() throws Exception { listener.resourceChanged(event); } }); } try { getDeltaProcessor().resourceChanged(event); } finally { // TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ? if (event.getType() == IResourceChangeEvent.POST_CHANGE) { this.deltaProcessors.set(null); } else { // If we are going to reuse the delta processor of this thread, don't hang on to state // that isn't meant to be reused. https://bugs.eclipse.org/bugs/show_bug.cgi?id=273385 getDeltaProcessor().overridenEventType = -1; } } } public Hashtable getExternalLibTimeStamps() { if (this.externalTimeStamps == null) { Hashtable timeStamps = new Hashtable(); File timestampsFile = getTimeStampsFile(); DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new FileInputStream(timestampsFile))); int size = in.readInt(); while (size-- > 0) { String key = in.readUTF(); long timestamp = in.readLong(); timeStamps.put(Path.fromPortableString(key), new Long(timestamp)); } } catch (IOException e) { if (timestampsFile.exists()) Util.log(e, "Unable to read external time stamps"); //$NON-NLS-1$ } finally { if (in != null) { try { in.close(); } catch (IOException e) { // nothing we can do: ignore } } } this.externalTimeStamps = timeStamps; } return this.externalTimeStamps; } public IJavaProject findJavaProject(String name) { if (getOldJavaProjecNames().contains(name)) return JavaModelManager.getJavaModelManager().getJavaModel().getJavaProject(name); return null; } /* * Workaround for bug 15168 circular errors not reported * Returns the list of java projects before resource delta processing * has started. */ public synchronized HashSet getOldJavaProjecNames() { if (this.javaProjectNamesCache == null) { HashSet result = new HashSet(); IJavaProject[] projects; try { projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects(); } catch (JavaModelException e) { return this.javaProjectNamesCache; } for (int i = 0, length = projects.length; i < length; i++) { IJavaProject project = projects[i]; result.add(project.getElementName()); } return this.javaProjectNamesCache = result; } return this.javaProjectNamesCache; } public synchronized void resetOldJavaProjectNames() { this.javaProjectNamesCache = null; } private File getTimeStampsFile() { return JavaCore.getPlugin().getStateLocation().append("externalLibsTimeStamps").toFile(); //$NON-NLS-1$ } public void saveExternalLibTimeStamps() throws CoreException { if (this.externalTimeStamps == null) return; // cleanup to avoid any leak ( https://bugs.eclipse.org/bugs/show_bug.cgi?id=244849 ) HashSet toRemove = new HashSet(); if (this.roots != null) { Enumeration keys = this.externalTimeStamps.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (this.roots.get(key) == null) { toRemove.add(key); } } } File timestamps = getTimeStampsFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(timestamps))); out.writeInt(this.externalTimeStamps.size() - toRemove.size()); Iterator entries = this.externalTimeStamps.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); IPath key = (IPath) entry.getKey(); if (!toRemove.contains(key)) { out.writeUTF(key.toPortableString()); Long timestamp = (Long) entry.getValue(); out.writeLong(timestamp.longValue()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } } /* * Update the roots that are affected by the addition or the removal of the given container resource. */ public synchronized void updateRoots(IPath containerPath, IResourceDelta containerDelta, DeltaProcessor deltaProcessor) { Map updatedRoots; Map otherUpdatedRoots; if (containerDelta.getKind() == IResourceDelta.REMOVED) { updatedRoots = this.oldRoots; otherUpdatedRoots = this.oldOtherRoots; } else { updatedRoots = this.roots; otherUpdatedRoots = this.otherRoots; } int containerSegmentCount = containerPath.segmentCount(); boolean containerIsProject = containerSegmentCount == 1; Iterator iterator = updatedRoots.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); IPath path = (IPath) entry.getKey(); if (containerPath.isPrefixOf(path) && !containerPath.equals(path)) { IResourceDelta rootDelta = containerDelta.findMember(path.removeFirstSegments(containerSegmentCount)); if (rootDelta == null) continue; DeltaProcessor.RootInfo rootInfo = (DeltaProcessor.RootInfo) entry.getValue(); if (!containerIsProject || !rootInfo.project.getPath().isPrefixOf(path)) { // only consider folder roots that are not included in the container deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); } ArrayList rootList = (ArrayList)otherUpdatedRoots.get(path); if (rootList != null) { Iterator otherProjects = rootList.iterator(); while (otherProjects.hasNext()) { rootInfo = (DeltaProcessor.RootInfo)otherProjects.next(); if (!containerIsProject || !rootInfo.project.getPath().isPrefixOf(path)) { // only consider folder roots that are not included in the container deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); } } } } } } }
epl-1.0
Beagle-PSE/Beagle
Core/src/main/java/de/uka/ipd/sdq/beagle/core/judge/EvaluableExpressionComplexityAnalyser.java
11941
package de.uka.ipd.sdq.beagle.core.judge; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.AdditionExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.ComparisonExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.ConstantExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.DivisionExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableVariable; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.ExponentationExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.ExponentialFunctionExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.IfThenElseExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.LogarithmExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.MultiplicationExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.NaturalLogarithmExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.SineExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.SubtractionExpression; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.RecursiveEvaluableExpressionVisitor; import org.apache.commons.lang3.Validate; /* * ATTENTION: Checkstyle is turned off where numbers with obvious meanings are used. */ /** * EvaluableExpressionComplexityAnalyser object for an {@link EvaluableExpression}. * * <p>{@link #determineComplexity(EvaluableExpression)} must be called before * {@link #getComputationalComplexitySum()} or * {@link #getHumanComprehensibilityComplexitySum()} are called. * * * @author Christoph Michelbach */ public class EvaluableExpressionComplexityAnalyser { /** * Every expression with depth larger than this will receive {@link #DEPTH_PENALTY} of * penalty in human-comprehensibility. */ private static final int DEPTH_PENALTY_THRESHOLD = 2; /** * If the maximum depth exceeds {@link #DEPTH_PENALTY_THRESHOLD}, the maximum depth to * the power of {@link PENALTY_MAX_DEPTH_EXPONTENT} times * {@link PENALTY_MAX_DEPTH_FACTOR} will be added to * {@link #humanComprehensibilityComplexitySum}. */ private static final double PENALTY_MAX_DEPTH_EXPONTENT = 1.4d; /** * If the maximum depth exceeds {@link #DEPTH_PENALTY_THRESHOLD}, the maximum depth to * the power of {@link PENALTY_MAX_DEPTH_EXPONTENT} times * {@link PENALTY_MAX_DEPTH_FACTOR} will be added to * {@link #humanComprehensibilityComplexitySum}. */ private static final double PENALTY_MAX_DEPTH_FACTOR = 2.7d; /** * The factor for the depth penalty of every expression branch. Every expression with * depth larger than {@link #DEPTH_PENALTY_THRESHOLD} will receive this much penalty * in human-comprehensibility in combination with {@link #DEPTH_PENALTY_EXPONENT}. */ private static final double DEPTH_PENATLY_FACOTOR = .5d; /** * The exponent for the depth penalty of every expression branch. Every expression * with depth larger than {@link #DEPTH_PENALTY_THRESHOLD} will receive this much * penalty in human-comprehensibility in combination with * {@link #DEPTH_PENATLY_FACOTOR}. */ private static final double DEPTH_PENALTY_EXPONENT = 1.3d; /** * The visitor this class uses. */ private Visitor visitor; /** * Determines the computational and human-readability complexity of {@code expression} * . * * @param expression The {@link EvaluableExpression} to determine the complexity * values for. */ public void determineComplexity(final EvaluableExpression expression) { this.visitor = new Visitor(); this.visitor.visitRecursively(expression); if (this.visitor.maxDepth > DEPTH_PENALTY_THRESHOLD) { this.visitor.humanComprehensibilityComplexitySum += PENALTY_MAX_DEPTH_FACTOR * Math.pow(this.visitor.maxDepth, PENALTY_MAX_DEPTH_EXPONTENT); } } /** * Returns the computational complexity. * * <p>{@link #determineComplexity(EvaluableExpression)} must be called before this * method or an {@link IllegalStateException} will be thrown. * * @return The computationalComplexitySum. */ public double getComputationalComplexitySum() { Validate.validState(this.visitor != null); return this.visitor.computationalComplexitySum; } /** * Returns the human-comprehensibility complexity. * * <p>{@link #determineComplexity(EvaluableExpression)} must be called before this * method or an {@link IllegalStateException} will be thrown. * * @return The humanComprehensibilityComplexitySum. */ public double getHumanComprehensibilityComplexitySum() { Validate.validState(this.visitor != null); return this.visitor.humanComprehensibilityComplexitySum; } /** * Private class for hiding the visitor pattern. * * @author Christoph Michelbach */ private class Visitor extends RecursiveEvaluableExpressionVisitor { /** * The total computational complexity. The values added up to this sum have been * determined on a laptop with an Intel® Core™ i7-4720HQ CPU @ 2.60GHz × 8 (8 * cores with Hyper-Threading; 4 cores physically) processor running Linux * 3.19.0-30-generic. */ private double computationalComplexitySum; /** * The total human-readability complexity. */ private double humanComprehensibilityComplexitySum; /** * The maximum depth of this expression. */ private int maxDepth; @Override protected void visitRecursively(final EvaluableExpression expression) { super.visitRecursively(expression); } @Override protected void atExpression(final EvaluableExpression expression) { if (this.getTraversalDepth() > DEPTH_PENALTY_THRESHOLD) { this.humanComprehensibilityComplexitySum += DEPTH_PENATLY_FACOTOR * Math.pow(this.getTraversalDepth(), DEPTH_PENALTY_EXPONENT); } if (this.getTraversalDepth() > this.maxDepth) { this.maxDepth = this.getTraversalDepth(); } } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atAddition(de.uka.ipd.sdq.beagle.core.evaluableexpressions.AdditionExpression) */ @Override protected void atAddition(final AdditionExpression expression) { final int numberOfElements = expression.getSummands().size(); this.computationalComplexitySum += 1d * (numberOfElements - 1); this.humanComprehensibilityComplexitySum += 1d * (numberOfElements - 1); } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atMultiplication(de.uka.ipd.sdq.beagle.core.evaluableexpressions. * MultiplicationExpression) */ @Override protected void atMultiplication(final MultiplicationExpression expression) { final int numberOfElements = expression.getFactors().size(); // CHECKSTYLE:OFF this.computationalComplexitySum += 1.6492450638792102d * (numberOfElements - 1); this.humanComprehensibilityComplexitySum += 3d * (numberOfElements - 1); // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atVariable(de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableVariable) */ @Override protected void atVariable(final EvaluableVariable expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 1d; this.humanComprehensibilityComplexitySum += 4d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atComparison(de.uka.ipd.sdq.beagle.core.evaluableexpressions. * ComparisonExpression) */ @Override protected void atComparison(final ComparisonExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 1d; this.humanComprehensibilityComplexitySum += 3d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atConstant(de.uka.ipd.sdq.beagle.core.evaluableexpressions.ConstantExpression) */ @Override protected void atConstant(final ConstantExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += .1d; this.humanComprehensibilityComplexitySum += .1d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atDivision(de.uka.ipd.sdq.beagle.core.evaluableexpressions.DivisionExpression) */ @Override protected void atDivision(final DivisionExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 3.2740998838559814d; this.humanComprehensibilityComplexitySum += 7d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atExponentation(de.uka.ipd.sdq.beagle.core.evaluableexpressions. * ExponentationExpression) */ @Override protected void atExponentation(final ExponentationExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 2177.7277840269966d; this.humanComprehensibilityComplexitySum += 12d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atExponentialFunction(de.uka.ipd.sdq.beagle.core.evaluableexpressions. * ExponentialFunctionExpression) */ @Override protected void atExponentialFunction(final ExponentialFunctionExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 941.1764705882353d; this.humanComprehensibilityComplexitySum += 20d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atIfThenElse(de.uka.ipd.sdq.beagle.core.evaluableexpressions. * IfThenElseExpression) */ @Override protected void atIfThenElse(final IfThenElseExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 2d; this.humanComprehensibilityComplexitySum += 4d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atLogarithm(de.uka.ipd.sdq.beagle.core.evaluableexpressions. * LogarithmExpression) */ @Override protected void atLogarithm(final LogarithmExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 126.78362573099415d; this.humanComprehensibilityComplexitySum += 25d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atNaturalLogarithm(de.uka.ipd.sdq.beagle.core.evaluableexpressions. * NaturalLogarithmExpression) */ @Override protected void atNaturalLogarithm(final NaturalLogarithmExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 26.54729466718568d; this.humanComprehensibilityComplexitySum += 17d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atSine(de .uka.ipd.sdq.beagle.core.evaluableexpressions.SineExpression) */ @Override protected void atSine(final SineExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 205.03680743897714d; this.humanComprehensibilityComplexitySum += 15d; // CHECKSTYLE:ON } /* * (non-Javadoc) * * @see de.uka.ipd.sdq.beagle.core.evaluableexpressions.util.ExpressionTreeWalker# * atSubstraction(de.uka.ipd.sdq.beagle.core.evaluableexpressions. * SubtractionExpression) */ @Override protected void atSubtraction(final SubtractionExpression expression) { // CHECKSTYLE:OFF this.computationalComplexitySum += 1d; this.humanComprehensibilityComplexitySum += 1.2d; // CHECKSTYLE:ON } } }
epl-1.0
uppaal-emf/uppaal
requirements/org.muml.uppaal.requirements.edit/src/org/muml/uppaal/requirements/provider/UnaryPropertyItemProvider.java
9536
/** */ package org.muml.uppaal.requirements.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; import org.muml.uppaal.expressions.ExpressionsFactory; import org.muml.uppaal.requirements.RequirementsFactory; import org.muml.uppaal.requirements.RequirementsPackage; import org.muml.uppaal.requirements.UnaryProperty; /** * This is the item provider adapter for a {@link org.muml.uppaal.requirements.UnaryProperty} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class UnaryPropertyItemProvider extends PropertyItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public UnaryPropertyItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addQuantifierPropertyDescriptor(object); addOperatorPropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Quantifier feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addQuantifierPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_UnaryProperty_quantifier_feature"), getString("_UI_PropertyDescriptor_description", "_UI_UnaryProperty_quantifier_feature", "_UI_UnaryProperty_type"), RequirementsPackage.Literals.UNARY_PROPERTY__QUANTIFIER, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Operator feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addOperatorPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_UnaryProperty_operator_feature"), getString("_UI_PropertyDescriptor_description", "_UI_UnaryProperty_operator_feature", "_UI_UnaryProperty_type"), RequirementsPackage.Literals.UNARY_PROPERTY__OPERATOR, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns UnaryProperty.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/UnaryProperty")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((UnaryProperty)object).getComment(); return label == null || label.length() == 0 ? getString("_UI_UnaryProperty_type") : getString("_UI_UnaryProperty_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(UnaryProperty.class)) { case RequirementsPackage.UNARY_PROPERTY__QUANTIFIER: case RequirementsPackage.UNARY_PROPERTY__OPERATOR: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case RequirementsPackage.UNARY_PROPERTY__EXPRESSION: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, RequirementsFactory.eINSTANCE.createDeadlockExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createNegationExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createPlusExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createMinusExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createAssignmentExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createIdentifierExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createLiteralExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createArithmeticExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createLogicalExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createFunctionCallExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createCompareExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createConditionExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createScopedIdentifierExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createQuantificationExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createIncrementDecrementExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createBitShiftExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createMinMaxExpression())); newChildDescriptors.add (createChildParameter (RequirementsPackage.Literals.UNARY_PROPERTY__EXPRESSION, ExpressionsFactory.eINSTANCE.createBitwiseExpression())); } }
epl-1.0
SENSIDL-PROJECT/SensIDL
bundles/de.fzi.sensidl.language.ui/src/de/fzi/sensidl/language/ui/wizard/SensidlWizardPage.java
11909
package de.fzi.sensidl.language.ui.wizard; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ContainerSelectionDialog; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; /** * The Sensidl Wizard page which shows the settings * * @author Sven Eckhardt * */ public class SensidlWizardPage extends WizardPage { private boolean vortoTransformation; /** * contains all generation languages that are shown in the generation * wizard. The languages are: <code>Java</code>, * <code>Java Plug-in Project</code>, <code>JavaScript</code>, * <code>C</code>, <code>C#</code> and <code>All</code> */ public static final String[] GENERATION_LANGUAGES_STRINGS = new String[] { "Java", "Java Plug-in Project", "JavaScript", "C", "C#", "OPC UA", "All" }; // first row Elements private Label label_ModelPath; private Button button_FileSystemModelPath; private Button button_WorkspaceModelPath; private Text textfield_ModelPath; private String text_ModelPath; // second row Elements private Label label_Path; private Label label_JavaProjectPathInfomation; private Button button_FileSystemPath; private Button button_WorkspacePath; private Text textfield_Path; private String text_Path; // // third row Elements private Combo combo_language; private String text_language; /** * Constructor * * @param pageName * the name of the page * @param title * the title of the page * @param titleImage * the titleImage of the page * @param modelPath * the path for the model path text field * @param path * the path for the path text field * @param language * the generation language */ protected SensidlWizardPage(String pageName, String title, ImageDescriptor titleImage, String modelPath, String path, String language, boolean vortoTransformation) { super(pageName, title, titleImage); this.text_ModelPath = modelPath; this.text_Path = path; this.text_language = language; this.vortoTransformation = vortoTransformation; } @Override public void performHelp() { // PlatformUI.getWorkbench().getHelpSystem().displayHelp("de.fzi.sensidl.help.sensidl_wizard_help_documentation"); } @Override public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); FormLayout formLayout = new FormLayout(); formLayout.marginHeight = 10; formLayout.marginWidth = 10; composite.setLayout(formLayout); // first row button_FileSystemModelPath = new Button(composite, SWT.PUSH); button_FileSystemModelPath.setText("File System..."); FormData position3_1 = new FormData(); position3_1.top = new FormAttachment(0, 0); position3_1.right = new FormAttachment(100, 0); button_FileSystemModelPath.setLayoutData(position3_1); if (vortoTransformation) { button_FileSystemModelPath.setEnabled(false); } button_WorkspaceModelPath = new Button(composite, SWT.PUSH); button_WorkspaceModelPath.setText("Workspace..."); FormData position3_2 = new FormData(); position3_2.top = new FormAttachment(0, 0); position3_2.right = new FormAttachment(button_FileSystemModelPath, -5); button_WorkspaceModelPath.setLayoutData(position3_2); if (vortoTransformation) { button_WorkspaceModelPath.setEnabled(false); } label_ModelPath = new Label(composite, SWT.READ_ONLY); label_ModelPath.setText("Model: "); FormData position1 = new FormData(); position1.left = new FormAttachment(0, 0); position1.top = new FormAttachment(0, 5); label_ModelPath.setLayoutData(position1); if (vortoTransformation) { label_ModelPath.setEnabled(false); } textfield_ModelPath = new Text(composite, SWT.SINGLE); textfield_ModelPath.setText(text_ModelPath); FormData position2 = new FormData(); position2.left = new FormAttachment(label_ModelPath, 10); position2.top = new FormAttachment(0, 5); position2.right = new FormAttachment(button_WorkspaceModelPath, -5); textfield_ModelPath.setLayoutData(position2); if (vortoTransformation) { textfield_ModelPath.setEnabled(false); } button_FileSystemModelPath.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(new Shell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.sidl" }); // set the workspace directory as default: dialog.setFilterPath(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString()); textfield_ModelPath.setText(dialog.open().replaceAll("\\\\", "/")); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); button_WorkspaceModelPath.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(new Shell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider()); dialog.setInput(ResourcesPlugin.getWorkspace().getRoot()); dialog.setAllowMultiple(false); dialog.setDoubleClickSelects(true); if (dialog.open() == ElementTreeSelectionDialog.OK) { IResource resource = (IResource) dialog.getFirstResult(); textfield_ModelPath.setText("platform:/resource" + resource.getFullPath().toString()); } } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); // second row button_FileSystemPath = new Button(composite, SWT.PUSH); button_FileSystemPath.setText("File System..."); FormData position6_1 = new FormData(); position6_1.top = new FormAttachment(button_FileSystemModelPath, 10); position6_1.right = new FormAttachment(100, 0); button_FileSystemPath.setLayoutData(position6_1); button_WorkspacePath = new Button(composite, SWT.PUSH); button_WorkspacePath.setText("Workspace..."); FormData position6_2 = new FormData(); position6_2.top = new FormAttachment(button_WorkspaceModelPath, 10); position6_2.right = new FormAttachment(button_FileSystemPath, -5); button_WorkspacePath.setLayoutData(position6_2); label_Path = new Label(composite, SWT.READ_ONLY); label_Path.setText("Path: "); FormData position4 = new FormData(); position4.left = new FormAttachment(0, 0); position4.top = new FormAttachment(button_FileSystemModelPath, 15); label_Path.setLayoutData(position4); textfield_Path = new Text(composite, SWT.SINGLE); textfield_Path.setText(text_Path); FormData position5 = new FormData(); position5.left = new FormAttachment(label_ModelPath, 10); position5.top = new FormAttachment(button_FileSystemModelPath, 15); position5.right = new FormAttachment(button_WorkspacePath, -5); textfield_Path.setLayoutData(position5); textfield_Path.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (combo_language.getText().equals(GENERATION_LANGUAGES_STRINGS[1])) { if (textfield_Path.getText().startsWith("platform:/resource/")) { if (textfield_Path.getText().replace("platform:/resource/", "").contains("/")) { setPageComplete(false); label_JavaProjectPathInfomation.setVisible(true); } else { setPageComplete(true); label_JavaProjectPathInfomation.setVisible(false); } } else { setPageComplete(false); label_JavaProjectPathInfomation.setVisible(true); } } else { setPageComplete(true); label_JavaProjectPathInfomation.setVisible(false); } } }); button_FileSystemPath.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { DirectoryDialog dialog = new DirectoryDialog(new Shell(), SWT.OPEN); // set the workspace directory as default: dialog.setFilterPath(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString()); textfield_Path.setText(dialog.open().replaceAll("\\\\", "/")); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); button_WorkspacePath.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { ContainerSelectionDialog dialog = new ContainerSelectionDialog(new Shell(), ResourcesPlugin.getWorkspace().getRoot(), true, "Select Destination"); if (dialog.open() == ContainerSelectionDialog.OK) { Path path = (Path) dialog.getResult()[0]; textfield_Path.setText("platform:/resource" + path.toString()); } } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); // third row combo_language = new Combo(composite, SWT.READ_ONLY); combo_language.setItems(GENERATION_LANGUAGES_STRINGS); combo_language.setText(text_language); FormData position8 = new FormData(); position8.left = new FormAttachment(0, 0); position8.top = new FormAttachment(button_WorkspacePath, 10); position8.right = new FormAttachment(100, 0); combo_language.setLayoutData(position8); combo_language.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (combo_language.getText().equals(GENERATION_LANGUAGES_STRINGS[1])) { button_FileSystemPath.setEnabled(false); } else { button_FileSystemPath.setEnabled(true); setPageComplete(true); label_JavaProjectPathInfomation.setVisible(false); } } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); if (combo_language.getText().equals(GENERATION_LANGUAGES_STRINGS[1])) { button_FileSystemPath.setEnabled(false); } else { button_FileSystemPath.setEnabled(true); } label_JavaProjectPathInfomation = new Label(composite, SWT.READ_ONLY); label_JavaProjectPathInfomation .setText("Warning: the Java Project has to be at the root of the current workspace"); FormData position9 = new FormData(); position9.top = new FormAttachment(combo_language, 10); label_JavaProjectPathInfomation.setLayoutData(position9); label_JavaProjectPathInfomation.setVisible(false); setControl(composite); } /** * * @return the text of the model path text field */ public String getTextModelPath() { return textfield_ModelPath.getText(); } /** * * @return the text of the path text field */ public String getTextPath() { return textfield_Path.getText(); } /** * * @return the generation language */ public String getLanguage() { return combo_language.getText(); } }
epl-1.0
sschafer/atomic
org.allmyinfo.meaning.impl.date/src/org/allmyinfo/meaning/impl/date/PubDateMeaningImpl.java
627
package org.allmyinfo.meaning.impl.date; import org.allmyinfo.coordinator.Coordinator; import org.allmyinfo.meaning.date.PubDateMeaning; import org.allmyinfo.nature.basic.DateNature; import org.allmyinfo.nodes.NodeId; import org.eclipse.jdt.annotation.NonNull; public class PubDateMeaningImpl extends DateMeaningImpl implements PubDateMeaning { public static final @NonNull String NAME = "org.allmyinfo.pubdate"; PubDateMeaningImpl(final @NonNull NodeId nodeId, final DateNature.@NonNull Reactor natureReactor, // final Coordinator.@NonNull Reactor coordReactor) { super(nodeId, natureReactor, coordReactor); } }
epl-1.0
opendaylight/yangtools
model/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/stmt/GroupingEffectiveStatement.java
850
/* * Copyright (c) 2017 Pantheon Technologies, 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.yangtools.yang.model.api.stmt; import com.google.common.annotations.Beta; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.YangStmtMapping; import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition; @Beta public interface GroupingEffectiveStatement extends DataTreeAwareEffectiveStatement<QName, GroupingStatement> { @Override default StatementDefinition statementDefinition() { return YangStmtMapping.GROUPING; } }
epl-1.0
debrief/debrief
info.limpet.stackedcharts.model/src/info/limpet/stackedcharts/model/impl/AbstractAnnotationImpl.java
7811
/******************************************************************************* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2020, Deep Blue C Technology Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *******************************************************************************/ /** */ package info.limpet.stackedcharts.model.impl; import java.awt.Color; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import info.limpet.stackedcharts.model.AbstractAnnotation; import info.limpet.stackedcharts.model.StackedchartsPackage; /** * <!-- begin-user-doc --> An implementation of the model object * '<em><b>Abstract Annotation</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link info.limpet.stackedcharts.model.impl.AbstractAnnotationImpl#getName * <em>Name</em>}</li> * <li>{@link info.limpet.stackedcharts.model.impl.AbstractAnnotationImpl#getColor * <em>Color</em>}</li> * <li>{@link info.limpet.stackedcharts.model.impl.AbstractAnnotationImpl#isIncludeInLegend * <em>Include In Legend</em>}</li> * </ul> * * @generated */ public abstract class AbstractAnnotationImpl extends MinimalEObjectImpl.Container implements AbstractAnnotation { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The default value of the '{@link #getColor() <em>Color</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getColor() * @generated * @ordered */ protected static final Color COLOR_EDEFAULT = null; /** * The default value of the '{@link #isIncludeInLegend() <em>Include In * Legend</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #isIncludeInLegend() * @generated * @ordered */ protected static final boolean INCLUDE_IN_LEGEND_EDEFAULT = true; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getColor() <em>Color</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getColor() * @generated * @ordered */ protected Color color = COLOR_EDEFAULT; /** * The cached value of the '{@link #isIncludeInLegend() <em>Include In * Legend</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #isIncludeInLegend() * @generated * @ordered */ protected boolean includeInLegend = INCLUDE_IN_LEGEND_EDEFAULT; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ protected AbstractAnnotationImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public Object eGet(final int featureID, final boolean resolve, final boolean coreType) { switch (featureID) { case StackedchartsPackage.ABSTRACT_ANNOTATION__NAME: return getName(); case StackedchartsPackage.ABSTRACT_ANNOTATION__COLOR: return getColor(); case StackedchartsPackage.ABSTRACT_ANNOTATION__INCLUDE_IN_LEGEND: return isIncludeInLegend(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(final int featureID) { switch (featureID) { case StackedchartsPackage.ABSTRACT_ANNOTATION__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case StackedchartsPackage.ABSTRACT_ANNOTATION__COLOR: return COLOR_EDEFAULT == null ? color != null : !COLOR_EDEFAULT.equals(color); case StackedchartsPackage.ABSTRACT_ANNOTATION__INCLUDE_IN_LEGEND: return includeInLegend != INCLUDE_IN_LEGEND_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eSet(final int featureID, final Object newValue) { switch (featureID) { case StackedchartsPackage.ABSTRACT_ANNOTATION__NAME: setName((String) newValue); return; case StackedchartsPackage.ABSTRACT_ANNOTATION__COLOR: setColor((Color) newValue); return; case StackedchartsPackage.ABSTRACT_ANNOTATION__INCLUDE_IN_LEGEND: setIncludeInLegend((Boolean) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return StackedchartsPackage.Literals.ABSTRACT_ANNOTATION; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eUnset(final int featureID) { switch (featureID) { case StackedchartsPackage.ABSTRACT_ANNOTATION__NAME: setName(NAME_EDEFAULT); return; case StackedchartsPackage.ABSTRACT_ANNOTATION__COLOR: setColor(COLOR_EDEFAULT); return; case StackedchartsPackage.ABSTRACT_ANNOTATION__INCLUDE_IN_LEGEND: setIncludeInLegend(INCLUDE_IN_LEGEND_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public Color getColor() { return color; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public String getName() { return name; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public boolean isIncludeInLegend() { return includeInLegend; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void setColor(final Color newColor) { final Color oldColor = color; color = newColor; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, StackedchartsPackage.ABSTRACT_ANNOTATION__COLOR, oldColor, color)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void setIncludeInLegend(final boolean newIncludeInLegend) { final boolean oldIncludeInLegend = includeInLegend; includeInLegend = newIncludeInLegend; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, StackedchartsPackage.ABSTRACT_ANNOTATION__INCLUDE_IN_LEGEND, oldIncludeInLegend, includeInLegend)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void setName(final String newName) { final String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, StackedchartsPackage.ABSTRACT_ANNOTATION__NAME, oldName, name)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); final StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); result.append(name); result.append(", color: "); result.append(color); result.append(", includeInLegend: "); result.append(includeInLegend); result.append(')'); return result.toString(); } } // AbstractAnnotationImpl
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.core/src/org/eclipse/jdt/core/compiler/CompilationParticipant.java
6149
/******************************************************************************* * Copyright (c) 2005, 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * mkaufman@bea.com - initial API as ICompilationParticipant * IBM - changed from interface ICompilationParticipant to abstract class CompilationParticipant * IBM - rewrote specification * *******************************************************************************/ package org.eclipse.jdt.core.compiler; import org.eclipse.jdt.core.IJavaProject; /** * A compilation participant is notified of events occurring during the compilation process. * The compilation process not only involves generating .class files (i.e. building), it also involves * cleaning the output directory, reconciling a working copy, etc. * So the notified events are the result of a build action, a clean action, a reconcile operation * (for a working copy), etc. * <p> * Code that participates in the build should in general be implemented with a separate Builder, * rather than a CompilationParticipant. It is only necessary to use a CompilationParticipant if * the build step needs to interact with the Java build, for instance by creating additional * Java source files that must themselves in turn be compiled. * <p> * Clients wishing to participate in the compilation process must subclass this class, and implement * {@link #isActive(IJavaProject)}, {@link #aboutToBuild(IJavaProject)}, * {@link #reconcile(ReconcileContext)}, etc. * </p><p> * This class is intended to be subclassed by clients. * </p> * @since 3.2 */ public abstract class CompilationParticipant { public final static int READY_FOR_BUILD = 1; public final static int NEEDS_FULL_BUILD = 2; /** * Notifies this participant that a build is about to start and provides it the opportunity to * create missing source folders for generated source files. Additional source folders * should be marked as optional so the project can be built when the folders do not exist. * Only sent to participants interested in the project. * <p> * Default is to return <code>READY_FOR_BUILD</code>. * </p> * @see #buildFinished(IJavaProject project) * @param project the project about to build * @return READY_FOR_BUILD or NEEDS_FULL_BUILD */ public int aboutToBuild(IJavaProject project) { return READY_FOR_BUILD; } /** * Notifies this participant that a build has finished for the project. * This will be sent, even if buildStarting() was not sent when no source files needed to be compiled * or the build failed. * Only sent to participants interested in the project. * @param project the project about to build * @since 3.4 */ public void buildFinished(IJavaProject project) { // do nothing by default } /** * Notifies this participant that a compile operation is about to start and provides it the opportunity to * generate source files based on the source files about to be compiled. * When isBatchBuild is true, then files contains all source files in the project. * Only sent to participants interested in the current build project. * * @param files is an array of BuildContext * @param isBatch identifies when the build is a batch build */ public void buildStarting(BuildContext[] files, boolean isBatch) { // do nothing by default } /** * Notifies this participant that a clean is about to start and provides it the opportunity to * delete generated source files. * Only sent to participants interested in the project. * @param project the project about to be cleaned */ public void cleanStarting(IJavaProject project) { // do nothing by default } /** * Returns whether this participant is active for a given project. * <p> * Default is to return <code>false</code>. * </p><p> * For efficiency, participants that are not interested in the * given project should return <code>false</code> for that project. * </p><p> * Note: In {@link org.eclipse.jdt.core.WorkingCopyOwner#newWorkingCopy(String, org.eclipse.jdt.core.IClasspathEntry[], org.eclipse.core.runtime.IProgressMonitor) * special cases}, the project may be closed and not exist. Participants typically return false when the * underlying project is closed. I.e. when the following check returns false: * <pre> * javaProject.getProject().isOpen(); * </pre> * </p> * @param project the project to participate in * @return whether this participant is active for a given project */ public boolean isActive(IJavaProject project) { return false; } /** * Returns whether this participant is interested in Annotations. * <p> * Returning <code>true</code> enables the callback {@link #processAnnotations(BuildContext[])}, where this * participant can influence build results. * </p> * <p> * Default is to return <code>false</code>. * </p> * * @return whether this participant is interested in Annotations */ public boolean isAnnotationProcessor() { return false; } /** * Notifies this participant that a compile operation has found source files using Annotations. * Only sent to participants interested in the current build project that answer true to {@link #isAnnotationProcessor()}. * Each BuildContext was informed whether its source file currently hasAnnotations(). * * @param files is an array of BuildContext */ public void processAnnotations(BuildContext[] files) { // do nothing by default } /** * Notifies this participant that a reconcile operation is happening. The participant can act on this reconcile * operation by using the given context. Other participant can then see the result of this participation * on this context. * <p> * Note that a participant should not modify the buffer of the working copy that is being reconciled. * </p><p> * Default is to do nothing. * </p> * @param context the reconcile context to act on */ public void reconcile(ReconcileContext context) { // do nothing by default } }
epl-1.0
LM25TTD/HopperIDE
Eclipse_Plugin/org.hopper.language.parent/org.hopper.language/src-gen/org/hopper/language/portugol/impl/StringLiteralImpl.java
3734
/** * generated by Xtext 2.9.0 */ package org.hopper.language.portugol.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.hopper.language.portugol.PortugolPackage; import org.hopper.language.portugol.StringLiteral; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>String Literal</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.hopper.language.portugol.impl.StringLiteralImpl#getValue <em>Value</em>}</li> * </ul> * * @generated */ public class StringLiteralImpl extends ExpressionImpl implements StringLiteral { /** * The default value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected static final String VALUE_EDEFAULT = null; /** * The cached value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected String value = VALUE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected StringLiteralImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return PortugolPackage.Literals.STRING_LITERAL; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setValue(String newValue) { String oldValue = value; value = newValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, PortugolPackage.STRING_LITERAL__VALUE, oldValue, value)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case PortugolPackage.STRING_LITERAL__VALUE: return getValue(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case PortugolPackage.STRING_LITERAL__VALUE: setValue((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case PortugolPackage.STRING_LITERAL__VALUE: setValue(VALUE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case PortugolPackage.STRING_LITERAL__VALUE: return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (value: "); result.append(value); result.append(')'); return result.toString(); } } //StringLiteralImpl
epl-1.0
happyspace/goclipse
plugin_ide.ui/src-lang/melnorme/lang/ide/ui/text/AbstractLangSourceViewerConfiguration.java
12530
/******************************************************************************* * Copyright (c) 2015 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.lang.ide.ui.text; import static melnorme.utilbox.core.Assert.AssertNamespace.assertUnreachable; import static melnorme.utilbox.core.CoreUtil.array; import static melnorme.utilbox.core.CoreUtil.tryCast; import java.util.Map; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.AbstractInformationControlManager; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.IAutoEditStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.information.IInformationPresenter; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.reconciler.AbstractReconciler; import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationHover; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.texteditor.ITextEditor; import _org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy; import _org.eclipse.jdt.internal.ui.text.HTMLAnnotationHover; import melnorme.lang.ide.core.text.format.AutoEditUtils; import melnorme.lang.ide.core.text.format.FormatterIndentMode; import melnorme.lang.ide.ui.CodeFormatterConstants; import melnorme.lang.ide.ui.EditorSettings_Actual; import melnorme.lang.ide.ui.LangUIPlugin; import melnorme.lang.ide.ui.LangUIPlugin_Actual; import melnorme.lang.ide.ui.editor.AbstractLangEditor; import melnorme.lang.ide.ui.editor.LangSourceViewer; import melnorme.lang.ide.ui.editor.ProjectionViewerExt; import melnorme.lang.ide.ui.editor.hover.BestMatchHover; import melnorme.lang.ide.ui.editor.structure.AbstractLangStructureEditor; import melnorme.lang.ide.ui.editor.structure.LangOutlineInformationControl.OutlineInformationControlCreator; import melnorme.lang.ide.ui.editor.structure.StructureElementInformationProvider; import melnorme.lang.ide.ui.editor.text.LangReconciler; import melnorme.lang.ide.ui.text.coloring.StylingPreferences; import melnorme.lang.ide.ui.text.completion.CompletionProposalsGrouping; import melnorme.lang.ide.ui.text.completion.ContentAssistantExt; import melnorme.lang.ide.ui.text.completion.LangContentAssistProcessor; import melnorme.lang.ide.ui.text.completion.LangContentAssistProcessor.ContentAssistCategoriesBuilder; import melnorme.util.swt.jface.text.ColorManager2; import melnorme.utilbox.collections.Indexable; public abstract class AbstractLangSourceViewerConfiguration extends AbstractSimpleLangSourceViewerConfiguration { protected final AbstractLangStructureEditor editor; public AbstractLangSourceViewerConfiguration(IPreferenceStore preferenceStore, ColorManager2 colorManager, StylingPreferences stylingPrefs, AbstractLangStructureEditor editor) { super(preferenceStore, colorManager, stylingPrefs); this.editor = editor; } public AbstractLangStructureEditor getEditor() { return editor; } public AbstractLangEditor getEditor_asLang() { return tryCast(editor, AbstractLangEditor.class); } /* ----------------- Hovers ----------------- */ @Override public final ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } @Override public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) { return new BestMatchHover(getEditor()); } @Override public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { return new HTMLAnnotationHover(false) { @Override protected boolean isIncluded(Annotation annotation) { return isShowInVerticalRuler(annotation); } }; } @Override public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) { return new HTMLAnnotationHover(true) { @Override protected boolean isIncluded(Annotation annotation) { return isShowInOverviewRuler(annotation); } }; } @Override public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) { InformationPresenter presenter = new InformationPresenter(getInformationPresenterControlCreator(sourceViewer)); presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); // Register information providers for (String contentType : getConfiguredContentTypes(sourceViewer)) { presenter.setInformationProvider(getInformationProvider(contentType), contentType); } presenter.setSizeConstraints(100, 12, false, true); return presenter; } protected abstract IInformationProvider getInformationProvider(String contentType); protected IInformationControlCreator getInformationPresenterControlCreator( @SuppressWarnings("unused") ISourceViewer sourceViewer) { return new IInformationControlCreator() { @Override public IInformationControl createInformationControl(Shell parent) { return new DefaultInformationControl(parent, true); } }; } /* ----------------- Navigation operations ----------------- */ @Override protected Map<String, ITextEditor> getHyperlinkDetectorTargets(ISourceViewer sourceViewer) { Map<String, ITextEditor> targets = super.getHyperlinkDetectorTargets(sourceViewer); targets.put(EditorSettings_Actual.EDITOR_CODE_TARGET, editor); return targets; } public void installOutlinePresenter(final LangSourceViewer sourceViewer) { final InformationPresenter presenter = new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer)); presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL); IInformationProvider provider = new StructureElementInformationProvider(getEditor()); for(String contentType : getConfiguredContentTypes(sourceViewer)) { presenter.setInformationProvider(provider, contentType); } presenter.setSizeConstraints(50, 20, true, false); presenter.install(sourceViewer); sourceViewer.setOutlinePresenter(presenter); } protected IInformationControlCreator getOutlinePresenterControlCreator( @SuppressWarnings("unused") ISourceViewer sourceViewer) { return new OutlineInformationControlCreator(this); } /* ----------------- Modification operations ----------------- */ @Override public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) { return new String[] { getToggleCommentPrefix(), "" }; } protected abstract String getToggleCommentPrefix(); @Override public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) { if(IDocument.DEFAULT_CONTENT_TYPE.equals(contentType)) { return array(LangUIPlugin_Actual.createAutoEditStrategy(sourceViewer, contentType)); } else { return super.getAutoEditStrategies(sourceViewer, contentType); } } @Override public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) { FormatterIndentMode indentMode = CodeFormatterConstants.fromPrefStore(); int spaceIndentationSize = CodeFormatterConstants.FORMATTER_INDENTATION_SPACES_SIZE.get(); String spaceIndent = AutoEditUtils.getNSpaces(spaceIndentationSize); // An empty string must be part of IndentPrefixes, so that empty lines do not fail the unindent operation. // for indent operation, only first element will be used, I believe switch (indentMode) { case TAB: return array("\t", spaceIndent, ""); // return getIndentPrefixesForTab(spaceIndent); case SPACES: return array(spaceIndent, "\t", ""); // return getIndentPrefixesForSpaces(spaceIndent); } throw assertUnreachable(); } @Override protected void updateIndentationSettings(SourceViewer sourceViewer, String property) { super.updateIndentationSettings(sourceViewer, property); if( CodeFormatterConstants.FORMATTER_INDENTATION_SPACES_SIZE.key.equals(property) || CodeFormatterConstants.FORMATTER_INDENT_MODE.key.equals(property)) { for(String contentType : getConfiguredContentTypes(sourceViewer)) { String[] prefixes= getIndentPrefixes(sourceViewer, contentType); sourceViewer.setIndentPrefixes(prefixes, contentType); } } } /* ----------------- Content Assist ----------------- */ @Override public ContentAssistant getContentAssistant(ISourceViewer sourceViewer) { AbstractLangEditor editor = getEditor_asLang(); if(editor != null) { ContentAssistantExt assistant = createContentAssitant(); assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); assistant.setRestoreCompletionProposalSize(LangUIPlugin.getDialogSettings("completion_proposal_size")); assistant.setInformationControlCreator( getInformationControl_ContentAsssist(getAdditionalInfoAffordanceString())); assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); assistant.enableColoredLabels(true); configureContentAssistantProcessors(assistant); // Note: configuration must come after processors are created assistant.configure(fPreferenceStore, editor.getSourceViewer_()); return assistant; } return null; } protected ContentAssistantExt createContentAssitant() { return new ContentAssistantExt(getPreferenceStore()); } protected void configureContentAssistantProcessors(ContentAssistant assistant) { Indexable<CompletionProposalsGrouping> categories = getContentAssistCategoriesProvider().getCategories(); IContentAssistProcessor cap = createContentAssistProcessor(assistant, categories); assistant.setContentAssistProcessor(cap, IDocument.DEFAULT_CONTENT_TYPE); } protected LangContentAssistProcessor createContentAssistProcessor(ContentAssistant assistant, Indexable<CompletionProposalsGrouping> categories) { return new LangContentAssistProcessor(assistant, getEditor(), categories); } protected abstract ContentAssistCategoriesBuilder getContentAssistCategoriesProvider(); /* ----------------- reconciler ----------------- */ @Override public IReconciler getReconciler(ISourceViewer sourceViewer) { ITextEditor editor = getEditor(); if(editor != null && editor.isEditable()) { AbstractReconciler reconciler = doCreateReconciler(editor); reconciler.setIsAllowedToModifyDocument(false); reconciler.setDelay(500); // Can't use zero return reconciler; } return null; } protected LangReconciler doCreateReconciler(ITextEditor editor) { CompositeReconcilingStrategy strategy = getReconciler_createCompositeStrategy(editor); return new LangReconciler(strategy, false, editor); } @SuppressWarnings("unused") protected CompositeReconcilingStrategy getReconciler_createCompositeStrategy(ITextEditor editor) { return new CompositeReconcilingStrategy(); } /* ----------------- ----------------- */ @Override public void configureViewer(ProjectionViewerExt sourceViewer) { super.configureViewer(sourceViewer); if(sourceViewer instanceof LangSourceViewer) { LangSourceViewer langSourceViewer = (LangSourceViewer) sourceViewer; installOutlinePresenter(langSourceViewer); } } }
epl-1.0
gnodet/wikitext
org.eclipse.mylyn.wikitext.twiki.core/src/org/eclipse/mylyn/internal/wikitext/twiki/core/token/IconReplacementToken.java
1804
/******************************************************************************* * Copyright (c) 2007, 2008 David Green 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: * David Green - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.wikitext.twiki.core.token; import org.eclipse.mylyn.wikitext.core.parser.ImageAttributes; import org.eclipse.mylyn.wikitext.core.parser.markup.PatternBasedElement; import org.eclipse.mylyn.wikitext.core.parser.markup.PatternBasedElementProcessor; import org.eclipse.mylyn.wikitext.twiki.core.TWikiLanguage; /** * Token that replaces <code>%ICON{"<icon type>"}%</code> with the appropriate image tag. * Supports %ICON{"help"}%, %ICON{"tip"}%, and %ICON{"warning"}% * * @author David Green */ public class IconReplacementToken extends PatternBasedElement { // TODO: check http://twiki.org/cgi-bin/view/TWiki04x02/TWikiDocGraphics to see if this covers all graphics @Override protected String getPattern(int groupOffset) { return "%ICON\\{\"([a-zA-Z]+)\"\\}%"; //$NON-NLS-1$ } @Override protected int getPatternGroupCount() { return 1; } @Override protected PatternBasedElementProcessor newProcessor() { return new IconProcessor(); } private static class IconProcessor extends PatternBasedElementProcessor { @Override public void emit() { String iconType = group(1); String iconUrl = ((TWikiLanguage)markupLanguage).toIconUrl(iconType); builder.image(new ImageAttributes(), iconUrl); } } }
epl-1.0
bradsdavis/cxml-api
src/main/java/org/cxml/v12028/TaxAmount.java
1282
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-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.09.23 at 10:57:51 AM CEST // package org.cxml.v12028; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "money" }) @XmlRootElement(name = "TaxAmount") public class TaxAmount { @XmlElement(name = "Money", required = true) protected Money money; /** * Gets the value of the money property. * * @return * possible object is * {@link Money } * */ public Money getMoney() { return money; } /** * Sets the value of the money property. * * @param value * allowed object is * {@link Money } * */ public void setMoney(Money value) { this.money = value; } }
epl-1.0
nlepine/M2Doc
plugins/org.obeonetwork.m2doc/src-gen/org/obeonetwork/m2doc/template/impl/QueryImpl.java
6718
/******************************************************************************* * Copyright (c) 2016 Obeo. * 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: * Obeo - initial API and implementation * *******************************************************************************/ /** */ package org.obeonetwork.m2doc.template.impl; import org.eclipse.acceleo.query.runtime.IQueryBuilderEngine.AstResult; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.obeonetwork.m2doc.template.Query; import org.obeonetwork.m2doc.template.QueryBehavior; import org.obeonetwork.m2doc.template.TemplatePackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Query</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.obeonetwork.m2doc.template.impl.QueryImpl#getBehavior <em>Behavior</em>}</li> * <li>{@link org.obeonetwork.m2doc.template.impl.QueryImpl#getQuery <em>Query</em>}</li> * </ul> * * @generated */ public class QueryImpl extends AbstractConstructImpl implements Query { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final String copyright = " Copyright (c) 2016 Obeo. \r\n All rights reserved. This program and the accompanying materials\r\n are made available under the terms of the Eclipse Public License v1.0\r\n which accompanies this distribution, and is available at\r\n http://www.eclipse.org/legal/epl-v10.html\r\n \r\n Contributors:\r\n Obeo - initial API and implementation"; /** * The default value of the '{@link #getBehavior() <em>Behavior</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBehavior() * @generated * @ordered */ protected static final QueryBehavior BEHAVIOR_EDEFAULT = QueryBehavior.TEXT; /** * The cached value of the '{@link #getBehavior() <em>Behavior</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBehavior() * @generated * @ordered */ protected QueryBehavior behavior = BEHAVIOR_EDEFAULT; /** * The default value of the '{@link #getQuery() <em>Query</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getQuery() * @generated * @ordered */ protected static final AstResult QUERY_EDEFAULT = null; /** * The cached value of the '{@link #getQuery() <em>Query</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getQuery() * @generated * @ordered */ protected AstResult query = QUERY_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected QueryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TemplatePackage.Literals.QUERY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AstResult getQuery() { return query; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setQuery(AstResult newQuery) { AstResult oldQuery = query; query = newQuery; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TemplatePackage.QUERY__QUERY, oldQuery, query)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public QueryBehavior getBehavior() { return behavior; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBehavior(QueryBehavior newBehavior) { QueryBehavior oldBehavior = behavior; behavior = newBehavior == null ? BEHAVIOR_EDEFAULT : newBehavior; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TemplatePackage.QUERY__BEHAVIOR, oldBehavior, behavior)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TemplatePackage.QUERY__BEHAVIOR: return getBehavior(); case TemplatePackage.QUERY__QUERY: return getQuery(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TemplatePackage.QUERY__BEHAVIOR: setBehavior((QueryBehavior)newValue); return; case TemplatePackage.QUERY__QUERY: setQuery((AstResult)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case TemplatePackage.QUERY__BEHAVIOR: setBehavior(BEHAVIOR_EDEFAULT); return; case TemplatePackage.QUERY__QUERY: setQuery(QUERY_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case TemplatePackage.QUERY__BEHAVIOR: return behavior != BEHAVIOR_EDEFAULT; case TemplatePackage.QUERY__QUERY: return QUERY_EDEFAULT == null ? query != null : !QUERY_EDEFAULT.equals(query); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (behavior: "); result.append(behavior); result.append(", query: "); result.append(query); result.append(')'); return result.toString(); } } //QueryImpl
epl-1.0
parraman/micobs
common/es.uah.aut.srg.micobs.editor.pdl.ui/src-gen/es/uah/aut/srg/micobs/lang/ui/internal/PDLActivator.java
3175
/******************************************************************************* * Copyright (c) 2013-2015 UAH Space Research Group. * 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: * MICOBS SRG Team - Initial API and implementation ******************************************************************************/ package es.uah.aut.srg.micobs.lang.ui.internal; import java.util.Collections; import java.util.Map; import org.apache.log4j.Logger; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.xtext.ui.shared.SharedStateModule; import org.eclipse.xtext.util.Modules2; import org.osgi.framework.BundleContext; import com.google.common.collect.Maps; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; /** * This class was generated. Customizations should only happen in a newly * introduced subclass. */ public class PDLActivator extends AbstractUIPlugin { public static final String ES_UAH_AUT_SRG_MICOBS_LANG_PDL = "es.uah.aut.srg.micobs.lang.PDL"; private static final Logger logger = Logger.getLogger(PDLActivator.class); private static PDLActivator INSTANCE; private Map<String, Injector> injectors = Collections.synchronizedMap(Maps.<String, Injector> newHashMapWithExpectedSize(1)); @Override public void start(BundleContext context) throws Exception { super.start(context); INSTANCE = this; } @Override public void stop(BundleContext context) throws Exception { injectors.clear(); INSTANCE = null; super.stop(context); } public static PDLActivator getInstance() { return INSTANCE; } public Injector getInjector(String language) { synchronized (injectors) { Injector injector = injectors.get(language); if (injector == null) { injectors.put(language, injector = createInjector(language)); } return injector; } } protected Injector createInjector(String language) { try { Module runtimeModule = getRuntimeModule(language); Module sharedStateModule = getSharedStateModule(); Module uiModule = getUiModule(language); Module mergedModule = Modules2.mixin(runtimeModule, sharedStateModule, uiModule); return Guice.createInjector(mergedModule); } catch (Exception e) { logger.error("Failed to create injector for " + language); logger.error(e.getMessage(), e); throw new RuntimeException("Failed to create injector for " + language, e); } } protected Module getRuntimeModule(String grammar) { if (ES_UAH_AUT_SRG_MICOBS_LANG_PDL.equals(grammar)) { return new es.uah.aut.srg.micobs.lang.PDLRuntimeModule(); } throw new IllegalArgumentException(grammar); } protected Module getUiModule(String grammar) { if (ES_UAH_AUT_SRG_MICOBS_LANG_PDL.equals(grammar)) { return new es.uah.aut.srg.micobs.lang.ui.PDLUiModule(this); } throw new IllegalArgumentException(grammar); } protected Module getSharedStateModule() { return new SharedStateModule(); } }
epl-1.0
debabratahazra/DS
designstudio/components/edge/core/com.odcgroup.edge.t24ui.model/ecore-gen/com/odcgroup/edge/t24ui/impl/T24UIFactoryImpl.java
3190
/** */ package com.odcgroup.edge.t24ui.impl; import com.odcgroup.edge.t24ui.*; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class T24UIFactoryImpl extends EFactoryImpl implements T24UIFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static T24UIFactory init() { try { T24UIFactory theT24UIFactory = (T24UIFactory)EPackage.Registry.INSTANCE.getEFactory(T24UIPackage.eNS_URI); if (theT24UIFactory != null) { return theT24UIFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new T24UIFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public T24UIFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case T24UIPackage.AVAILABLE_COS_PATTERNS: return createAvailableCOSPatterns(); case T24UIPackage.COMPOSITE_SCREEN: return createCompositeScreen(); case T24UIPackage.BESPOKE_COMPOSITE_SCREEN: return createBespokeCompositeScreen(); case T24UIPackage.AVAILABLE_TRANSLATION_LANGUAGES: return createAvailableTranslationLanguages(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AvailableCOSPatterns createAvailableCOSPatterns() { AvailableCOSPatternsImpl availableCOSPatterns = new AvailableCOSPatternsImpl(); return availableCOSPatterns; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CompositeScreen createCompositeScreen() { CompositeScreenImpl compositeScreen = new CompositeScreenImpl(); return compositeScreen; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BespokeCompositeScreen createBespokeCompositeScreen() { BespokeCompositeScreenImpl bespokeCompositeScreen = new BespokeCompositeScreenImpl(); return bespokeCompositeScreen; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AvailableTranslationLanguages createAvailableTranslationLanguages() { AvailableTranslationLanguagesImpl availableTranslationLanguages = new AvailableTranslationLanguagesImpl(); return availableTranslationLanguages; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public T24UIPackage getT24UIPackage() { return (T24UIPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static T24UIPackage getPackage() { return T24UIPackage.eINSTANCE; } } //T24UIFactoryImpl
epl-1.0
AldebaranLeger/RamziAndTheScientists
Camera.java
1309
import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; public class Camera { private Ramzi player; private float xCamera, yCamera; //coordonnées du point que regarde la caméra (centre de l'écran) public Camera(Ramzi player) { this.player = player; this.xCamera = player.getX(); this.yCamera = player.getY(); } public void place(GameContainer container, Graphics g) { g.translate(container.getWidth() / 2 - (int) xCamera, container.getHeight() / 2 - (int) yCamera); } //traque le joueur public void update(GameContainer container) { refreshCamera(container); } public void refreshCamera(GameContainer container) { int containerWidth = container.getWidth() / 4; this.xCamera = cameraPosition(this.player.getX(), containerWidth); int containerHeight = container.getHeight() / 4; this.yCamera = cameraPosition(this.player.getY(), containerHeight); } public float cameraPosition(float playerPosition, int containerDimension){ float result = 0; if (playerPosition > this.yCamera + containerDimension) { result = playerPosition - containerDimension; } else if (playerPosition < this.yCamera - containerDimension) { result = playerPosition + containerDimension; } return result; } }
epl-1.0
mandeepdhami/controller
opendaylight/md-sal/messagebus-impl/src/main/java/org/opendaylight/controller/messagebus/eventsources/netconf/NetconfEventSource.java
17108
/* * 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.messagebus.eventsources.netconf; import static com.google.common.util.concurrent.Futures.immediateFuture; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.regex.Pattern; import javax.xml.stream.XMLStreamException; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.MountPoint; import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; import org.opendaylight.controller.md.sal.dom.api.DOMEvent; import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint; import org.opendaylight.controller.md.sal.dom.api.DOMNotification; import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener; import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService; import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService; import org.opendaylight.controller.messagebus.app.impl.TopicDOMNotification; import org.opendaylight.controller.messagebus.app.impl.Util; import org.opendaylight.controller.messagebus.spi.EventSource; import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicNotification; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicInput; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutput; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutputBuilder; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicStatus; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicInput; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.util.concurrent.CheckedFuture; public class NetconfEventSource implements EventSource, DOMNotificationListener { private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSource.class); private static final NodeIdentifier TOPIC_NOTIFICATION_ARG = new NodeIdentifier(TopicNotification.QNAME); private static final NodeIdentifier EVENT_SOURCE_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "node-id")); private static final NodeIdentifier TOPIC_ID_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "topic-id")); private static final NodeIdentifier PAYLOAD_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "payload")); private static final String ConnectionNotificationSourceName = "ConnectionNotificationSource"; private final String nodeId; private final Node node; private final DOMMountPoint netconfMount; private final MountPoint mountPoint; private final DOMNotificationPublishService domPublish; private final Map<String, String> urnPrefixToStreamMap; // key = urnPrefix, value = StreamName private final List<NotificationTopicRegistration> notificationTopicRegistrationList = new ArrayList<>(); public NetconfEventSource(final Node node, final Map<String, String> streamMap, final DOMMountPoint netconfMount, final MountPoint mountPoint, final DOMNotificationPublishService publishService) { this.netconfMount = Preconditions.checkNotNull(netconfMount); this.mountPoint = Preconditions.checkNotNull(mountPoint); this.node = Preconditions.checkNotNull(node); this.urnPrefixToStreamMap = Preconditions.checkNotNull(streamMap); this.domPublish = Preconditions.checkNotNull(publishService); this.nodeId = node.getNodeId().getValue(); this.initializeNotificationTopicRegistrationList(); LOG.info("NetconfEventSource [{}] created.", this.nodeId); } private void initializeNotificationTopicRegistrationList() { notificationTopicRegistrationList.add(new ConnectionNotificationTopicRegistration(ConnectionNotificationSourceName, this)); Optional<Map<String, Stream>> streamMap = getAvailableStreams(); if(streamMap.isPresent()){ LOG.debug("Stream configuration compare..."); for (String urnPrefix : this.urnPrefixToStreamMap.keySet()) { final String streamName = this.urnPrefixToStreamMap.get(urnPrefix); LOG.debug("urnPrefix: {} streamName: {}", urnPrefix, streamName); if(streamMap.get().containsKey(streamName)){ LOG.debug("Stream containig on device"); notificationTopicRegistrationList.add(new StreamNotificationTopicRegistration(streamMap.get().get(streamName),urnPrefix, this)); } } } } private Optional<Map<String, Stream>> getAvailableStreams(){ Map<String,Stream> streamMap = null; InstanceIdentifier<Streams> pathStream = InstanceIdentifier.builder(Netconf.class).child(Streams.class).build(); Optional<DataBroker> dataBroker = this.mountPoint.getService(DataBroker.class); if(dataBroker.isPresent()){ LOG.debug("GET Available streams ..."); ReadOnlyTransaction tx = dataBroker.get().newReadOnlyTransaction(); CheckedFuture<Optional<Streams>, ReadFailedException> checkFeature = tx.read(LogicalDatastoreType.OPERATIONAL,pathStream); try { Optional<Streams> streams = checkFeature.checkedGet(); if(streams.isPresent()){ streamMap = new HashMap<>(); for(Stream stream : streams.get().getStream()){ LOG.debug("*** find stream {}", stream.getName().getValue()); streamMap.put(stream.getName().getValue(), stream); } } } catch (ReadFailedException e) { LOG.warn("Can not read streams for node {}",this.nodeId); } } else { LOG.warn("No databroker on node {}", this.nodeId); } return Optional.fromNullable(streamMap); } @Override public Future<RpcResult<JoinTopicOutput>> joinTopic(final JoinTopicInput input) { LOG.debug("Join topic {} on {}", input.getTopicId().getValue(), this.nodeId); final NotificationPattern notificationPattern = input.getNotificationPattern(); final List<SchemaPath> matchingNotifications = getMatchingNotifications(notificationPattern); return registerTopic(input.getTopicId(),matchingNotifications); } @Override public Future<RpcResult<Void>> disJoinTopic(DisJoinTopicInput input) { for(NotificationTopicRegistration reg : notificationTopicRegistrationList){ reg.unRegisterNotificationTopic(input.getTopicId()); } return Util.resultRpcSuccessFor((Void) null) ; } private synchronized Future<RpcResult<JoinTopicOutput>> registerTopic(final TopicId topicId, final List<SchemaPath> notificationsToSubscribe){ LOG.debug("Join topic {} - register"); JoinTopicStatus joinTopicStatus = JoinTopicStatus.Down; if(notificationsToSubscribe != null && notificationsToSubscribe.isEmpty() == false){ LOG.debug("Notifications to subscribe has found - count {}",notificationsToSubscribe.size() ); final Optional<DOMNotificationService> notifyService = getDOMMountPoint().getService(DOMNotificationService.class); if(notifyService.isPresent()){ int registeredNotificationCount = 0; for(SchemaPath schemaNotification : notificationsToSubscribe){ for(NotificationTopicRegistration reg : notificationTopicRegistrationList){ LOG.debug("Try notification registratio {} on SchemaPathNotification {}", reg.getSourceName(), schemaNotification.getLastComponent().getLocalName()); if(reg.checkNotificationPath(schemaNotification)){ LOG.info("Source of notification {} is activating, TopicId {}", reg.getSourceName(), topicId.getValue() ); boolean regSuccess = reg.registerNotificationTopic(schemaNotification, topicId); if(regSuccess){ registeredNotificationCount = registeredNotificationCount +1; } } } } if(registeredNotificationCount > 0){ joinTopicStatus = JoinTopicStatus.Up; } } else { LOG.warn("NO DOMNotification service on node {}", this.nodeId); } } else { LOG.debug("Notifications to subscribe has NOT found"); } final JoinTopicOutput output = new JoinTopicOutputBuilder().setStatus(joinTopicStatus).build(); return immediateFuture(RpcResultBuilder.success(output).build()); } public void reActivateStreams(){ for (NotificationTopicRegistration reg : notificationTopicRegistrationList) { LOG.info("Source of notification {} is reactivating on node {}", reg.getSourceName(), this.nodeId); reg.reActivateNotificationSource(); } } public void deActivateStreams(){ for (NotificationTopicRegistration reg : notificationTopicRegistrationList) { LOG.info("Source of notification {} is deactivating on node {}", reg.getSourceName(), this.nodeId); reg.deActivateNotificationSource(); } } @Override public void onNotification(final DOMNotification notification) { SchemaPath notificationPath = notification.getType(); Date notificationEventTime = null; if(notification instanceof DOMEvent){ notificationEventTime = ((DOMEvent) notification).getEventTime(); } for(NotificationTopicRegistration notifReg : notificationTopicRegistrationList){ ArrayList<TopicId> topicIdsForNotification = notifReg.getNotificationTopicIds(notificationPath); if(topicIdsForNotification != null && topicIdsForNotification.isEmpty() == false){ if(notifReg instanceof StreamNotificationTopicRegistration){ StreamNotificationTopicRegistration streamReg = (StreamNotificationTopicRegistration)notifReg; streamReg.setLastEventTime(notificationEventTime); } for(TopicId topicId : topicIdsForNotification){ publishNotification(notification, topicId); LOG.debug("Notification {} has been published for TopicId {}",notification.getType(), topicId.getValue()); } } } } private void publishNotification(final DOMNotification notification, TopicId topicId){ final ContainerNode topicNotification = Builders.containerBuilder() .withNodeIdentifier(TOPIC_NOTIFICATION_ARG) .withChild(ImmutableNodes.leafNode(TOPIC_ID_ARG, topicId)) .withChild(ImmutableNodes.leafNode(EVENT_SOURCE_ARG, this.nodeId)) .withChild(encapsulate(notification)) .build(); try { domPublish.putNotification(new TopicDOMNotification(topicNotification)); } catch (final InterruptedException e) { throw Throwables.propagate(e); } } private AnyXmlNode encapsulate(final DOMNotification body) { // FIXME: Introduce something like AnyXmlWithNormalizedNodeData in Yangtools final Document doc = XmlUtil.newDocument(); final Optional<String> namespace = Optional.of(PAYLOAD_ARG.getNodeType().getNamespace().toString()); final Element element = XmlUtil.createElement(doc , "payload", namespace); final DOMResult result = new DOMResult(element); final SchemaContext context = getDOMMountPoint().getSchemaContext(); final SchemaPath schemaPath = body.getType(); try { NetconfMessageTransformUtil.writeNormalizedNode(body.getBody(), result, schemaPath, context); return Builders.anyXmlBuilder().withNodeIdentifier(PAYLOAD_ARG) .withValue(new DOMSource(element)) .build(); } catch (IOException | XMLStreamException e) { LOG.error("Unable to encapsulate notification.",e); throw Throwables.propagate(e); } } private List<SchemaPath> getMatchingNotifications(NotificationPattern notificationPattern){ // FIXME: default language should already be regex final String regex = Util.wildcardToRegex(notificationPattern.getValue()); final Pattern pattern = Pattern.compile(regex); List<SchemaPath> availableNotifications = getAvailableNotifications(); if(availableNotifications == null || availableNotifications.isEmpty()){ return null; } return Util.expandQname(availableNotifications, pattern); } @Override public void close() throws Exception { for(NotificationTopicRegistration streamReg : notificationTopicRegistrationList){ streamReg.close(); } } @Override public NodeKey getSourceNodeKey(){ return getNode().getKey(); } @Override public List<SchemaPath> getAvailableNotifications() { final List<SchemaPath> availNotifList = new ArrayList<>(); // add Event Source Connection status notification availNotifList.add(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH); // FIXME: use SchemaContextListener to get changes asynchronously final Set<NotificationDefinition> availableNotifications = getDOMMountPoint().getSchemaContext().getNotifications(); // add all known notifications from netconf device for (final NotificationDefinition nd : availableNotifications) { availNotifList.add(nd.getPath()); } return availNotifList; } public Node getNode() { return node; } DOMMountPoint getDOMMountPoint() { return netconfMount; } MountPoint getMountPoint() { return mountPoint; } NetconfNode getNetconfNode(){ return node.getAugmentation(NetconfNode.class); } }
epl-1.0
arpitpanwar/Crawler
src/edu/upenn/cis455/storage/entity/ChannelEntity.java
1518
package edu.upenn.cis455.storage.entity; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; import com.sleepycat.persist.model.Relationship; import com.sleepycat.persist.model.SecondaryKey; /** * Entity for Channel information * @author cis455 * */ @Entity public class ChannelEntity { @PrimaryKey private String channelId; private String channelName; private String xPathExpressions; private String styleSheet; private String channelCreatedBy; private long channelLastUpdated; public String getChannelId() { return channelId; } public void setChannelId(String channelId) { this.channelId = channelId; } public String getChannelName() { return channelName; } public void setChannelName(String channelName) { this.channelName = channelName; } public String getChannelCreatedBy() { return channelCreatedBy; } public void setChannelCreatedBy(String channelCreatedBy) { this.channelCreatedBy = channelCreatedBy; } public long getChannelLastUpdated() { return channelLastUpdated; } public void setChannelLastUpdated(long channelLastUpdated) { this.channelLastUpdated = channelLastUpdated; } public String getxPathExpressions() { return xPathExpressions; } public void setxPathExpressions(String xPathExpressions) { this.xPathExpressions = xPathExpressions; } public String getStyleSheet() { return styleSheet; } public void setStyleSheet(String styleSheet) { this.styleSheet = styleSheet; } }
epl-1.0
ModelWriter/WP6
EcoreConcepts-JavaConcepts-Annotator/src/eu/modelwriter/architecture/ecoreconcepts/javaconcepts/parser/EcoreConceptsParser.java
1741
package eu.modelwriter.architecture.ecoreconcepts.javaconcepts.parser; import java.io.*; import java.util.regex.*; /** * Ecore Concepts Parser * @author Samuel Cruz-Lara (LORIA) * */ public class EcoreConceptsParser { private static String basePath; private static String ecoreConceptsFile; private static String ecoreConceptsParseredFile; private static Pattern pattern; private static Matcher matcher; public EcoreConceptsParser() { EcoreConceptsParser.basePath = "EcoreConcepts-JavaConcepts-Annotator/ModelsContents/"; EcoreConceptsParser.ecoreConceptsFile = basePath + "EcoreConcepts.txt"; EcoreConceptsParser.ecoreConceptsParseredFile = basePath + "EcoreConceptsParsered.txt"; EcoreConceptsParser.pattern = Pattern.compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*$"); } public static void main(String[] args) { try { new EcoreConceptsParser().parser(); } catch (FileNotFoundException e) { System.out.println("Error while opening the file: " + EcoreConceptsParser.ecoreConceptsFile); } catch (IOException e) { System.out.println("I/O Error"); } catch (Exception e){ e.printStackTrace(); } } public void parser() throws FileNotFoundException, IOException, Exception { BufferedReader bfr = new BufferedReader(new FileReader(EcoreConceptsParser.ecoreConceptsFile)); BufferedWriter bfw = new BufferedWriter(new FileWriter(EcoreConceptsParser.ecoreConceptsParseredFile)); String ligne, strMatcher ; while ((ligne = bfr.readLine()) != null) { matcher = pattern.matcher(ligne); if (matcher.find()) { strMatcher = matcher.group(); System.out.println(strMatcher); bfw.write(strMatcher); } bfw.newLine(); } bfr.close(); bfw.close(); } }
epl-1.0
sabev/sap-services-registry-eclipse
org.eclipse.servicesregistry.proxy/src/org/eclipse/servicesregistry/proxy/ServicesRegistrySiService.java
2380
/******************************************************************************* * Copyright (c) 2012 SAP AG 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: * SAP AG - initial API and implementation *******************************************************************************/ package org.eclipse.servicesregistry.proxy; /** * Service implementation of {ServicesRegistrySiService} (generated by SAP WSDL to Java generator). */ @javax.xml.ws.WebServiceClient(name = "ServicesRegistrySiService", targetNamespace = "http://sap.com/esi/uddi/sr/api/ws/", wsdlLocation = "wsdl/servicesregistry.wsdl") public class ServicesRegistrySiService extends javax.xml.ws.Service { private final static java.net.URL SERVICESREGISTRYSISERVICE_WSDL_LOCATION; static { java.net.URL url = null; try { java.net.URL tmpUrl = ServicesRegistrySiService.class.getClassLoader().getResource("wsdl/servicesregistry.wsdl"); url = new java.net.URL(tmpUrl.getProtocol(), tmpUrl.getHost(), tmpUrl.getPort(), tmpUrl.getFile()); } catch (java.net.MalformedURLException e) { e.printStackTrace(); } SERVICESREGISTRYSISERVICE_WSDL_LOCATION = url; } /** * Default service constructor. */ public ServicesRegistrySiService() throws java.net.MalformedURLException { super(SERVICESREGISTRYSISERVICE_WSDL_LOCATION, new javax.xml.namespace.QName("http://sap.com/esi/uddi/sr/api/ws/", "ServicesRegistrySiService")); } public ServicesRegistrySiService(java.net.URL wsdlLocation, javax.xml.namespace.QName serviceName) { super(wsdlLocation, serviceName); } /** * Get method for webservice port [ServicesRegistrySiPort]. */ @javax.xml.ws.WebEndpoint(name = "ServicesRegistrySiPort") public org.eclipse.servicesregistry.proxy.ServicesRegistrySi getServicesRegistrySiPort() { javax.xml.namespace.QName portName = new javax.xml.namespace.QName("http://sap.com/esi/uddi/sr/api/ws/","ServicesRegistrySiPort"); return (org.eclipse.servicesregistry.proxy.ServicesRegistrySi) super.getPort(portName,org.eclipse.servicesregistry.proxy.ServicesRegistrySi.class); } }
epl-1.0
rohitdubey12/kura
kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/type/IntegerValue.java
2595
/******************************************************************************* * Copyright (c) 2016, 2017 Eurotech and/or its affiliates 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: * Eurotech * Amit Kumar Mondal * *******************************************************************************/ package org.eclipse.kura.type; import static java.util.Objects.requireNonNull; import static org.eclipse.kura.type.DataType.INTEGER; import org.eclipse.kura.annotation.Immutable; import org.eclipse.kura.annotation.ThreadSafe; /** * This class represents a {@link Integer} value as a {@link TypedValue}. * * @noextend This class is not intended to be extended by clients. */ @Immutable @ThreadSafe public class IntegerValue implements TypedValue<Integer> { /** * The actual contained value that will be represented as * {@link TypedValue}. */ private final int value; /** * Instantiates a new integer value. * * @param value * the value */ public IntegerValue(final int value) { this.value = value; } /** {@inheritDoc} */ @Override public int compareTo(final TypedValue<Integer> otherTypedValue) { requireNonNull(otherTypedValue, "Typed Value cannot be null"); return Integer.valueOf(this.value).compareTo(otherTypedValue.getValue()); } /** {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final IntegerValue other = (IntegerValue) obj; if (this.value != other.value) { return false; } return true; } /** {@inheritDoc} */ @Override public DataType getType() { return INTEGER; } /** {@inheritDoc} */ @Override public Integer getValue() { return this.value; } /** {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + this.value; return result; } /** {@inheritDoc} */ @Override public String toString() { return "IntegerValue [value=" + this.value + "]"; } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/ui/search/OccurrencesSearchLabelProvider.java
3709
/******************************************************************************* * Copyright (c) 2000, 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.StyledString.Styler; import org.eclipse.search.ui.text.AbstractTextSearchViewPage; import org.eclipse.search.ui.text.Match; import org.eclipse.jdt.internal.core.manipulation.search.IOccurrencesFinder; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.viewsupport.ColoringLabelProvider; import org.eclipse.jdt.internal.core.manipulation.search.SearchMessages; class OccurrencesSearchLabelProvider extends TextSearchLabelProvider implements IStyledLabelProvider { public OccurrencesSearchLabelProvider(AbstractTextSearchViewPage page) { super(page); } @Override public String getText(Object element) { return getLabelWithCounts(element, internalGetText(element)); } private String getLineNumberLabel(JavaElementLine element) { return Messages.format(SearchMessages.OccurrencesSearchLabelProvider_line_number, new Integer(element.getLineNumber() + 1)); } private String internalGetText(Object element) { JavaElementLine jel= (JavaElementLine) element; return getLineNumberLabel(jel) + jel.getLineContents(); } private StyledString internalGetRichText(Object element) { JavaElementLine jel= (JavaElementLine) element; String lineNumberString= getLineNumberLabel(jel); Styler highlightStyle= ColoringLabelProvider.HIGHLIGHT_STYLE; StyledString res= new StyledString(); res.append(lineNumberString, StyledString.QUALIFIER_STYLER); res.append(jel.getLineContents()); Match[] matches= getPage().getInput().getMatches(jel); for (int i= 0; i < matches.length; i++) { OccurrenceMatch curr= (OccurrenceMatch) matches[i]; int offset= curr.getOriginalOffset() - jel.getLineStartOffset() + lineNumberString.length(); int length= curr.getOriginalLength(); if (offset >= 0 && (offset + length <= res.length())) { if ((curr.getFlags() & IOccurrencesFinder.F_WRITE_OCCURRENCE) != 0) { res.setStyle(offset, length, ColoringLabelProvider.HIGHLIGHT_WRITE_STYLE); } else { res.setStyle(offset, length, highlightStyle); } } } return res; } @Override public Image getImage(Object element) { if (element instanceof JavaElementLine) { int flags= ((JavaElementLine) element).getFlags(); if ((flags & IOccurrencesFinder.F_WRITE_OCCURRENCE) != 0) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_WRITEACCESS); } if ((flags & IOccurrencesFinder.F_READ_OCCURRENCE) != 0) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_READACCESS); } if ((flags & IOccurrencesFinder.F_EXCEPTION_DECLARATION) != 0) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); } } return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_OCCURRENCE); } @Override public StyledString getStyledText(Object element) { return getColoredLabelWithCounts(element, internalGetRichText(element)); } }
epl-1.0
hoticer/FoodOrder
src/com/hoticer/ordering/domain/User.java
1315
package com.hoticer.ordering.domain; import java.util.LinkedHashSet; import java.util.Set; public class User { private Integer userId; private String username; private String password; private int access; private Set<Trade> trades = new LinkedHashSet<Trade>(); public void setTrades(Set<Trade> trades) { this.trades = trades; } public Set<Trade> getTrades() { return trades; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAccess() { return access; } public void setAccess(int access) { this.access = access; } @Override public String toString() { return "User [userId=" + userId + ", username=" + username + ", password=" + password + ", access=" + access + "]"; } public User(Integer userId, String username, String password, int access) { super(); this.userId = userId; this.username = username; this.password = password; this.access = access; } public User() { // TODO Auto-generated constructor stub } }
epl-1.0
sleshchenko/che
selenium/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClientFactory.java
718
/* * 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.selenium.core.client; import com.google.inject.assistedinject.Assisted; /** @author Dmytro Nochevnov */ public interface TestUserServiceClientFactory { TestUserServiceClientImpl create( @Assisted("name") String name, @Assisted("password") String password, @Assisted("offlineToken") String offlineToken); }
epl-1.0
IBM-i2/Data-Acquisition-Accelerators
Data-Acquisition-Accelerators/Acxiom_Accelerator/eclipse-project/acxiom-example/src/acxiom-soap/com/acxiom/schemas/v201110/us/idod/findpeople/response/InputFormatFaultType.java
2218
// // Generated By:JAX-WS RI IBM 2.2.1-11/28/2011 08:27 AM(foreman)- (JAXB RI IBM 2.2.3-07/05/2013 05:22 AM(foreman)-) // package com.acxiom.schemas.v201110.us.idod.findpeople.response; 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 InputFormatFaultType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="InputFormatFaultType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Detail" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Field" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "InputFormatFaultType", propOrder = { "detail", "field" }) public class InputFormatFaultType { @XmlElement(name = "Detail") protected String detail; @XmlElement(name = "Field") protected String field; /** * Gets the value of the detail property. * * @return * possible object is * {@link String } * */ public String getDetail() { return detail; } /** * Sets the value of the detail property. * * @param value * allowed object is * {@link String } * */ public void setDetail(String value) { this.detail = value; } /** * Gets the value of the field property. * * @return * possible object is * {@link String } * */ public String getField() { return field; } /** * Sets the value of the field property. * * @param value * allowed object is * {@link String } * */ public void setField(String value) { this.field = value; } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/inheritance/ns/JAXBInheritanceSubTypeParentRootOnlyTestCases.java
2969
/******************************************************************************* * 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: * Denise Smith - May 2012 ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.inheritance.ns; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import org.eclipse.persistence.jaxb.JAXBMarshaller; import org.eclipse.persistence.jaxb.MarshallerProperties; import org.eclipse.persistence.jaxb.UnmarshallerProperties; import org.eclipse.persistence.oxm.XMLConstants; import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases; public class JAXBInheritanceSubTypeParentRootOnlyTestCases extends JAXBWithJSONTestCases { public JAXBInheritanceSubTypeParentRootOnlyTestCases(String name) throws Exception { super(name); setClasses(new Class[] {SubTypeParentRootOnly.class}); setControlDocument("org/eclipse/persistence/testing/jaxb/inheritance/ns/subTypeParentRoot.xml"); setControlJSON("org/eclipse/persistence/testing/jaxb/inheritance/ns/subTypeParentRoot.json"); Map<String, String> namespaces= new HashMap<String, String>(); namespaces.put("rootNamespace","ns0"); namespaces.put("someNamespace","ns1"); namespaces.put(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,"xsi"); jaxbUnmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, namespaces); } public JAXBMarshaller getJSONMarshaller() throws Exception{ Map<String, String> namespaces= new HashMap<String, String>(); namespaces.put("rootNamespace","ns0"); namespaces.put("someNamespace","ns1"); namespaces.put(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,"xsi"); JAXBMarshaller jsonMarshaller = (JAXBMarshaller) jaxbContext.createMarshaller(); jsonMarshaller.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER, namespaces); jsonMarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json"); return jsonMarshaller; } public Object getControlObject() { SubTypeParentRootOnly subType = new SubTypeParentRootOnly(); return subType; } public Object getReadControlObject() { SubTypeParentRootOnly subType = new SubTypeParentRootOnly(); JAXBElement elem = new JAXBElement<BaseTypeWithRootElement>(new QName("baseTypeWithRootElement"), BaseTypeWithRootElement.class, subType); return elem; } }
epl-1.0
eclipse/ice
org.eclipse.ice.client.widgets/src/org/eclipse/ice/client/widgets/providers/Default/DefaultGeometryPageProvider.java
2189
/******************************************************************************* * Copyright (c) 2012, 2014, 2015 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 re-implementation and/or initial documentation - * Fangzhou Lin * Minor updates for architecture compliance, original implementation - * Jay Jay Billings *******************************************************************************/ package org.eclipse.ice.client.widgets.providers.Default; import java.util.ArrayList; import org.eclipse.ice.client.widgets.ICEGeometryPage; import org.eclipse.ice.client.widgets.providers.IGeometryPageProvider; import org.eclipse.ice.datastructures.ICEObject.Component; import org.eclipse.ice.datastructures.form.GeometryComponent; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.editor.IFormPage; /** * This class is a default extension for providing Default Geometry Page * * @author Fangzhou Lin, Jay Jay Billings * */ public class DefaultGeometryPageProvider extends DefaultPageProvider implements IGeometryPageProvider { /* * (non-Javadoc) * * @see * org.eclipse.ice.client.widgets.providers.IGeometryPageProvider#getPages( * org. eclipse.ui.forms.editor.FormEditor, java.util.ArrayList) */ @Override public ArrayList<IFormPage> getPages(FormEditor formEditor, ArrayList<Component> components) { ArrayList<IFormPage> pages = new ArrayList<IFormPage>(); // Get the GeometryComponent and create the GeometryPage. if (!(components.isEmpty())) { GeometryComponent geometryComponent = (GeometryComponent) (components .get(0)); if (geometryComponent != null) { // Make the GeometryPage ICEGeometryPage geometryPage = new ICEGeometryPage(formEditor, "GPid", geometryComponent.getName()); // Set the GeometryComponent geometryPage.setGeometry(geometryComponent); pages.add(geometryPage); } } return pages; } }
epl-1.0
nickmain/xmind
bundles/org.xmind.ui.mindmap/src/org/xmind/ui/commands/CreateBoundaryCommand.java
1644
/* ****************************************************************************** * Copyright (c) 2006-2012 XMind Ltd. and others. * * This file is a part of XMind 3. XMind releases 3 and * above are dual-licensed under the Eclipse Public License (EPL), * which is available at http://www.eclipse.org/legal/epl-v10.html * and the GNU Lesser General Public License (LGPL), * which is available at http://www.gnu.org/licenses/lgpl.html * See http://www.xmind.net/license.html for details. * * Contributors: * XMind Ltd. - initial API and implementation *******************************************************************************/ package org.xmind.ui.commands; import org.eclipse.core.runtime.Assert; import org.xmind.core.IBoundary; import org.xmind.core.IWorkbook; import org.xmind.gef.command.CreateCommand; import org.xmind.ui.internal.MindMapUIPlugin; public class CreateBoundaryCommand extends CreateCommand { private IWorkbook workbook; private IBoundary boundary; public CreateBoundaryCommand(IWorkbook workbook) { Assert.isNotNull(workbook); this.workbook = workbook; } protected boolean canCreate() { if (boundary == null) { boundary = workbook.createBoundary(); } return boundary != null; } protected Object create() { canCreate(); return boundary; } @Override public void execute() { MindMapUIPlugin.getDefault().getUsageDataCollector() .increase("InsertBoundaryCount"); //$NON-NLS-1$ super.execute(); } }
epl-1.0
aptana/Pydev
bundles/com.python.pydev.refactoring/src/com/python/pydev/refactoring/refactorer/Refactorer.java
5535
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.python.pydev.refactoring.refactorer; import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation; import org.python.pydev.core.log.Log; import org.python.pydev.editor.codecompletion.revisited.visitors.AssignDefinition; import org.python.pydev.editor.model.ItemPointer; import org.python.pydev.editor.refactoring.AbstractPyRefactoring; import org.python.pydev.editor.refactoring.RefactoringRequest; import org.python.pydev.editor.refactoring.TooManyMatchesException; import org.python.pydev.parser.visitors.scope.ASTEntry; import org.python.pydev.shared_core.structure.Tuple; import org.python.pydev.shared_ui.EditorUtils; import com.python.pydev.refactoring.IPyRefactoring2; import com.python.pydev.refactoring.wizards.rename.PyRenameEntryPoint; import com.python.pydev.refactoring.wizards.rename.PyRenameRefactoringWizard; import com.python.pydev.ui.hierarchy.HierarchyNodeModel; /** * This is the entry point for any refactoring that we implement. * * @author Fabio */ public class Refactorer extends AbstractPyRefactoring implements IPyRefactoring2 { public String getName() { return "PyDev Extensions Refactorer"; } /** * Renames something... * * Basically passes things to the rename processor (it will choose the kind of rename that will happen). * * @see org.python.pydev.editor.refactoring.IPyRefactoring#rename(org.python.pydev.editor.refactoring.RefactoringRequest) */ public String rename(RefactoringRequest request) { try { RenameRefactoring renameRefactoring = new RenameRefactoring(new PyRenameEntryPoint(request)); request.fillInitialNameAndOffset(); final PyRenameRefactoringWizard wizard = new PyRenameRefactoringWizard(renameRefactoring, "Rename", "inputPageDescription", request, request.initialName); try { RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard); op.run(EditorUtils.getShell(), "Rename Refactor Action"); } catch (InterruptedException e) { // do nothing. User action got cancelled } } catch (Exception e) { Log.log(e); } return null; } public ItemPointer[] findDefinition(RefactoringRequest request) throws TooManyMatchesException { return new RefactorerFindDefinition().findDefinition(request); } // --------------------------------------------------------- IPyRefactoring2 public boolean areAllInSameClassHierarchy(List<AssignDefinition> defs) { return new RefactorerFinds(this).areAllInSameClassHierarchy(defs); } public HierarchyNodeModel findClassHierarchy(RefactoringRequest request, boolean findOnlyParents) { return new RefactorerFinds(this).findClassHierarchy(request, findOnlyParents); } public Map<Tuple<String, File>, HashSet<ASTEntry>> findAllOccurrences(RefactoringRequest req) throws OperationCanceledException, CoreException { PyRenameEntryPoint processor = new PyRenameEntryPoint(req); //to see if a new request was not created in the meantime (in which case this one will be cancelled) req.checkCancelled(); IProgressMonitor monitor = req.getMonitor(); Map<Tuple<String, File>, HashSet<ASTEntry>> occurrencesInOtherFiles; try { monitor.beginTask("Find all occurrences", 100); monitor.setTaskName("Find all occurrences"); RefactoringStatus status; try { req.pushMonitor(new SubProgressMonitor(monitor, 10)); status = processor.checkInitialConditions(req.getMonitor()); if (status.getSeverity() == RefactoringStatus.FATAL) { return null; } } finally { req.popMonitor().done(); } req.checkCancelled(); try { req.pushMonitor(new SubProgressMonitor(monitor, 85)); status = processor.checkFinalConditions(req.getMonitor(), null, false); if (status.getSeverity() == RefactoringStatus.FATAL) { return null; } } finally { req.popMonitor().done(); } req.checkCancelled(); occurrencesInOtherFiles = processor.getOccurrencesInOtherFiles(); HashSet<ASTEntry> occurrences = processor.getOccurrences(); occurrencesInOtherFiles.put(new Tuple<String, File>(req.moduleName, req.pyEdit.getEditorFile()), occurrences); req.getMonitor().worked(5); } finally { monitor.done(); } return occurrencesInOtherFiles; } }
epl-1.0
pkriens/bndtools
bndtools.jareditor/src/bndtools/jareditor/internal/Printer.java
13499
package bndtools.jareditor.internal; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.jar.Manifest; import java.util.zip.ZipException; import aQute.bnd.header.Attrs; import aQute.bnd.header.Parameters; import aQute.bnd.osgi.Analyzer; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Descriptors.PackageRef; import aQute.bnd.osgi.Domain; import aQute.bnd.osgi.Jar; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.Resource; import aQute.bnd.osgi.Verifier; import aQute.lib.collections.SortedList; import aQute.lib.io.IO; import aQute.libg.generics.Create; import bndtools.jareditor.internal.utils.CollectionUtil; public class Printer extends Processor { final static int MANIFEST = 2; final static int LIST = 4; final static int IMPEXP = 16; final static int USES = 32; final static int USEDBY = 64; final static int COMPONENT = 128; final static int METATYPE = 256; final static int VERIFY = 1; PrintStream out = System.out; private static final String EOL = String.format("%n"); public void setOut(PrintStream out) { this.out = out; } public void doPrint(String string, int options) throws Exception { int optionsi = options; File file = new File(string); if (!file.exists()) error("File to print not found: " + string); else { if (optionsi == 0) optionsi = VERIFY | MANIFEST | IMPEXP | USES; doPrint(file, optionsi); } } private void doPrint(File file, int options) throws ZipException, IOException, Exception { Jar jar = new Jar(file.getName(), file); try { if ((options & VERIFY) != 0) { Verifier verifier = new Verifier(jar); verifier.setPedantic(isPedantic()); verifier.verify(); getInfo(verifier); } if ((options & MANIFEST) != 0) { Manifest manifest = jar.getManifest(); if (manifest == null) warning("JAR has no manifest " + file); else { out.println("[MANIFEST " + jar.getName() + "]"); printManifest(manifest); } out.println(); } if ((options & IMPEXP) != 0) { out.println("[IMPEXP]"); Manifest m = jar.getManifest(); if (m != null) { Domain domain = Domain.domain(m); Parameters imports = domain.getImportPackage(); Parameters exports = domain.getExportPackage(); for (String p : exports.keySet()) { if (imports.containsKey(p)) { Attrs attrs = imports.get(p); if (attrs.containsKey(VERSION_ATTRIBUTE)) { exports.get(p).put("imported-as", attrs.get(VERSION_ATTRIBUTE)); } } } print("Import-Package", new TreeMap<String,Attrs>(imports)); print("Export-Package", new TreeMap<String,Attrs>(exports)); } else warning("File has no manifest"); } if ((options & (USES | USEDBY)) != 0) { out.println(); Analyzer analyzer = new Analyzer(); try { analyzer.setPedantic(isPedantic()); analyzer.setJar(jar); analyzer.analyze(); if ((options & USES) != 0) { out.println("[USES]"); printMultiMap(analyzer.getUses()); out.println(); } if ((options & USEDBY) != 0) { out.println("[USEDBY]"); Map<PackageRef,Set<PackageRef>> usedBy = CollectionUtil.invertMapOfCollection(analyzer.getUses()); printMultiMap(usedBy); } analyzer.setJar((Jar) null); } finally { analyzer.close(); } out.println(); } if ((options & COMPONENT) != 0) { printComponents(jar); out.println(); } if ((options & METATYPE) != 0) { printMetatype(jar); out.println(); } if ((options & LIST) != 0) { out.println("[LIST]"); for (Map.Entry<String,Map<String,Resource>> entry : jar.getDirectories().entrySet()) { String name = entry.getKey(); Map<String,Resource> contents = entry.getValue(); out.println(name); if (contents != null) { for (String element : contents.keySet()) { int n = element.lastIndexOf('/'); if (n > 0) element = element.substring(n + 1); out.print(" "); out.print(element); String path = element; if (name.length() != 0) path = name + "/" + element; Resource r = contents.get(path); if (r != null) { String extra = r.getExtra(); if (extra != null) { out.print(" extra='" + escapeUnicode(extra) + "'"); } } out.println(); } } } out.println(); } } finally { jar.close(); } } /** * @param manifest */ private void printManifest(Manifest manifest) { SortedSet<String> sorted = new TreeSet<String>(); for (Object element : manifest.getMainAttributes().keySet()) { sorted.add(element.toString()); } for (String key : sorted) { Object value = manifest.getMainAttributes().getValue(key); format(out, "%-40s %-40s%s", new Object[] { key, value, EOL }); } } private void print(String msg, Map< ? , ? extends Map< ? , ? >> ports) { if (ports.isEmpty()) return; out.println(msg); for (Entry< ? , ? extends Map< ? , ? >> entry : ports.entrySet()) { Object key = entry.getKey(); Map< ? , ? > clause = Create.copy(entry.getValue()); clause.remove("uses:"); format(out, " %-38s %s%s", key.toString().trim(), clause.isEmpty() ? "" : clause.toString(), EOL); } } private <T extends Comparable< ? super T>> void printMultiMap(Map<T, ? extends Collection<T>> map) { SortedList<T> keys = new SortedList<T>(map.keySet()); for (Object key : keys) { String name = key.toString(); SortedList<T> values = new SortedList<T>(map.get(key)); String list = vertical(41, values); format(out, "%-40s %s", name, list); } } private static String vertical(int padding, Collection< ? > used) { StringBuilder sb = new StringBuilder(); String del = ""; for (Object s : used) { String name = s.toString(); sb.append(del); sb.append(name); sb.append(EOL); del = pad(padding); } if (sb.length() == 0) sb.append(EOL); return sb.toString(); } private static String pad(int i) { StringBuilder sb = new StringBuilder(); int ii = i; while (ii-- > 0) sb.append(' '); return sb.toString(); } private static void format(PrintStream out, String string, Object... objects) { if (objects == null || objects.length == 0) return; StringBuffer sb = new StringBuffer(); int index = 0; for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); switch (c) { case '%' : String s = objects[index++] + ""; int width = 0; int justify = -1; i++; c = string.charAt(i++); switch (c) { case '-' : justify = -1; break; case '+' : justify = 1; break; case '|' : justify = 0; break; default : --i; } c = string.charAt(i++); while (c >= '0' && c <= '9') { width *= 10; width += c - '0'; c = string.charAt(i++); } --i; if (c != 's') { throw new IllegalArgumentException("Invalid sprintf format: " + string); } if (s.length() > width) sb.append(s); else { switch (justify) { case -1 : default : sb.append(s); for (int j = 0; j < width - s.length(); j++) sb.append(" "); break; case 1 : for (int j = 0; j < width - s.length(); j++) sb.append(" "); sb.append(s); break; case 0 : int spaces = (width - s.length()) / 2; for (int j = 0; j < spaces; j++) sb.append(" "); sb.append(s); for (int j = 0; j < width - s.length() - spaces; j++) sb.append(" "); break; } } break; default : sb.append(c); } } out.print(sb); } private static final String escapeUnicode(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= ' ' && c <= '~' && c != '\\') sb.append(c); else { sb.append("\\u"); sb.append(nibble(c >> 12)); sb.append(nibble(c >> 8)); sb.append(nibble(c >> 4)); sb.append(nibble(c)); } } return sb.toString(); } private static final char nibble(int i) { return "0123456789ABCDEF".charAt(i & 0xF); } /** * Print the components in this JAR. * * @param jar */ private void printComponents(Jar jar) throws Exception { out.println("[COMPONENTS]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } String componentHeader = manifest.getMainAttributes().getValue(Constants.SERVICE_COMPONENT); Parameters clauses = new Parameters(componentHeader); boolean printed = false; for (String path : clauses.keySet()) { printed = true; out.println(path); Resource r = jar.getResource(path); if (r != null) { InputStreamReader ir = new InputStreamReader(r.openInputStream(), Constants.DEFAULT_CHARSET); OutputStreamWriter or = new OutputStreamWriter(out, Constants.DEFAULT_CHARSET); try { IO.copy(ir, or); } finally { or.flush(); ir.close(); } } else { out.println(" - no resource"); warning("No Resource found for service component: " + path); } } if (printed) { out.println(); } } /** * Print the metatypes in this JAR. * * @param jar */ private void printMetatype(Jar jar) throws Exception { out.println("[METATYPE]"); Manifest manifest = jar.getManifest(); if (manifest == null) { out.println("No manifest"); return; } Map<String,Resource> map = jar.getDirectories().get("OSGI-INF/metatype"); if (map != null) { for (Map.Entry<String,Resource> entry : map.entrySet()) { out.println(entry.getKey()); IO.copy(entry.getValue().openInputStream(), out); out.println(); } out.println(); } } }
epl-1.0
alexVengrovsk/che
plugins/plugin-java/che-plugin-java-ext-lang-client/src/main/java/org/eclipse/che/ide/ext/java/client/editor/JavaReconcileClient.java
2642
/******************************************************************************* * 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.ide.ext.java.client.editor; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.ext.java.shared.dto.ReconcileResult; import org.eclipse.che.ide.rest.AsyncRequestCallback; import org.eclipse.che.ide.rest.AsyncRequestFactory; import org.eclipse.che.ide.rest.DtoUnmarshallerFactory; import org.eclipse.che.ide.util.loging.Log; /** * @author Evgen Vidolob */ @Singleton public class JavaReconcileClient { private final DtoUnmarshallerFactory dtoUnmarshallerFactory; private final AsyncRequestFactory asyncRequestFactory; private final AppContext appContext; @Inject public JavaReconcileClient(DtoUnmarshallerFactory dtoUnmarshallerFactory, AppContext appContext, AsyncRequestFactory asyncRequestFactory) { this.appContext = appContext; this.dtoUnmarshallerFactory = dtoUnmarshallerFactory; this.asyncRequestFactory = asyncRequestFactory; } public void reconcile(String projectPath, String fqn, final ReconcileCallback callback) { String url = appContext.getDevMachine().getWsAgentBaseUrl() + "/jdt/" + appContext.getWorkspaceId() + "/reconcile/?projectpath=" + projectPath + "&fqn=" + fqn; asyncRequestFactory.createGetRequest(url) .send(new AsyncRequestCallback<ReconcileResult>(dtoUnmarshallerFactory.newUnmarshaller(ReconcileResult.class)) { @Override protected void onSuccess(ReconcileResult result) { callback.onReconcile(result); } @Override protected void onFailure(Throwable exception) { Log.error(JavaReconcileClient.class, exception); } }); } public interface ReconcileCallback { void onReconcile(ReconcileResult result); } }
epl-1.0
LittleNoobLol/renren-crawler
renren-crawler/src/main/java/io/renren/modules/crawler/context/url/BJHUrl.java
265
package io.renren.modules.crawler.context.url; public class BJHUrl { public static String getList(int limit,int skip){ return "https://baijia.baidu.com/listarticle?ajax=json&_limit="+limit+"&_skip="+skip+"&quality=1&_desc=top_st%2Cupdated_at"; } }
epl-1.0
debabratahazra/DS
designstudio/components/t24menu/ui/com.odcgroup.t24.menu.edit/src/com/odcgroup/t24/menu/menu/provider/TranslationItemProvider.java
5378
/** */ package com.odcgroup.t24.menu.menu.provider; import com.odcgroup.t24.menu.menu.MenuPackage; import com.odcgroup.t24.menu.menu.Translation; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemProviderAdapter; import org.eclipse.emf.edit.provider.ViewerNotification; /** * This is the item provider adapter for a {@link com.odcgroup.t24.menu.menu.Translation} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class TranslationItemProvider extends ItemProviderAdapter implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TranslationItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addLanguagePropertyDescriptor(object); addMessagePropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Language feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addLanguagePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Translation_language_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Translation_language_feature", "_UI_Translation_type"), MenuPackage.Literals.TRANSLATION__LANGUAGE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Message feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addMessagePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Translation_message_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Translation_message_feature", "_UI_Translation_type"), MenuPackage.Literals.TRANSLATION__MESSAGE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This returns Translation.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Translation")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((Translation)object).getLanguage(); return label == null || label.length() == 0 ? getString("_UI_Translation_type") : getString("_UI_Translation_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(Translation.class)) { case MenuPackage.TRANSLATION__LANGUAGE: case MenuPackage.TRANSLATION__MESSAGE: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ResourceLocator getResourceLocator() { return MenuEditPlugin.INSTANCE; } }
epl-1.0
ObeoNetwork/EAST-ADL-Designer
plugins/org.obeonetwork.dsl.eastadl/src/org/obeonetwork/dsl/east_adl/behavior/impl/TransitionImpl.java
13178
/** * <copyright> * </copyright> * * $Id$ */ package org.obeonetwork.dsl.east_adl.behavior.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.obeonetwork.dsl.east_adl.behavior.BehaviorPackage; import org.obeonetwork.dsl.east_adl.behavior.State; import org.obeonetwork.dsl.east_adl.behavior.Transition; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Transition</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.obeonetwork.dsl.east_adl.behavior.impl.TransitionImpl#getTrigger <em>Trigger</em>}</li> * <li>{@link org.obeonetwork.dsl.east_adl.behavior.impl.TransitionImpl#getGuard <em>Guard</em>}</li> * <li>{@link org.obeonetwork.dsl.east_adl.behavior.impl.TransitionImpl#getEffect <em>Effect</em>}</li> * <li>{@link org.obeonetwork.dsl.east_adl.behavior.impl.TransitionImpl#getSource <em>Source</em>}</li> * <li>{@link org.obeonetwork.dsl.east_adl.behavior.impl.TransitionImpl#getDestination <em>Destination</em>}</li> * </ul> * </p> * * @generated */ public class TransitionImpl extends EObjectImpl implements Transition { /** * The default value of the '{@link #getTrigger() <em>Trigger</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTrigger() * @generated * @ordered */ protected static final String TRIGGER_EDEFAULT = null; /** * The cached value of the '{@link #getTrigger() <em>Trigger</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTrigger() * @generated * @ordered */ protected String trigger = TRIGGER_EDEFAULT; /** * The default value of the '{@link #getGuard() <em>Guard</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getGuard() * @generated * @ordered */ protected static final String GUARD_EDEFAULT = null; /** * The cached value of the '{@link #getGuard() <em>Guard</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getGuard() * @generated * @ordered */ protected String guard = GUARD_EDEFAULT; /** * The default value of the '{@link #getEffect() <em>Effect</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEffect() * @generated * @ordered */ protected static final String EFFECT_EDEFAULT = null; /** * The cached value of the '{@link #getEffect() <em>Effect</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEffect() * @generated * @ordered */ protected String effect = EFFECT_EDEFAULT; /** * The cached value of the '{@link #getSource() <em>Source</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSource() * @generated * @ordered */ protected State source; /** * The cached value of the '{@link #getDestination() <em>Destination</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDestination() * @generated * @ordered */ protected State destination; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TransitionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return BehaviorPackage.Literals.TRANSITION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getTrigger() { return trigger; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTrigger(String newTrigger) { String oldTrigger = trigger; trigger = newTrigger; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BehaviorPackage.TRANSITION__TRIGGER, oldTrigger, trigger)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getGuard() { return guard; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setGuard(String newGuard) { String oldGuard = guard; guard = newGuard; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BehaviorPackage.TRANSITION__GUARD, oldGuard, guard)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getEffect() { return effect; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEffect(String newEffect) { String oldEffect = effect; effect = newEffect; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BehaviorPackage.TRANSITION__EFFECT, oldEffect, effect)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public State getSource() { if (source != null && source.eIsProxy()) { InternalEObject oldSource = (InternalEObject)source; source = (State)eResolveProxy(oldSource); if (source != oldSource) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, BehaviorPackage.TRANSITION__SOURCE, oldSource, source)); } } return source; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public State basicGetSource() { return source; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSource(State newSource, NotificationChain msgs) { State oldSource = source; source = newSource; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, BehaviorPackage.TRANSITION__SOURCE, oldSource, newSource); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSource(State newSource) { if (newSource != source) { NotificationChain msgs = null; if (source != null) msgs = ((InternalEObject)source).eInverseRemove(this, BehaviorPackage.STATE__OUTGOING_TRANSITIONS, State.class, msgs); if (newSource != null) msgs = ((InternalEObject)newSource).eInverseAdd(this, BehaviorPackage.STATE__OUTGOING_TRANSITIONS, State.class, msgs); msgs = basicSetSource(newSource, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BehaviorPackage.TRANSITION__SOURCE, newSource, newSource)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public State getDestination() { if (destination != null && destination.eIsProxy()) { InternalEObject oldDestination = (InternalEObject)destination; destination = (State)eResolveProxy(oldDestination); if (destination != oldDestination) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, BehaviorPackage.TRANSITION__DESTINATION, oldDestination, destination)); } } return destination; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public State basicGetDestination() { return destination; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetDestination(State newDestination, NotificationChain msgs) { State oldDestination = destination; destination = newDestination; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, BehaviorPackage.TRANSITION__DESTINATION, oldDestination, newDestination); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDestination(State newDestination) { if (newDestination != destination) { NotificationChain msgs = null; if (destination != null) msgs = ((InternalEObject)destination).eInverseRemove(this, BehaviorPackage.STATE__INCOMING_TRANSITIONS, State.class, msgs); if (newDestination != null) msgs = ((InternalEObject)newDestination).eInverseAdd(this, BehaviorPackage.STATE__INCOMING_TRANSITIONS, State.class, msgs); msgs = basicSetDestination(newDestination, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BehaviorPackage.TRANSITION__DESTINATION, newDestination, newDestination)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case BehaviorPackage.TRANSITION__SOURCE: if (source != null) msgs = ((InternalEObject)source).eInverseRemove(this, BehaviorPackage.STATE__OUTGOING_TRANSITIONS, State.class, msgs); return basicSetSource((State)otherEnd, msgs); case BehaviorPackage.TRANSITION__DESTINATION: if (destination != null) msgs = ((InternalEObject)destination).eInverseRemove(this, BehaviorPackage.STATE__INCOMING_TRANSITIONS, State.class, msgs); return basicSetDestination((State)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 BehaviorPackage.TRANSITION__SOURCE: return basicSetSource(null, msgs); case BehaviorPackage.TRANSITION__DESTINATION: return basicSetDestination(null, 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 BehaviorPackage.TRANSITION__TRIGGER: return getTrigger(); case BehaviorPackage.TRANSITION__GUARD: return getGuard(); case BehaviorPackage.TRANSITION__EFFECT: return getEffect(); case BehaviorPackage.TRANSITION__SOURCE: if (resolve) return getSource(); return basicGetSource(); case BehaviorPackage.TRANSITION__DESTINATION: if (resolve) return getDestination(); return basicGetDestination(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case BehaviorPackage.TRANSITION__TRIGGER: setTrigger((String)newValue); return; case BehaviorPackage.TRANSITION__GUARD: setGuard((String)newValue); return; case BehaviorPackage.TRANSITION__EFFECT: setEffect((String)newValue); return; case BehaviorPackage.TRANSITION__SOURCE: setSource((State)newValue); return; case BehaviorPackage.TRANSITION__DESTINATION: setDestination((State)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case BehaviorPackage.TRANSITION__TRIGGER: setTrigger(TRIGGER_EDEFAULT); return; case BehaviorPackage.TRANSITION__GUARD: setGuard(GUARD_EDEFAULT); return; case BehaviorPackage.TRANSITION__EFFECT: setEffect(EFFECT_EDEFAULT); return; case BehaviorPackage.TRANSITION__SOURCE: setSource((State)null); return; case BehaviorPackage.TRANSITION__DESTINATION: setDestination((State)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case BehaviorPackage.TRANSITION__TRIGGER: return TRIGGER_EDEFAULT == null ? trigger != null : !TRIGGER_EDEFAULT.equals(trigger); case BehaviorPackage.TRANSITION__GUARD: return GUARD_EDEFAULT == null ? guard != null : !GUARD_EDEFAULT.equals(guard); case BehaviorPackage.TRANSITION__EFFECT: return EFFECT_EDEFAULT == null ? effect != null : !EFFECT_EDEFAULT.equals(effect); case BehaviorPackage.TRANSITION__SOURCE: return source != null; case BehaviorPackage.TRANSITION__DESTINATION: return destination != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (trigger: "); result.append(trigger); result.append(", guard: "); result.append(guard); result.append(", effect: "); result.append(effect); result.append(')'); return result.toString(); } } //TransitionImpl
epl-1.0
agoncal/core
bean-validation/tests/src/test/java/org/jboss/forge/addon/validation/ui/ValidationJDK8UITest.java
2264
/** * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.validation.ui; import java.util.List; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.forge.addon.ui.controller.CommandController; import org.jboss.forge.addon.ui.output.UIMessage; import org.jboss.forge.addon.ui.test.UITestHarness; import org.jboss.forge.arquillian.AddonDependencies; import org.jboss.forge.arquillian.AddonDependency; import org.jboss.forge.arquillian.archive.AddonArchive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author <a href="ggastald@redhat.com">George Gastaldi</a> */ @RunWith(Arquillian.class) @Ignore("HV-1022") public class ValidationJDK8UITest { @Deployment @AddonDependencies({ @AddonDependency(name = "org.jboss.forge.addon:bean-validation"), @AddonDependency(name = "org.jboss.forge.addon:ui-test-harness"), @AddonDependency(name = "org.jboss.forge.furnace.container:cdi") }) public static AddonArchive getDeployment() { AddonArchive archive = ShrinkWrap .create(AddonArchive.class) .addBeansXML() .addClass(ValidationJDK8Command.class) .addClass(NotFoo.class) .addClass(NotFooValidator.class); return archive; } @Inject UITestHarness testHarness; @Test public void testValidation() throws Exception { try (CommandController controller = testHarness.createCommandController(ValidationJDK8Command.class)) { controller.initialize(); controller.setValueFor("name", "Foo"); Assert.assertFalse("Controller should not be valid", controller.isValid()); List<UIMessage> messages = controller.validate(); Assert.assertEquals("An error should have been captured", 1, messages.size()); Assert.assertEquals("My Error Message", messages.get(0).getDescription()); } } }
epl-1.0
opendaylight/yangtools
codec/yang-data-codec-xml/src/main/java/org/opendaylight/yangtools/yang/data/codec/xml/NumberXmlCodec.java
852
/* * Copyright (c) 2016 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.yangtools.yang.data.codec.xml; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.opendaylight.yangtools.yang.data.impl.codec.DataStringCodec; final class NumberXmlCodec<T extends Number> extends AbstractXmlCodec<T> { NumberXmlCodec(final DataStringCodec<T> codec) { super(codec); } @Override public void writeValue(final XMLStreamWriter ctx, final T value) throws XMLStreamException { ctx.writeCharacters(String.valueOf(value)); } }
epl-1.0
gnuarmeclipse/plug-ins
plugins/ilg.gnumcueclipse.debug.gdbjtag/src/ilg/gnumcueclipse/debug/gdbjtag/viewmodel/peripheral/PeripheralPath.java
2243
/******************************************************************************* * Copyright (c) 2014 Liviu Ionescu. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Liviu Ionescu - initial version *******************************************************************************/ package ilg.gnumcueclipse.debug.gdbjtag.viewmodel.peripheral; public class PeripheralPath { // ------------------------------------------------------------------------ private String[] fSegments = null; // ------------------------------------------------------------------------ public PeripheralPath() { fSegments = new String[0]; } public PeripheralPath(PeripheralPath parentPath, PeripheralPath namePath) { String[] parentSegments = parentPath.getSegments(); String[] nameSegments = namePath.getSegments(); fSegments = new String[parentSegments.length + nameSegments.length]; System.arraycopy(parentSegments, 0, fSegments, 0, parentSegments.length); System.arraycopy(nameSegments, 0, fSegments, parentSegments.length, nameSegments.length); } public PeripheralPath(String name) { fSegments = new String[] { name }; } public PeripheralPath(String parent, String name) { fSegments = new String[] { parent, name }; } // ------------------------------------------------------------------------ private String[] getSegments() { return fSegments; } public String toPath() { return toStringBuilder().toString(); } public String toPath(boolean addSlash) { StringBuilder sb = toStringBuilder(); if (addSlash) { sb.append('/'); } return sb.toString(); } @Override public String toString() { return toPath(); } private StringBuilder toStringBuilder() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < fSegments.length; i++) if (fSegments[i] != null) { if (sb.length() != 0) { sb.append('.'); } sb.append(fSegments[i]); } return sb; } // ------------------------------------------------------------------------ }
epl-1.0