repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/storage/AbstractFastArrayStorageEngine.java
3159
/* * Copyright (c) 2018 Ahome' Innovation Technologies. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ait.lienzo.client.core.shape.storage; import com.ait.lienzo.client.core.shape.json.IJSONSerializable; import com.ait.lienzo.client.core.shape.json.validators.ValidationContext; import com.ait.lienzo.client.core.shape.json.validators.ValidationException; import com.ait.lienzo.client.core.types.BoundingBox; import com.ait.tooling.nativetools.client.collection.NFastArrayList; import com.google.gwt.json.client.JSONObject; public abstract class AbstractFastArrayStorageEngine<M> extends AbstractStorageEngine<M> { private final NFastArrayList<M> m_list = new NFastArrayList<>(); protected AbstractFastArrayStorageEngine(final StorageEngineType type) { super(type); } protected AbstractFastArrayStorageEngine(final StorageEngineType type, final JSONObject node, final ValidationContext ctx) throws ValidationException { super(type, node, ctx); } @Override public int size() { return m_list.size(); } @Override public boolean isEmpty() { return m_list.isEmpty(); } @Override public void clear() { m_list.clear(); } @Override public boolean contains(final M item) { return m_list.contains(item); } @Override public void add(final M item) { m_list.add(item); } @Override public void remove(final M item) { m_list.remove(item); } @Override public void refresh(final M item) { } @Override public void refresh() { } @Override public NFastArrayList<M> getChildren() { return m_list; } @Override public NFastArrayList<M> getChildren(final BoundingBox bounds) { return m_list; } @Override public boolean isSpatiallyIndexed() { return false; } @Override public void moveUp(final M item) { m_list.moveUp(item); } @Override public void moveDown(final M item) { m_list.moveDown(item); } @Override public void moveToTop(final M item) { m_list.moveToTop(item); } @Override public void moveToBottom(final M item) { m_list.moveToBottom(item); } public abstract static class FastArrayStorageEngineFactory<S extends IJSONSerializable<S>> extends AbstractStorageEngineFactory<S> { protected FastArrayStorageEngineFactory(final StorageEngineType type) { super(type); } } }
apache-2.0
lialun/uaparser
src/main/java/li/allan/UAData.java
5419
package li.allan; import li.allan.domain.*; import li.allan.json.FastJsonImpl; import li.allan.json.GsonImpl; import li.allan.json.JacksonImpl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; class UAData { private static UAData uaData; private UAData(String configPath) { try { String source = readFromResources(configPath); JSON_PACKAGE jsonPackage = findJsonPackage(); if (jsonPackage.equals(JSON_PACKAGE.FASTJSON)) { load(FastJsonImpl.parseData(source)); } else if (jsonPackage.equals(JSON_PACKAGE.JACKSON)) { load(JacksonImpl.parseData(source)); } else { load(GsonImpl.parseData(source)); } } catch (IOException e) { throw new RuntimeException("ERROR loading UAparser data file", e); } } private static UAData getInstance() { if (uaData == null) { uaData = new UAData("uaparser.json"); } return uaData; } public static Map<String[], UserAgent> getUserAgentMap() { return getInstance().userAgentMap; } public static Map<String[], OS> getOSMap() { return getInstance().OSMap; } public static Map<String, Map<String, Version>> getOSVersionAliasMap() { return getInstance().OSVersionAliasMap; } private Map<String[], UserAgent> userAgentMap;//Map<regex[], useragent> private Map<String[], OS> OSMap;//Map<regex[],os> private Map<String, Map<String, Version>> OSVersionAliasMap;//Map<osName, Map<versionRegex,Version>> private static String readFromResources(String path) throws IOException { InputStream inputStream = ClassLoader.getSystemResourceAsStream(path); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); int BUFFER_SIZE = 4096; byte[] data = new byte[BUFFER_SIZE]; int count; while ((count = inputStream.read(data, 0, BUFFER_SIZE)) != -1) { outStream.write(data, 0, count); } return new String(outStream.toByteArray(), "UTF-8"); } private void load(Map<String, List<Map<String, String>>> data) { //agentType Map<Integer, BrowserType> browserTypeMap = new HashMap<Integer, BrowserType>(); for (int i = 0; i < data.get("agentType").size(); i++) { Map<String, String> tmp = data.get("agentType").get(i); browserTypeMap.put(Integer.valueOf(tmp.get("id")), new BrowserType(Integer.valueOf(tmp.get("id")), tmp.get("name"))); } //agent userAgentMap = new LinkedHashMap<String[], UserAgent>(); for (int i = 0; i < data.get("agent").size(); i++) { Map<String, String> tmp = data.get("agent").get(i); String[] regexs = tmp.get("regex").toString().split("\\|\\|\\|\\|"); UserAgent b = new UserAgent(tmp.get("name"), browserTypeMap.get(tmp.get("type")), tmp.get("homepage")); userAgentMap.put(regexs, b); } //deviceType Map<Integer, DeviceType> deviceTypeMap = new HashMap<Integer, DeviceType>(); for (int i = 0; i < data.get("deviceType").size(); i++) { Map<String, String> tmp = data.get("deviceType").get(i); deviceTypeMap.put(Integer.valueOf(tmp.get("id")), new DeviceType(Integer.valueOf(tmp.get("id")), (String) tmp.get("name"))); } //OS OSMap = new LinkedHashMap<String[], OS>(); for (int i = 0; i < data.get("os").size(); i++) { Map<String, String> tmp = data.get("os").get(i); String[] regexs = tmp.get("regex").toString().split("\\|\\|\\|\\|"); OS os = new OS(tmp.get("name"), deviceTypeMap.get(tmp.get("deviceType"))); OSMap.put(regexs, os); } //OS version alias OSVersionAliasMap = new HashMap<String, Map<String, Version>>(); for (int i = 0; i < data.get("oSVersionAliases").size(); i++) { Map<String, String> tmp = data.get("oSVersionAliases").get(i); if (!OSVersionAliasMap.containsKey(tmp.get("os"))) { OSVersionAliasMap.put(tmp.get("os"), new HashMap<String, Version>()); } Version version = new Version(tmp.get("major"), tmp.get("minor"), tmp.get("revision")); OSVersionAliasMap.get(tmp.get("os")).put(tmp.get("regex"), version); } } /** * find the json parser package which has import * * @return * @throws ClassNotFoundException */ private JSON_PACKAGE findJsonPackage() { try { Class.forName("com.alibaba.fastjson.JSONObject"); return JSON_PACKAGE.FASTJSON; } catch (ClassNotFoundException e) { } try { Class.forName("com.fasterxml.jackson.databind.ObjectMapper"); return JSON_PACKAGE.JACKSON; } catch (ClassNotFoundException e) { } try { Class.forName("com.google.gson.Gson"); return JSON_PACKAGE.GSON; } catch (ClassNotFoundException e) { } throw new RuntimeException("you must import one of FastJson, Jackson2.x, Gson"); } enum JSON_PACKAGE { FASTJSON, JACKSON, GSON } }
apache-2.0
leonchen83/cool-lang
src/main/java/com/leon/cool/lang/tree/runtime/impl/EvalTreeScanner.java
15266
package com.leon.cool.lang.tree.runtime.impl; import com.leon.cool.lang.Constant; import com.leon.cool.lang.ast.Assign; import com.leon.cool.lang.ast.Blocks; import com.leon.cool.lang.ast.BoolConst; import com.leon.cool.lang.ast.Branch; import com.leon.cool.lang.ast.CaseDef; import com.leon.cool.lang.ast.Comp; import com.leon.cool.lang.ast.Cond; import com.leon.cool.lang.ast.Dispatch; import com.leon.cool.lang.ast.Divide; import com.leon.cool.lang.ast.IdConst; import com.leon.cool.lang.ast.IntConst; import com.leon.cool.lang.ast.IsVoid; import com.leon.cool.lang.ast.Let; import com.leon.cool.lang.ast.LetAttrDef; import com.leon.cool.lang.ast.Loop; import com.leon.cool.lang.ast.Lt; import com.leon.cool.lang.ast.LtEq; import com.leon.cool.lang.ast.Mul; import com.leon.cool.lang.ast.Neg; import com.leon.cool.lang.ast.NewDef; import com.leon.cool.lang.ast.NoExpression; import com.leon.cool.lang.ast.Not; import com.leon.cool.lang.ast.Paren; import com.leon.cool.lang.ast.Plus; import com.leon.cool.lang.ast.StaticDispatch; import com.leon.cool.lang.ast.StaticDispatchBody; import com.leon.cool.lang.ast.StringConst; import com.leon.cool.lang.ast.Sub; import com.leon.cool.lang.glossary.Out; import com.leon.cool.lang.object.CoolBool; import com.leon.cool.lang.object.CoolInt; import com.leon.cool.lang.object.CoolObject; import com.leon.cool.lang.object.CoolString; import com.leon.cool.lang.support.TreeSupport; import com.leon.cool.lang.support.declaration.MethodDeclaration; import com.leon.cool.lang.support.infrastructure.Context; import com.leon.cool.lang.tree.runtime.EvalTreeVisitor; import com.leon.cool.lang.type.Type; import com.leon.cool.lang.type.TypeEnum; import java.util.stream.Collectors; import static com.leon.cool.lang.factory.ObjectFactory.coolBool; import static com.leon.cool.lang.factory.ObjectFactory.coolBoolDefault; import static com.leon.cool.lang.factory.ObjectFactory.coolInt; import static com.leon.cool.lang.factory.ObjectFactory.coolIntDefault; import static com.leon.cool.lang.factory.ObjectFactory.coolString; import static com.leon.cool.lang.factory.ObjectFactory.coolStringDefault; import static com.leon.cool.lang.factory.ObjectFactory.coolVoid; import static com.leon.cool.lang.factory.TypeFactory.objectType; import static com.leon.cool.lang.support.ErrorSupport.error; import static com.leon.cool.lang.support.ErrorSupport.errorPos; import static com.leon.cool.lang.support.TypeSupport.isBasicType; import static com.leon.cool.lang.support.TypeSupport.isBoolType; import static com.leon.cool.lang.support.TypeSupport.isIntType; import static com.leon.cool.lang.support.TypeSupport.isSelfType; import static com.leon.cool.lang.support.TypeSupport.isStringType; /** * Copyright leon * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author leon on 16-3-27 */ public class EvalTreeScanner implements EvalTreeVisitor { protected TreeSupport treeSupport; public EvalTreeScanner(TreeSupport treeSupport) { this.treeSupport = treeSupport; } @Override public CoolObject applyAssign(Assign assign, @Out Context context) { var object = assign.expr.accept(this, context); context.environment.update(assign.id.tok.name, object); return object; } @Override public CoolObject applyBlocks(Blocks blocks, @Out Context context) { CoolObject object = coolVoid(); for (var expr : blocks.exprs) { object = expr.accept(this, context); } return object; } @Override public CoolObject applyNewDef(NewDef newDef, @Out Context context) { Type type; if (isSelfType(newDef.type)) { type = context.selfObject.type; } else { type = objectType(newDef.type.name); } return treeSupport.newDef(this, type, context); } @Override public CoolObject applyIsVoid(IsVoid isVoid, @Out Context context) { var object = isVoid.expr.accept(this, context); return coolBool(object.type.type() == TypeEnum.VOID); } @Override public CoolObject applyPlus(Plus plus, @Out Context context) { var l = (CoolInt) plus.left.accept(this, context); var r = (CoolInt) plus.right.accept(this, context); return coolInt(l.val + r.val); } @Override public CoolObject applySub(Sub sub, @Out Context context) { CoolInt l = (CoolInt) sub.left.accept(this, context); CoolInt r = (CoolInt) sub.right.accept(this, context); return coolInt(l.val - r.val); } @Override public CoolObject applyMul(Mul mul, @Out Context context) { var l = (CoolInt) mul.left.accept(this, context); var r = (CoolInt) mul.right.accept(this, context); return coolInt(l.val * r.val); } @Override public CoolObject applyDivide(Divide divide, @Out Context context) { var l = (CoolInt) divide.left.accept(this, context); var r = (CoolInt) divide.right.accept(this, context); if (r.val == 0) { error("runtime.error.divide.zero", errorPos(divide.right)); } return coolInt(l.val / r.val); } @Override public CoolObject applyNeg(Neg neg, @Out Context context) { var val = (CoolInt) neg.expr.accept(this, context); return coolInt(-val.val); } @Override public CoolObject applyLt(Lt lt, @Out Context context) { var l = (CoolInt) lt.left.accept(this, context); var r = (CoolInt) lt.right.accept(this, context); if (l.val < r.val) { return coolBool(true); } else { return coolBool(false); } } @Override public CoolObject applyLtEq(LtEq ltEq, @Out Context context) { var l = (CoolInt) ltEq.left.accept(this, context); var r = (CoolInt) ltEq.right.accept(this, context); if (l.val <= r.val) { return coolBool(true); } else { return coolBool(false); } } @Override public CoolObject applyComp(Comp comp, @Out Context context) { var l = comp.left.accept(this, context); var r = comp.right.accept(this, context); if (isBasicType(l.type) && isBasicType(r.type)) { if (l instanceof CoolString && r instanceof CoolString) { return coolBool(((CoolString) l).str.equals(((CoolString) r).str)); } else if (l instanceof CoolInt && r instanceof CoolInt) { return coolBool(((CoolInt) l).val == ((CoolInt) r).val); } else if (l instanceof CoolBool && r instanceof CoolBool) { return coolBool(((CoolBool) l).val == ((CoolBool) r).val); } else { throw new AssertionError("unexpected error."); } } else { return coolBool(l.equals(r)); } } @Override public CoolObject applyNot(Not not, @Out Context context) { var bool = (CoolBool) not.expr.accept(this, context); return coolBool(!bool.val); } @Override public CoolObject applyIdConst(IdConst idConst, @Out Context context) { if (idConst.tok.name.equals(Constant.SELF)) { return context.selfObject; } else { return context.environment.lookup(idConst.tok.name).get(); } } @Override public CoolObject applyStringConst(StringConst stringConst, @Out Context context) { return coolString(stringConst.tok.name); } @Override public CoolObject applyBoolConst(BoolConst boolConst, @Out Context context) { return coolBool(boolConst.bool); } @Override public CoolObject applyIntConst(IntConst intConst, @Out Context context) { return coolInt(Integer.parseInt(intConst.tok.name)); } @Override public CoolObject applyParen(Paren paren, @Out Context context) { return paren.expr.accept(this, context); } @Override public CoolObject applyNoExpression(NoExpression expr, @Out Context context) { return coolVoid(); } @Override public CoolObject applyDispatch(Dispatch dispatch, @Out Context context) { /** * 对方法调用的参数求值 */ var paramObjects = dispatch.params.stream().map(e -> e.accept(this, context)).collect(Collectors.toList()); /** * 对上述参数表达式求得类型 */ var paramTypes = paramObjects.stream().map(e -> e.type).collect(Collectors.toList()); var obj = context.selfObject; //根据类型,方法名称,类名lookup方法声明 var methodDeclaration = treeSupport.lookupMethodDeclaration(obj.type.className(), dispatch.id.name, paramTypes).get(); var str = treeSupport.buildIn(paramObjects, obj, methodDeclaration, errorPos(dispatch.starPos, dispatch.endPos)); if (str != null) return str; /** * 进入scope * */ context.environment.enterScope(); assert paramObjects.size() == methodDeclaration.declaration.formals.size(); /** * 绑定形参 */ for (var i = 0; i < methodDeclaration.declaration.formals.size(); i++) { context.environment.addId(methodDeclaration.declaration.formals.get(i).id.name, paramObjects.get(i)); } //对函数体求值 var object = methodDeclaration.declaration.expr.accept(this, context); /** * 退出scope */ context.environment.exitScope(); return object; } @Override public CoolObject applyStaticDispatchBody(StaticDispatchBody staticDispatchBody, @Out Context context) { return coolVoid(); } @Override public CoolObject applyStaticDispatch(StaticDispatch staticDispatch, @Out Context context) { /** * 对方法调用的参数求值 */ var paramObjects = staticDispatch.dispatch.params.stream().map(e -> e.accept(this, context)).collect(Collectors.toList()); /** * 对上述参数表达式求得类型 */ var paramTypes = paramObjects.stream().map(e -> e.type).collect(Collectors.toList()); MethodDeclaration methodDeclaration; // expr[@TYPE].ID( [ expr [[, expr]] ∗ ] )对第一个expr求值 var obj = staticDispatch.expr.accept(this, context); if (obj.type.type() == TypeEnum.VOID) { error("runtime.error.dispatch.void", errorPos(staticDispatch.expr)); } //如果提供type,则根据type查找方法声明 //如果没提供type,则根据上述expr值的类型查找方法声明 if (staticDispatch.type.isPresent()) { methodDeclaration = treeSupport.lookupMethodDeclaration(staticDispatch.type.get().name, staticDispatch.dispatch.id.name, paramTypes).get(); } else { methodDeclaration = treeSupport.lookupMethodDeclaration(obj.type.className(), staticDispatch.dispatch.id.name, paramTypes).get(); } var str = treeSupport.buildIn(paramObjects, obj, methodDeclaration, errorPos(staticDispatch.starPos, staticDispatch.endPos)); if (str != null) return str; /** * 进入scope,此scope是上述expr值对象的scope */ obj.variables.enterScope(); assert paramObjects.size() == methodDeclaration.declaration.formals.size(); /** * 绑定形参 */ for (var i = 0; i < methodDeclaration.declaration.formals.size(); i++) { obj.variables.addId(methodDeclaration.declaration.formals.get(i).id.name, paramObjects.get(i)); } //对函数体求值 var object = methodDeclaration.declaration.expr.accept(this, new Context(obj, obj.variables)); /** * 退出scope */ obj.variables.exitScope(); return object; } @Override public CoolObject applyCond(Cond cond, @Out Context context) { if (((CoolBool) cond.condExpr.accept(this, context)).val) { return cond.thenExpr.accept(this, context); } else { return cond.elseExpr.accept(this, context); } } @Override public CoolObject applyLoop(Loop loop, @Out Context context) { while (((CoolBool) loop.condExpr.accept(this, context)).val) { loop.loopExpr.accept(this, context); } return coolVoid(); } @Override public CoolObject applyLet(Let let, @Out Context context) { context.environment.enterScope(); let.attrDefs.forEach(e -> e.accept(this, context)); var object = let.expr.accept(this, context); context.environment.exitScope(); return object; } @Override public CoolObject applyCaseDef(CaseDef caseDef, @Out Context context) { var object = caseDef.caseExpr.accept(this, context); var temp = object.type.className(); while (temp != null) { final var filterStr = temp; var branchOpt = caseDef.branchList.stream().filter(e -> e.type.name.equals(filterStr)).findFirst(); if (branchOpt.isPresent()) { var branch = branchOpt.get(); context.environment.enterScope(); context.environment.addId(branch.id.name, object); var returnVal = branch.expr.accept(this, context); context.environment.exitScope(); if (returnVal.type.type() == TypeEnum.VOID) { error("runtime.error.void", errorPos(branch.expr)); } return returnVal; } temp = treeSupport.classGraph.get(temp); } error("runtime.error.case", errorPos(caseDef.starPos, caseDef.endPos)); return coolVoid(); } @Override public CoolObject applyBranch(Branch branch, @Out Context context) { return coolVoid(); } @Override public CoolObject applyLetAttrDef(LetAttrDef letAttrDef, @Out Context context) { if (letAttrDef.expr.isPresent()) { context.environment.addId(letAttrDef.id.name, letAttrDef.expr.get().accept(this, context)); } else { if (isStringType(letAttrDef.type)) { context.environment.addId(letAttrDef.id.name, coolStringDefault()); } else if (isIntType(letAttrDef.type)) { context.environment.addId(letAttrDef.id.name, coolIntDefault()); } else if (isBoolType(letAttrDef.type)) { context.environment.addId(letAttrDef.id.name, coolBoolDefault()); } else { context.environment.addId(letAttrDef.id.name, coolVoid()); } } return context.selfObject; } }
apache-2.0
Dmedina88/DaFlux
sample_complex/src/main/java/ui/DividerItemDecoration.java
3168
package ui; /** * Created by David on 12/5/2015. */ import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.view.ViewCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; public class DividerItemDecoration extends RecyclerView.ItemDecoration { public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; private static final int[] ATTRS = new int[] { android.R.attr.listDivider }; private Drawable mDivider; private int mOrientation; public DividerItemDecoration(Context context, int orientation) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); setOrientation(orientation); } public void setOrientation(int orientation) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw new IllegalArgumentException("invalid orientation"); } mOrientation = orientation; } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { if (mOrientation == VERTICAL_LIST) { drawVertical(c, parent, null); } else { drawHorizontal(c, parent); } } public void drawVertical(Canvas c, RecyclerView parent, RecyclerView.State state) { final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getBottom() + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child)); final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawHorizontal(Canvas c, RecyclerView parent) { final int top = parent.getPaddingTop(); final int bottom = parent.getHeight() - parent.getPaddingBottom(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int left = child.getRight() + params.rightMargin + Math.round(ViewCompat.getTranslationX(child)); final int right = left + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { if (mOrientation == VERTICAL_LIST) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } } }
apache-2.0
mbudiu-vmw/hiero
platform/src/test/java/org/hillview/test/table/TableDataSetTest.java
3507
/* * Copyright (c) 2018 VMware Inc. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hillview.test.table; import org.hillview.dataset.LocalDataSet; import org.hillview.dataset.ParallelDataSet; import org.hillview.dataset.api.IDataSet; import org.hillview.sketches.SampleQuantileSketch; import org.hillview.sketches.results.ColumnSortOrientation; import org.hillview.sketches.results.SampleList; import org.hillview.table.RecordOrder; import org.hillview.table.SmallTable; import org.hillview.table.api.ITable; import org.hillview.table.api.IndexComparator; import org.hillview.test.BaseTest; import org.hillview.utils.TestTables; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import static junit.framework.TestCase.assertTrue; public class TableDataSetTest extends BaseTest { @Test public void localDataSetTest() { int numCols = 3; int size = 1000, resolution = 20; SmallTable randTable = TestTables.getIntTable(size, numCols); RecordOrder cso = new RecordOrder(); for (String colName : randTable.getSchema().getColumnNames()) { cso.append(new ColumnSortOrientation(randTable.getSchema().getDescription(colName), true)); } SampleQuantileSketch sqSketch = new SampleQuantileSketch(cso, resolution, size, 0); LocalDataSet<ITable> ld = new LocalDataSet<ITable>(randTable); SampleList sl = ld.blockingSketch(sqSketch); Assert.assertNotNull(sl); IndexComparator comp = cso.getIndexComparator(sl.table); for (int i = 0; i < (sl.table.getNumOfRows() - 1); i++) assertTrue(comp.compare(i, i + 1) <= 0); //System.out.println(ql); } @Test public void parallelDataSetTest() { int numCols = 3; int size = 1000, resolution = 20; SmallTable randTable1 = TestTables.getIntTable(size, numCols); SmallTable randTable2 = TestTables.getIntTable(size, numCols); RecordOrder cso = new RecordOrder(); for (String colName : randTable1.getSchema().getColumnNames()) { cso.append(new ColumnSortOrientation(randTable1.getSchema().getDescription(colName), true)); } LocalDataSet<ITable> ld1 = new LocalDataSet<ITable>(randTable1); LocalDataSet<ITable> ld2 = new LocalDataSet<ITable>(randTable2); ArrayList<IDataSet<ITable>> elements = new ArrayList<IDataSet<ITable>>(2); elements.add(ld1); elements.add(ld2); ParallelDataSet<ITable> par = new ParallelDataSet<ITable>(elements); SampleQuantileSketch sqSketch = new SampleQuantileSketch(cso, resolution, size, 0); SampleList sl = par.blockingSketch(sqSketch); Assert.assertNotNull(sl); IndexComparator comp = cso.getIndexComparator(sl.table); for (int i = 0; i < (sl.table.getNumOfRows() - 1); i++) assertTrue(comp.compare(i, i + 1) <= 0); } }
apache-2.0
vital-ai/beaker-notebook
plugin/sqlsh/src/main/java/com/twosigma/beaker/sqlsh/utils/BeakerInputVar.java
3462
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twosigma.beaker.sqlsh.utils; public class BeakerInputVar { String fieldName; String objectName; String type; boolean array; boolean object; boolean all; int index; String errorMessage; public BeakerInputVar(String var) { int a = var.indexOf('['); int b = var.indexOf(']'); int dot = var.indexOf('.', b); if (a >= 0 && b > a) { if ((dot - b) > 1 || (dot < 1 && (var.length() - 1) > b)) { errorMessage = "expected token '.' after ']': " + var; return; } array = true; objectName = var.substring(0, a); String index = var.substring(a + 1, b); if (objectName.isEmpty()) { errorMessage = "unexpected token '[': " + var; return; } if (index.isEmpty()) { errorMessage = "index of array element should be defined: " + var; return; } if ("*".equals(index)) { all = true; } else { try { this.index = Integer.parseInt(index); } catch (NumberFormatException n) { errorMessage = "NumberFormatException in " + var + "; " + n.getMessage(); return; } } } else if (a > b && b >=0) { errorMessage = "unexpected token ']': " + var; return; } else if (a >= 0) { errorMessage = "unexpected token '[': " + var; return; } else if (b >= 0) { errorMessage = "unexpected token ']': " + var; return; } if (dot > 0) { object = true; fieldName = var.substring(dot + 1); if (fieldName.isEmpty()) { errorMessage = "unexpected token '.': " + var; return; } if (objectName == null) { objectName = var.substring(0, dot); } } if (objectName == null) objectName = var; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isArray() { return array; } public void setArray(boolean array) { this.array = array; } public boolean isObject() { return object; } public void setObject(boolean object) { this.object = object; } public boolean isAll() { return all; } public void setAll(boolean all) { this.all = all; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
apache-2.0
smee/gradoop
gradoop-common/src/test/java/org/gradoop/common/model/impl/properties/PropertyValueUtilsTest.java
34407
/* * Copyright © 2014 - 2018 Leipzig University (Database Research Group) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradoop.common.model.impl.properties; import org.junit.Test; import java.math.BigDecimal; import static org.gradoop.common.GradoopTestUtils.*; import static org.gradoop.common.model.impl.properties.PropertyValueUtils.Boolean.or; import static org.gradoop.common.model.impl.properties.PropertyValueUtils.Numeric.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.gradoop.common.model.impl.properties.PropertyValue.create; public class PropertyValueUtilsTest { @Test public void testOr() throws Exception { PropertyValue p; p = or(create(true), create(true)); assertTrue(p.isBoolean()); assertTrue(p.getBoolean()); p = or(create(true), create(false)); assertTrue(p.isBoolean()); assertTrue(p.getBoolean()); p = or(create(false), create(true)); assertTrue(p.isBoolean()); assertTrue(p.getBoolean()); p = or(create(false), create(false)); assertTrue(p.isBoolean()); assertFalse(p.getBoolean()); } @Test public void testAddReturningBigDecimal() throws Exception { PropertyValue p; // BigDecimal p = add(create(BIG_DECIMAL_VAL_7), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.add(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // double p = add(create(BIG_DECIMAL_VAL_7), create(DOUBLE_VAL_5)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.add(BigDecimal.valueOf(DOUBLE_VAL_5)).compareTo(p.getBigDecimal()), 0); p = add(create(DOUBLE_VAL_5), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(DOUBLE_VAL_5)).add(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // float p = add(create(BIG_DECIMAL_VAL_7), create(FLOAT_VAL_4)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.add(BigDecimal.valueOf(FLOAT_VAL_4)).compareTo(p.getBigDecimal()), 0); p = add(create(FLOAT_VAL_4), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(FLOAT_VAL_4)).add(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // long p = add(create(BIG_DECIMAL_VAL_7), create(LONG_VAL_3)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.add(BigDecimal.valueOf(LONG_VAL_3)).compareTo(p.getBigDecimal()), 0); p = add(create(LONG_VAL_3), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(LONG_VAL_3)).add(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // int p = add(create(BIG_DECIMAL_VAL_7), create(INT_VAL_2)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.add(BigDecimal.valueOf(INT_VAL_2)).compareTo(p.getBigDecimal()), 0); p = add(create(INT_VAL_2), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(INT_VAL_2)).add(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // short p = add(create(BIG_DECIMAL_VAL_7), create(SHORT_VAL_e)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.add(BigDecimal.valueOf(SHORT_VAL_e)).compareTo(p.getBigDecimal()), 0); p = add(create(SHORT_VAL_e), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(SHORT_VAL_e)).add(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); } @Test public void testAddReturningDouble() { PropertyValue p; // double p = add(create(DOUBLE_VAL_5), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 + DOUBLE_VAL_5, p.getDouble(), 0); // float p = add(create(DOUBLE_VAL_5), create(FLOAT_VAL_4)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 + FLOAT_VAL_4, p.getDouble(), 0); p = add(create(FLOAT_VAL_4), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(FLOAT_VAL_4 + DOUBLE_VAL_5, p.getDouble(), 0); // long p = add(create(DOUBLE_VAL_5), create(LONG_VAL_3)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 + LONG_VAL_3, p.getDouble(), 0); p = add(create(LONG_VAL_3), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(LONG_VAL_3 + DOUBLE_VAL_5, p.getDouble(), 0); // int p = add(create(DOUBLE_VAL_5), create(INT_VAL_2)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 + INT_VAL_2, p.getDouble(), 0); p = add(create(INT_VAL_2), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(INT_VAL_2 + DOUBLE_VAL_5, p.getDouble(), 0); // short p = add(create(DOUBLE_VAL_5), create(SHORT_VAL_e)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 + SHORT_VAL_e, p.getDouble(), 0); p = add(create(SHORT_VAL_e), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(SHORT_VAL_e + DOUBLE_VAL_5, p.getDouble(), 0); } @Test public void testAddReturningFloat() { PropertyValue p; // float p = add(create(FLOAT_VAL_4), create(FLOAT_VAL_4)); assertTrue(p.isFloat()); assertEquals(FLOAT_VAL_4 + FLOAT_VAL_4, p.getFloat(), 0); // long p = add(create(FLOAT_VAL_4), create(LONG_VAL_3)); assertTrue(p.isFloat()); assertEquals(FLOAT_VAL_4 + LONG_VAL_3, p.getFloat(), 0); p = add(create(LONG_VAL_3), create(FLOAT_VAL_4)); assertTrue(p.isFloat()); assertEquals(LONG_VAL_3 + FLOAT_VAL_4, p.getFloat(), 0); // int p = add(create(FLOAT_VAL_4), create(INT_VAL_2)); assertTrue(p.isFloat()); assertEquals(FLOAT_VAL_4 + INT_VAL_2, p.getFloat(), 0); p = add(create(INT_VAL_2), create(FLOAT_VAL_4)); assertTrue(p.isFloat()); assertEquals(INT_VAL_2 + FLOAT_VAL_4, p.getFloat(), 0); // short p = add(create(FLOAT_VAL_4), create(SHORT_VAL_e)); assertTrue(p.isFloat()); assertEquals(FLOAT_VAL_4 + SHORT_VAL_e, p.getFloat(), 0); p = add(create(SHORT_VAL_e), create(FLOAT_VAL_4)); assertTrue(p.isFloat()); assertEquals(SHORT_VAL_e + FLOAT_VAL_4, p.getFloat(), 0); } @Test public void testAddReturningLong() { PropertyValue p; // long p = add(create(LONG_VAL_3), create(LONG_VAL_3)); assertTrue(p.isLong()); assertEquals(LONG_VAL_3 + LONG_VAL_3, p.getLong(), 0); // int p = add(create(LONG_VAL_3), create(INT_VAL_2)); assertTrue(p.isLong()); assertEquals(LONG_VAL_3 + INT_VAL_2, p.getLong(), 0); p = add(create(INT_VAL_2), create(LONG_VAL_3)); assertTrue(p.isLong()); assertEquals(INT_VAL_2 + LONG_VAL_3, p.getLong(), 0); // short p = add(create(LONG_VAL_3), create(SHORT_VAL_e)); assertTrue(p.isLong()); assertEquals(LONG_VAL_3 + SHORT_VAL_e, p.getLong(), 0); p = add(create(SHORT_VAL_e), create(LONG_VAL_3)); assertTrue(p.isLong()); assertEquals(SHORT_VAL_e + LONG_VAL_3, p.getLong(), 0); } @Test public void testAddReturningInteger() { PropertyValue p; // int p = add(create(INT_VAL_2), create(INT_VAL_2)); assertTrue(p.isInt()); assertEquals(INT_VAL_2 + INT_VAL_2, p.getInt(), 0); // short p = add(create(INT_VAL_2), create(SHORT_VAL_e)); assertTrue(p.isInt()); assertEquals(INT_VAL_2 + SHORT_VAL_e, p.getInt(), 0); p = add(create(SHORT_VAL_e), create(INT_VAL_2)); assertTrue(p.isInt()); assertEquals(SHORT_VAL_e + INT_VAL_2, p.getInt(), 0); p = add(create(SHORT_VAL_e), create(SHORT_VAL_e)); assertTrue(p.isInt()); assertEquals(SHORT_VAL_e + SHORT_VAL_e, p.getInt(), 0); } @Test public void testMultiplyReturningBigDecimal() throws Exception { PropertyValue p; // BigDecimal p = multiply(create(BIG_DECIMAL_VAL_7), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.multiply(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // double p = multiply(create(BIG_DECIMAL_VAL_7), create(DOUBLE_VAL_5)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.multiply(BigDecimal.valueOf(DOUBLE_VAL_5)).compareTo(p.getBigDecimal()), 0); p = multiply(create(DOUBLE_VAL_5), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(DOUBLE_VAL_5)).multiply(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // float p = multiply(create(BIG_DECIMAL_VAL_7), create(FLOAT_VAL_4)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.multiply(BigDecimal.valueOf(FLOAT_VAL_4)).compareTo(p.getBigDecimal()), 0); p = multiply(create(FLOAT_VAL_4), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(FLOAT_VAL_4)).multiply(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // long p = multiply(create(BIG_DECIMAL_VAL_7), create(LONG_VAL_3)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.multiply(BigDecimal.valueOf(LONG_VAL_3)).compareTo(p.getBigDecimal()), 0); p = multiply(create(LONG_VAL_3), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(LONG_VAL_3)).multiply(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // int p = multiply(create(BIG_DECIMAL_VAL_7), create(INT_VAL_2)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.multiply(BigDecimal.valueOf(INT_VAL_2)).compareTo(p.getBigDecimal()), 0); p = multiply(create(INT_VAL_2), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(INT_VAL_2)).multiply(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); // short p = multiply(create(BIG_DECIMAL_VAL_7), create(SHORT_VAL_e)); assertTrue(p.isBigDecimal()); assertEquals(BIG_DECIMAL_VAL_7.multiply(BigDecimal.valueOf(SHORT_VAL_e)).compareTo(p.getBigDecimal()), 0); p = multiply(create(SHORT_VAL_e), create(BIG_DECIMAL_VAL_7)); assertTrue(p.isBigDecimal()); assertEquals((BigDecimal.valueOf(SHORT_VAL_e)).multiply(BIG_DECIMAL_VAL_7).compareTo(p.getBigDecimal()), 0); } @Test public void testMultiplyReturningDouble() { PropertyValue p; // double p = multiply(create(DOUBLE_VAL_5), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 * DOUBLE_VAL_5, p.getDouble(), 0); // float p = multiply(create(DOUBLE_VAL_5), create(FLOAT_VAL_4)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 * FLOAT_VAL_4, p.getDouble(), 0); p = multiply(create(FLOAT_VAL_4), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(FLOAT_VAL_4 * DOUBLE_VAL_5, p.getDouble(), 0); // long p = multiply(create(DOUBLE_VAL_5), create(LONG_VAL_3)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 * LONG_VAL_3, p.getDouble(), 0); p = multiply(create(LONG_VAL_3), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(LONG_VAL_3 * DOUBLE_VAL_5, p.getDouble(), 0); // int p = multiply(create(DOUBLE_VAL_5), create(INT_VAL_2)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 * INT_VAL_2, p.getDouble(), 0); p = multiply(create(INT_VAL_2), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(INT_VAL_2 * DOUBLE_VAL_5, p.getDouble(), 0); // short p = multiply(create(DOUBLE_VAL_5), create(SHORT_VAL_e)); assertTrue(p.isDouble()); assertEquals(DOUBLE_VAL_5 * SHORT_VAL_e, p.getDouble(), 0); p = multiply(create(SHORT_VAL_e), create(DOUBLE_VAL_5)); assertTrue(p.isDouble()); assertEquals(SHORT_VAL_e * DOUBLE_VAL_5, p.getDouble(), 0); } @Test public void testMultiplyReturningFloat() { PropertyValue p; // float p = multiply(create(FLOAT_VAL_4), create(FLOAT_VAL_4)); assertTrue(p.isFloat()); assertEquals(FLOAT_VAL_4 * FLOAT_VAL_4, p.getFloat(), 0); // long p = multiply(create(FLOAT_VAL_4), create(LONG_VAL_3)); assertTrue(p.isFloat()); assertEquals(FLOAT_VAL_4 * LONG_VAL_3, p.getFloat(), 0); p = multiply(create(LONG_VAL_3), create(FLOAT_VAL_4)); assertTrue(p.isFloat()); assertEquals(LONG_VAL_3 * FLOAT_VAL_4, p.getFloat(), 0); // int p = multiply(create(FLOAT_VAL_4), create(INT_VAL_2)); assertTrue(p.isFloat()); assertEquals(FLOAT_VAL_4 * INT_VAL_2, p.getFloat(), 0); p = multiply(create(INT_VAL_2), create(FLOAT_VAL_4)); assertTrue(p.isFloat()); assertEquals(INT_VAL_2 * FLOAT_VAL_4, p.getFloat(), 0); // short p = multiply(create(FLOAT_VAL_4), create(SHORT_VAL_e)); assertTrue(p.isFloat()); assertEquals(FLOAT_VAL_4 * SHORT_VAL_e, p.getFloat(), 0); p = multiply(create(SHORT_VAL_e), create(FLOAT_VAL_4)); assertTrue(p.isFloat()); assertEquals(SHORT_VAL_e * FLOAT_VAL_4, p.getFloat(), 0); } @Test public void testMultiplyReturningLong() { PropertyValue p; // long p = multiply(create(LONG_VAL_3), create(LONG_VAL_3)); assertTrue(p.isLong()); assertEquals(LONG_VAL_3 * LONG_VAL_3, p.getLong(), 0); // int p = multiply(create(LONG_VAL_3), create(INT_VAL_2)); assertTrue(p.isLong()); assertEquals(LONG_VAL_3 * INT_VAL_2, p.getLong(), 0); p = multiply(create(INT_VAL_2), create(LONG_VAL_3)); assertTrue(p.isLong()); assertEquals(INT_VAL_2 * LONG_VAL_3, p.getLong(), 0); // short p = multiply(create(LONG_VAL_3), create(SHORT_VAL_e)); assertTrue(p.isLong()); assertEquals(LONG_VAL_3 * SHORT_VAL_e, p.getLong(), 0); p = multiply(create(SHORT_VAL_e), create(LONG_VAL_3)); assertTrue(p.isLong()); assertEquals(SHORT_VAL_e * LONG_VAL_3, p.getLong(), 0); } @Test public void testMultiplyReturningInteger() { PropertyValue p; // int p = multiply(create(INT_VAL_2), create(INT_VAL_2)); assertTrue(p.isInt()); assertEquals(INT_VAL_2 * INT_VAL_2, p.getInt(), 0); // short p = multiply(create(INT_VAL_2), create(SHORT_VAL_e)); assertTrue(p.isInt()); assertEquals(INT_VAL_2 * SHORT_VAL_e, p.getInt(), 0); p = multiply(create(SHORT_VAL_e), create(INT_VAL_2)); assertTrue(p.isInt()); assertEquals(SHORT_VAL_e * INT_VAL_2, p.getInt(), 0); p = multiply(create(SHORT_VAL_e), create(SHORT_VAL_e)); assertTrue(p.isInt()); assertEquals(SHORT_VAL_e * SHORT_VAL_e, p.getInt(), 0); } @Test public void testMin() throws Exception { PropertyValue p; BigDecimal minBigDecimal = new BigDecimal("10"); BigDecimal maxBigDecimal = new BigDecimal("11"); double minDouble = 10d; double maxDouble = 11d; float minFloat = 10f; float maxFloat = 11f; long minLong = 10L; long maxLong = 11L; int minInt = 10; int maxInt = 11; short minShort = (short)10; short maxShort = (short)11; // MIN BigDecimal p = min(create(minBigDecimal), create(maxBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(maxBigDecimal), create(minBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(minBigDecimal), create(maxDouble)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(maxDouble), create(minBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(minBigDecimal), create(maxFloat)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(maxFloat), create(minBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(minBigDecimal), create(maxLong)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(maxLong), create(minBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(minBigDecimal), create(maxInt)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(maxInt), create(minBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(minBigDecimal), create(maxShort)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); p = min(create(maxShort), create(minBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(minBigDecimal), 0); // MIN Double p = min(create(minDouble), create(maxBigDecimal)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(maxBigDecimal), create(minDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(minDouble), create(maxDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(maxDouble), create(minDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(minDouble), create(maxFloat)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(maxFloat), create(minDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(minDouble), create(maxLong)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(maxLong), create(minDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(minDouble), create(maxInt)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(maxInt), create(minDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(minDouble), create(maxShort)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); p = min(create(maxShort), create(minDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), minDouble, 0); // MIN Float p = min(create(minFloat), create(maxBigDecimal)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(maxBigDecimal), create(minFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(minFloat), create(maxDouble)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(maxDouble), create(minFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(minFloat), create(maxFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(maxFloat), create(minFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(minFloat), create(maxLong)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(maxLong), create(minFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(minFloat), create(maxInt)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(maxInt), create(minFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(minFloat), create(maxShort)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); p = min(create(maxShort), create(minFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), minFloat, 0); // MIN Long p = min(create(minLong), create(maxBigDecimal)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(maxBigDecimal), create(minLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(minLong), create(maxDouble)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(maxDouble), create(minLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(minLong), create(maxFloat)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(maxFloat), create(minLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(minLong), create(maxLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(maxLong), create(minLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(minLong), create(maxInt)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(maxInt), create(minLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(minLong), create(maxShort)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); p = min(create(maxShort), create(minLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), minLong, 0); // MIN Int p = min(create(minInt), create(maxBigDecimal)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(maxBigDecimal), create(minInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(minInt), create(maxDouble)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(maxDouble), create(minInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(minInt), create(maxFloat)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(maxFloat), create(minInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(minInt), create(maxLong)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(maxLong), create(minInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(minInt), create(maxInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(maxInt), create(minInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(minInt), create(maxShort)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); p = min(create(maxShort), create(minInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), minInt, 0); // MIN Short p = min(create(minShort), create(maxBigDecimal)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(maxBigDecimal), create(minShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(minShort), create(maxDouble)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(maxDouble), create(minShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(minShort), create(maxFloat)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(maxFloat), create(minShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(minShort), create(maxLong)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(maxLong), create(minShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(minShort), create(maxInt)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(maxInt), create(minShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(minShort), create(maxShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); p = min(create(maxShort), create(minShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), minShort, 0); } @Test public void testMax() throws Exception { PropertyValue p; BigDecimal minBigDecimal = new BigDecimal("10"); BigDecimal maxBigDecimal = new BigDecimal("11"); double minDouble = 10d; double maxDouble = 11d; float minFloat = 10f; float maxFloat = 11f; long minLong = 10L; long maxLong = 11L; int minInt = 10; int maxInt = 11; short minShort = (short)10; short maxShort = (short)11; // MAX BigDecimal p = max(create(maxBigDecimal), create(minBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(minBigDecimal), create(maxBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(maxBigDecimal), create(minDouble)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(minDouble), create(maxBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(maxBigDecimal), create(minFloat)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(minFloat), create(maxBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(maxBigDecimal), create(minLong)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(minLong), create(maxBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(maxBigDecimal), create(minInt)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(minInt), create(maxBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(maxBigDecimal), create(minShort)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); p = max(create(minShort), create(maxBigDecimal)); assertTrue(p.isBigDecimal()); assertEquals(p.getBigDecimal().compareTo(maxBigDecimal), 0); // MAX Double p = max(create(maxDouble), create(minBigDecimal)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(minBigDecimal), create(maxDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(maxDouble), create(minDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(minDouble), create(maxDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(maxDouble), create(minFloat)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(minFloat), create(maxDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(maxDouble), create(minLong)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(minLong), create(maxDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(maxDouble), create(minInt)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(minInt), create(maxDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(maxDouble), create(minShort)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); p = max(create(minShort), create(maxDouble)); assertTrue(p.isDouble()); assertEquals(p.getDouble(), maxDouble, 0); // MAX Float p = max(create(maxFloat), create(minBigDecimal)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(minBigDecimal), create(maxFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(maxFloat), create(minDouble)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(minDouble), create(maxFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(maxFloat), create(minFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(minFloat), create(maxFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(maxFloat), create(minLong)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(minLong), create(maxFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(maxFloat), create(minInt)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(minInt), create(maxFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(maxFloat), create(minShort)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); p = max(create(minShort), create(maxFloat)); assertTrue(p.isFloat()); assertEquals(p.getFloat(), maxFloat, 0); // MAX Long p = max(create(maxLong), create(minBigDecimal)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(minBigDecimal), create(maxLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(maxLong), create(minDouble)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(minDouble), create(maxLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(maxLong), create(minFloat)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(minFloat), create(maxLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(maxLong), create(minLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(minLong), create(maxLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(maxLong), create(minInt)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(minInt), create(maxLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(maxLong), create(minShort)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); p = max(create(minShort), create(maxLong)); assertTrue(p.isLong()); assertEquals(p.getLong(), maxLong, 0); // MAX Int p = max(create(maxInt), create(minBigDecimal)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(minBigDecimal), create(maxInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(maxInt), create(minDouble)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(minDouble), create(maxInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(maxInt), create(minFloat)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(minFloat), create(maxInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(maxInt), create(minLong)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(minLong), create(maxInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(maxInt), create(minInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(minInt), create(maxInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(maxInt), create(minShort)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); p = max(create(minShort), create(maxInt)); assertTrue(p.isInt()); assertEquals(p.getInt(), maxInt, 0); // MAX Short p = max(create(maxShort), create(minBigDecimal)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(minBigDecimal), create(maxShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(maxShort), create(minDouble)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(minDouble), create(maxShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(maxShort), create(minFloat)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(minFloat), create(maxShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(maxShort), create(minLong)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(minLong), create(maxShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(maxShort), create(minInt)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(minInt), create(maxShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(maxShort), create(minShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); p = max(create(minShort), create(maxShort)); assertTrue(p.isShort()); assertEquals(p.getShort(), maxShort, 0); } }
apache-2.0
cocoatomo/asakusafw
utils-project/java-dom/src/main/java/com/asakusafw/utils/java/model/syntax/UnaryOperator.java
3531
/** * Copyright 2011-2017 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.utils.java.model.syntax; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Represents unary operators. */ public enum UnaryOperator { /** * Unary plus. */ PLUS("+", Category.ARITHMETIC), //$NON-NLS-1$ /** * Unary minus. */ MINUS("-", Category.ARITHMETIC), //$NON-NLS-1$ /** * Bit complement. */ COMPLEMENT("~", Category.BITWISE), //$NON-NLS-1$ /** * Logical not. */ NOT("!", Category.LOGICAL), //$NON-NLS-1$ /** * Prefix increment. */ INCREMENT("++", Category.INCREMENT_DECREMENT), //$NON-NLS-1$ /** * Prefix decrement. */ DECREMENT("--", Category.INCREMENT_DECREMENT), //$NON-NLS-1$ ; private final String symbol; private final Category category; /** * Creates a new instance. * @param symbol the operator symbol * @param category the operator category */ UnaryOperator(String symbol, Category category) { assert symbol != null; assert category != null; this.symbol = symbol; this.category = category; } /** * Returns the operator symbol. * @return the operator symbol */ public String getSymbol() { return this.symbol; } /** * Returns the operator category. * @return the operator category */ public Category getCategory() { return category; } /** * Returns an operator from its symbol. * @param symbol the target operator symbol * @return the corresponded operator, or {@code null} if there is no such the operator * @throws IllegalArgumentException if the parameter is {@code null} */ public static UnaryOperator fromSymbol(String symbol) { if (symbol == null) { throw new IllegalArgumentException("symbol must not be null"); //$NON-NLS-1$ } return SymbolToUnaryOperator.get(symbol); } /** * Represents an operator kind. */ public enum Category { /** * Prefix increment/decrement. */ INCREMENT_DECREMENT, /** * Arithmetic operations. */ ARITHMETIC, /** * Bitwise operations. */ BITWISE, /** * Logical operations. */ LOGICAL, } private static class SymbolToUnaryOperator { private static final Map<String, UnaryOperator> REVERSE_DICTIONARY; static { Map<String, UnaryOperator> map = new HashMap<>(); for (UnaryOperator elem : UnaryOperator.values()) { map.put(elem.getSymbol(), elem); } REVERSE_DICTIONARY = Collections.unmodifiableMap(map); } static UnaryOperator get(String key) { return REVERSE_DICTIONARY.get(key); } } }
apache-2.0
kubernetes-client/java
client-java-contrib/prometheus-operator/src/main/java/com/coreos/monitoring/models/V1ThanosRulerSpecProjectedDownwardAPI.java
3148
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.coreos.monitoring.models; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** information about the downwardAPI data to project */ @ApiModel(description = "information about the downwardAPI data to project") @javax.annotation.Generated( value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-08-31T19:41:55.826Z[Etc/UTC]") public class V1ThanosRulerSpecProjectedDownwardAPI { public static final String SERIALIZED_NAME_ITEMS = "items"; @SerializedName(SERIALIZED_NAME_ITEMS) private List<V1ThanosRulerSpecDownwardAPIItems> items = null; public V1ThanosRulerSpecProjectedDownwardAPI items( List<V1ThanosRulerSpecDownwardAPIItems> items) { this.items = items; return this; } public V1ThanosRulerSpecProjectedDownwardAPI addItemsItem( V1ThanosRulerSpecDownwardAPIItems itemsItem) { if (this.items == null) { this.items = new ArrayList<V1ThanosRulerSpecDownwardAPIItems>(); } this.items.add(itemsItem); return this; } /** * Items is a list of DownwardAPIVolume file * * @return items */ @javax.annotation.Nullable @ApiModelProperty(value = "Items is a list of DownwardAPIVolume file") public List<V1ThanosRulerSpecDownwardAPIItems> getItems() { return items; } public void setItems(List<V1ThanosRulerSpecDownwardAPIItems> items) { this.items = items; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } V1ThanosRulerSpecProjectedDownwardAPI v1ThanosRulerSpecProjectedDownwardAPI = (V1ThanosRulerSpecProjectedDownwardAPI) o; return Objects.equals(this.items, v1ThanosRulerSpecProjectedDownwardAPI.items); } @Override public int hashCode() { return Objects.hash(items); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class V1ThanosRulerSpecProjectedDownwardAPI {\n"); sb.append(" items: ").append(toIndentedString(items)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
apache-2.0
anjlab/eclipse-tapestry5-plugin
com.anjlab.eclipse.tapestry5/src/com/anjlab/eclipse/tapestry5/JarTapestryContext.java
7212
package com.anjlab.eclipse.tapestry5; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJarEntryResource; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.WorkingCopyOwner; import com.anjlab.eclipse.tapestry5.internal.CompilationUnitContext.CompilationUnitLifecycle; public class JarTapestryContext extends TapestryContext { public JarTapestryContext(IJarEntryResource jarEntry) { initFromFile(new JarEntryFile(this, jarEntry)); } public JarTapestryContext(IClassFile classFile) { initFromFile(new ClassFile(this, classFile)); } @Override protected CompilationUnitLifecycle getCompilationUnit() { return new CompilationUnitLifecycle() { @Override public ICompilationUnit createCompilationUnit() { TapestryFile javaFile = getJavaFile(); if (javaFile instanceof ClassFile && javaFile.exists()) { IClassFile classFile = ((ClassFile) javaFile).getClassFile(); try { return classFile.getWorkingCopy(new WorkingCopyOwner() { }, new NullProgressMonitor()); } catch (JavaModelException e) { Activator.getDefault().logError("Error getting compilation unit", e); } } return null; } @Override public void dispose(ICompilationUnit compilationUnit) { try { compilationUnit.discardWorkingCopy(); } catch (JavaModelException e) { // Ignore } } }; } @Override public String getPackageName() { TapestryFile javaFile = getJavaFile(); return (javaFile instanceof ClassFile) ? ((ClassFile) javaFile).getClassFile().getParent().getElementName() : "unknown"; } @Override public List<TapestryFile> findTapestryFiles(TapestryFile forFile, boolean findFirst, FileNameBuilder fileNameBuilder) { List<TapestryFile> files = new ArrayList<TapestryFile>(); IPackageFragment pkg = null; if (forFile instanceof ClassFile) { IJavaElement parent = ((ClassFile) forFile).getClassFile().getParent(); if (parent instanceof IPackageFragment) { pkg = (IPackageFragment) parent; } } else if (forFile instanceof JarEntryFile) { Object parent = ((JarEntryFile) forFile).getJarEntry().getParent(); if (parent instanceof IPackageFragment) { pkg = (IPackageFragment) parent; } } if (pkg != null) { try { String fileName = fileNameBuilder.getFileName(forFile.getName(), forFile.getFileExtension()); if (fileName.endsWith(".class")) { IClassFile classFile = pkg.getClassFile(fileName); if (classFile != null) { files.add(new ClassFile(this, classFile)); if (findFirst) { return files; } } } else { Object[] resources = pkg.getNonJavaResources(); for (Object resource : resources) { if (resource instanceof IJarEntryResource) { IJarEntryResource jarEntry = (IJarEntryResource) resource; boolean matches = false; if (fileName.contains("*")) { matches = Pattern.matches(fileName, jarEntry.getName()); } matches = matches || fileName.equals(jarEntry.getName()); if (matches) { files.add(new JarEntryFile(this, jarEntry)); if (findFirst) { return files; } } } } TapestryFile file = createLookup().findClasspathFileCaseInsensitive(fileName); if (file != null) { files.add(file); if (findFirst) { return files; } } } } catch (JavaModelException e) { // Ignore } } return files; } protected Map<String, String> codeDesignExtensionMappings() { Map<String, String> result = new HashMap<String, String>(); result.put("tml", "class"); result.put("class", "tml"); return result; } @Override public boolean isReadOnly() { return true; } private TapestryComponentSpecification specification; @Override public TapestryComponentSpecification getSpecification() { if (specification == null) { IType type = getJavaType(); if (type == null) { return TapestryComponentSpecification.EMPTY; } specification = new TapestryComponentSpecification(type, this); } return specification; } @Override public IType getJavaType() { TapestryFile javaFile = getJavaFile(); if (javaFile == null) { return null; } IType type = ((ClassFile)javaFile).getClassFile().findPrimaryType(); return type; } @Override public FileLookup createLookup() { return new JarFileLookup(getJavaType()); } }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Framework/Docking/src/main/java/docking/resources/icons/NumberIcon.java
3307
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking.resources.icons; import java.awt.*; import java.awt.geom.Rectangle2D; import javax.swing.Icon; import javax.swing.JComponent; import docking.util.GraphicsUtils; /** * An icon that paints the given number */ public class NumberIcon implements Icon { private String number; private float bestFontSize = -1; public NumberIcon(int number) { this.number = Integer.toString(number); } public void setNumber(int number) { this.number = Integer.toString(number); bestFontSize = -1; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(Color.WHITE); g.fillRect(x, y, getIconWidth(), getIconHeight()); g.setColor(new Color(0xb5d5ff)); g.drawRect(x, y, getIconWidth(), getIconHeight()); float fontSize = getMaxFontSize(g, getIconWidth() - 1, getIconHeight()); Font originalFont = g.getFont(); Font textFont = originalFont.deriveFont(fontSize).deriveFont(Font.BOLD); g.setFont(textFont); FontMetrics fontMetrics = g.getFontMetrics(textFont); Rectangle2D stringBounds = fontMetrics.getStringBounds(number, g); int textHeight = (int) stringBounds.getHeight(); int iconHeight = getIconHeight(); int space = y + iconHeight - textHeight; int halfSpace = space >> 1; int baselineY = y + iconHeight - halfSpace;// - halfTextHeight;// + halfTextHeight; int textWidth = (int) stringBounds.getWidth(); int iconWidth = getIconWidth(); int halfWidth = iconWidth >> 1; int halfTextWidth = textWidth >> 1; int baselineX = x + (halfWidth - halfTextWidth); g.setColor(Color.BLACK); JComponent jc = null; if (c instanceof JComponent) { jc = (JComponent) c; } GraphicsUtils.drawString(jc, g, number, baselineX, baselineY); } private float getMaxFontSize(Graphics g, int width, int height) { if (bestFontSize > 0) { return bestFontSize; } float size = 12f; Font font = g.getFont().deriveFont(size); // reasonable default if (textFitsInFont(g, font, width, height)) { bestFontSize = size; return bestFontSize; } do { size--; font = g.getFont().deriveFont(size); } while (!textFitsInFont(g, font, width, height)); bestFontSize = Math.max(1f, size); return bestFontSize; } private boolean textFitsInFont(Graphics g, Font font, int width, int height) { // padding so the text does not touch the border int padding = 2; FontMetrics fontMetrics = g.getFontMetrics(font); int textWidth = fontMetrics.stringWidth(number) + padding; if (textWidth > width) { return false; } int textHeight = fontMetrics.getHeight(); return textHeight < height; } @Override public int getIconHeight() { return 16; } @Override public int getIconWidth() { return 16; } }
apache-2.0
wardensky/wardensky-demo
java/mq_request_reply/src/main/java/com/wardensky/demo/mq_request_reply/MqClient.java
2496
package com.wardensky.demo.mq_request_reply; import java.util.UUID; import javax.jms.DeliveryMode; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.Session; import javax.jms.TemporaryQueue; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MqClient extends MqAbstractBase implements MessageListener { private TemporaryQueue tempQ; private static final Logger logger = LoggerFactory.getLogger(MqClient.class); public String response = null; public void start(String qName) throws JMSException { this.qName = qName; connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, GlobalConfig.MQ_URL); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(this.qName); producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); tempQ = session.createTemporaryQueue(); this.consumer = session.createConsumer(tempQ); this.consumer.setMessageListener(this); } public void close() throws JMSException { producer.close(); consumer.close(); session.close(); connection.close(); } public static void main(String[] args) { MqClient client = new MqClient(); try { String qName = "adminQueue"; client.start(qName); for (int i = 0; i < 10; i++) { client.sendRequest("message " + i); Thread.sleep(1000 * 2); } Thread.sleep(1000 * 300); client.close(); } catch (Exception e) { logger.error("", e); } } public void sendRequest(String msg) throws JMSException { TextMessage message = session.createTextMessage(msg); message.setJMSReplyTo(tempQ); String correlationId = UUID.randomUUID().toString(); message.setJMSCorrelationID(correlationId); logger.info("client send message " + message.getJMSCorrelationID()); logger.info("tempq " + tempQ.getQueueName()); producer.send(message); } public void onMessage(Message message) { TextMessage textMessage = (TextMessage) message; try { logger.info("client receive message"); logger.info(textMessage.getText()); this.response = textMessage.getText(); } catch (Exception ex) { logger.error("", ex); } } }
apache-2.0
crow-misia/FindBugsPlugin
src/main/java/jp/co/minori/findbugs/detect/slf4j/WrongPlaceholderDetector.java
8486
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package jp.co.minori.findbugs.detect.slf4j; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.OpcodeStack.Item; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; /** * @author Kengo TODA (eller86) * @see https://github.com/eller86/findbugs-slf4j */ public class WrongPlaceholderDetector extends OpcodeStackDetector { private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("(.?)(\\\\\\\\)*\\{\\}"); private final BugReporter bugReporter; private final ArrayDataHandler arrayDataHandler; private final ThrowableHandler throwableHandler; private static final Set<String> TARGET_METHOD_NAMES = new HashSet<String>( Arrays.asList("trace", "debug", "info", "warn", "error")); // these methods do not use formatter private static final Set<String> SIGS_WITHOUT_FORMAT = new HashSet<String>( Arrays.asList( "(Ljava/lang/String;)V", "(Lorg/slf4j/Maker;Ljava/lang/String;)V", "(Ljava/lang/String;Ljava/lang/Throwable;)V", "(Lorg/slf4j/Maker;Ljava/lang/String;Ljava/lang/Throwable;)V")); public WrongPlaceholderDetector(final BugReporter bugReporter) { this.bugReporter = bugReporter; this.throwableHandler = new ThrowableHandler(); this.arrayDataHandler = new ArrayDataHandler(throwableHandler); } @Override public void sawOpcode(final int seen) { throwableHandler.sawOpcode(this, seen); if (seen == INVOKEINTERFACE) { checkLogger(); } arrayDataHandler.sawOpcode(stack, seen); } @Override public void afterOpcode(final int seen) { final ArrayData newUserValueToSet = arrayDataHandler.afterOpcode(stack, seen); super.afterOpcode(seen); if (newUserValueToSet != null) { final Item createdArray = stack.getStackItem(0); createdArray.setUserValue(newUserValueToSet); } try { throwableHandler.afterOpcode(this, seen); } catch (final ClassNotFoundException e) { throw new IllegalStateException("class not found", e); } } private void checkLogger() { final String signature = getSigConstantOperand(); if (!"org/slf4j/Logger".equals(getClassConstantOperand()) || !TARGET_METHOD_NAMES.contains(getNameConstantOperand())) { return; } final boolean withoutFormat = SIGS_WITHOUT_FORMAT.contains(signature); final String formatString = getFormatString(stack, signature); if (formatString == null || withoutFormat) { return; } verifyFormat(formatString); final int placeholderCount = countPlaceholder(formatString); int parameterCount; try { parameterCount = countParameter(stack, signature); } catch (final IllegalStateException e) { // Using unknown array as parameter. In this case, we cannot check number of parameter. final BugInstance bug = new BugInstance(this, "SLF4J_UNKNOWN_ARRAY", HIGH_PRIORITY) .addSourceLine(this).addClassAndMethod(this) .addCalledMethod(this); bugReporter.reportBug(bug); return; } if (placeholderCount != parameterCount) { final BugInstance bug = new BugInstance(this, "SLF4J_PLACE_HOLDER_MISMATCH", HIGH_PRIORITY) .addInt(placeholderCount).addInt(parameterCount) .addSourceLine(this).addClassAndMethod(this) .addCalledMethod(this); bugReporter.reportBug(bug); } } private void verifyFormat(final String formatString) { final CodepointIterator iterator = new CodepointIterator(formatString); while (iterator.hasNext()) { if (Character.isLetter(iterator.next().intValue())) { // found non-sign character. return; } } final BugInstance bug = new BugInstance(this, "SLF4J_SIGN_ONLY_FORMAT", NORMAL_PRIORITY) .addString(formatString) .addSourceLine(this).addClassAndMethod(this) .addCalledMethod(this); bugReporter.reportBug(bug); } int countParameter(final OpcodeStack stack, final String methodSignature) { final String[] signatures = splitSignature(methodSignature); int parameterCount = signatures.length - 1; // -1 means 'formatString' is not parameter if ("[Ljava/lang/Object;".equals(signatures[parameterCount])) { final ArrayData arrayData = (ArrayData) stack.getStackItem(0).getUserValue(); if (arrayData == null || arrayData.getSize() < 0) { throw new IllegalStateException("no array initializer found"); } parameterCount = arrayData.getSize(); if (arrayData.hasThrowableAtLast()) { --parameterCount; } return parameterCount; } if ("Lorg/slf4j/Maker;".equals(signatures[0])) { --parameterCount; } final Item lastItem = stack.getStackItem(0); if (throwableHandler.checkThrowable(lastItem)) { --parameterCount; } return parameterCount; } int countPlaceholder(final String format) { final Matcher matcher = PLACEHOLDER_PATTERN.matcher(format); int count = 0; while (matcher.find()) { if (!"\\".equals(matcher.group(1))) { ++count; } } return count; } private String getFormatString(final OpcodeStack stack, final String signature) { // formatString is the first string in argument final int stackIndex = indexOf(signature, "Ljava/lang/String;"); final Object constant = stack.getStackItem(stackIndex).getConstant(); if (constant == null) { final BugInstance bug = new BugInstance(this, "SLF4J_FORMAT_SHOULD_BE_CONST", HIGH_PRIORITY) .addSourceLine(this).addClassAndMethod(this) .addCalledMethod(this); bugReporter.reportBug(bug); return null; } return constant.toString(); } int indexOf(final String methodSignature, final String targetType) { final String[] arguments = splitSignature(methodSignature); int index = arguments.length; for (final String type : arguments) { --index; if (type.equals(targetType)) { return index; } } return -1; } private static final Pattern SIGNATURE_PATTERN = Pattern.compile("^\\((.*)\\).*$"); private String[] splitSignature(final String methodSignature) { final Matcher matcher = SIGNATURE_PATTERN.matcher(methodSignature); if (matcher.find()) { final String[] arguments = matcher.group(1).split(";"); for (int i = 0, n = arguments.length; i < n; i++) { arguments[i] = arguments[i] + ';'; } return arguments; } throw new IllegalArgumentException(); } }
apache-2.0
nortal/lorque
lorque-app/src/main/java/com/nortal/lorque/core/GsonProvider.java
2573
package com.nortal.lorque.core; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; /** * @author Vassili Jakovlev */ @Provider @Produces(APPLICATION_JSON) @Consumes(APPLICATION_JSON) public class GsonProvider<T> implements MessageBodyReader<T>, MessageBodyWriter<T> { private final Gson gson; public GsonProvider() { gson = getGsonBuilder().create(); } public static GsonBuilder getGsonBuilder() { return new GsonBuilder().setDateFormat(DateFormat.ISO_8601); } @Override public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } @Override public void writeTo(T object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { PrintWriter printWriter = new PrintWriter(entityStream); String json; if (object instanceof String) { json = (String) object; } else { json = gson.toJson(object); } try { printWriter.write(json); printWriter.flush(); } finally { printWriter.close(); } } @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } @Override public T readFrom(Class<T> type, Type gnericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { InputStreamReader reader = new InputStreamReader(entityStream, "UTF-8"); try { return gson.fromJson(reader, type); } finally { reader.close(); } } }
apache-2.0
soggier/compiler
src/ch/ntb/inf/deep/eclipse/ui/properties/DeepProjectPage.java
19160
/* * Copyright 2011 - 2013 NTB University of Applied Sciences in Technology * Buchs, Switzerland, http://www.ntb.ch/inf * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ch.ntb.inf.deep.eclipse.ui.properties; import java.io.File; import java.util.GregorianCalendar; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchPropertyPage; import org.eclipse.ui.dialogs.PropertyPage; import ch.ntb.inf.deep.config.Configuration; import ch.ntb.inf.deep.config.Parser; import ch.ntb.inf.deep.eclipse.DeepPlugin; import ch.ntb.inf.deep.eclipse.ui.preferences.PreferenceConstants; public class DeepProjectPage extends PropertyPage implements IWorkbenchPropertyPage { private final String defaultPath = DeepPlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.DEFAULT_LIBRARY_PATH); private final String defaultImgPath = ""; private Combo boardCombo, programmerCombo, osCombo, imgFormatCombo; private Button checkDefaultLibPath, browse, checkImg, browseImg; private Text path, pathImg; private int indexImgFormat; private String lastImgPathChoice = defaultImgPath; private boolean createImgFile = false; private String lastChoice, lastImgFormatChoice; private Label libState; private String projectSpecificLibPath, board, programmer, os, rootclasses, imglocation, imgformat; private String[][] boards, programmers, osys, imgformats; private DeepFileChanger dfc; @Override protected Control createContents(Composite parent) { // read deep project file IProject project = (IProject) getElement().getAdapter(IProject.class); dfc = new DeepFileChanger(project.getLocation() + "/" + project.getName() + ".deep"); projectSpecificLibPath = dfc.getContent("libpath"); if (projectSpecificLibPath != null && projectSpecificLibPath.length() >= 2) projectSpecificLibPath = projectSpecificLibPath.substring(1, projectSpecificLibPath.length()-1); //set last choice to workspace default if that is currently selected if(projectSpecificLibPath == null && lastChoice == null) lastChoice = defaultPath; //replace null values with empty strings if(lastChoice == null) lastChoice = ""; if(lastImgFormatChoice == null) lastImgFormatChoice = ""; if(lastImgPathChoice == null) lastImgPathChoice = ""; board = dfc.getContent("boardtype"); programmer = dfc.getContent("programmertype"); os = dfc.getContent("ostype"); rootclasses = dfc.getContent("rootclasses"); imglocation = dfc.getContent("imgfile"); imgformat = dfc.getContent("imgformat"); if(imglocation == null && imgformat == null){ createImgFile = false; lastImgPathChoice = project.getLocation().toString(); lastImgPathChoice = lastImgPathChoice.replace('/', '\\'); } else{ createImgFile = true; lastImgPathChoice = imglocation.replace('/', '\\'); lastImgPathChoice = lastImgPathChoice.substring(1,lastImgPathChoice.length() -1 ); int indexOfProjectName = lastImgPathChoice.lastIndexOf("\\"); lastImgPathChoice = lastImgPathChoice.substring(0, indexOfProjectName); lastImgFormatChoice = imgformat; } // System.out.println(dfc.fileContent.toString()); // System.out.println(libPath); // System.out.println(board); // System.out.println(programmer); // System.out.println(os); // System.out.println(rootclasses); // System.out.println(lastImgPathChoice); // System.out.println(lastImgFormatChoice); // System.out.println(""); // read project preferences // build control Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); Group groupLib = new Group(composite, SWT.NONE); groupLib.setText("Target Library"); GridLayout gridLayout2 = new GridLayout(2, false); groupLib.setLayout(gridLayout2); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = 2; groupLib.setLayoutData(gridData); Label label1 = new Label(groupLib,SWT.NONE); label1.setText("Pleace specify the target library you want to use for this project."); label1.setLayoutData(gridData); Label dummy = new Label(groupLib, SWT.NONE); dummy.setLayoutData(gridData); checkDefaultLibPath = new Button(groupLib, SWT.CHECK); checkDefaultLibPath.setText("Use default library path"); checkDefaultLibPath.setSelection(projectSpecificLibPath == null); checkDefaultLibPath.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (e.widget.equals(checkDefaultLibPath)) { if (checkDefaultLibPath.getSelection()) { path.setEnabled(false); path.setText(defaultPath); projectSpecificLibPath = null;//implies default } else { path.setEnabled(true); path.setText(lastChoice); projectSpecificLibPath = path.getText(); } if (checkLibPath()) readLib(); } } }); checkDefaultLibPath.setLayoutData(gridData); path = new Text(groupLib, SWT.SINGLE | SWT.BORDER); GridData gridData2 = new GridData(); gridData2.horizontalAlignment = SWT.FILL; gridData2.grabExcessHorizontalSpace = true; path.setLayoutData(gridData2); path.setText(getEffectiveLibPath()); path.setEnabled(!checkDefaultLibPath.getSelection()); path.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { projectSpecificLibPath = path.getText(); if (checkLibPath()) readLib(); } }); browse = new Button(groupLib, SWT.PUSH); browse.setText("Browse..."); browse.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (!checkDefaultLibPath.getSelection()){ openDirectoryDialog(); if (checkLibPath()) readLib(); } } }); libState = new Label(groupLib,SWT.NONE); libState.setLayoutData(gridData); // Group groupBoard = new Group(composite, SWT.BOTTOM); Group groupBoard = new Group(composite, SWT.NONE); groupBoard.setText("Board configuration"); GridLayout groupLayout1 = new GridLayout(2, false); groupBoard.setLayout(groupLayout1); GridData gridData3 = new GridData(); gridData3.horizontalAlignment = SWT.FILL; gridData3.grabExcessHorizontalSpace = true; gridData3.horizontalSpan = 2; groupBoard.setLayoutData(gridData3); Label boardLabel = new Label(groupBoard, SWT.NONE); boardLabel.setText("Select a board"); boardCombo = new Combo(groupBoard, SWT.VERTICAL | SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY); boardCombo.addSelectionListener(listener); Label progLabel = new Label(groupBoard, SWT.NONE); progLabel.setText("Select a programmer"); programmerCombo = new Combo(groupBoard, SWT.VERTICAL | SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY); programmerCombo.addSelectionListener(listener); // Group groupOS = new Group(composite, SWT.BOTTOM); Group groupOS = new Group(composite, SWT.NONE); groupOS.setText("Runtime system"); GridLayout groupLayout2 = new GridLayout(2, false); groupOS.setLayout(groupLayout2); GridData gridData4 = new GridData(); gridData4.horizontalAlignment = SWT.FILL; gridData4.grabExcessHorizontalSpace = true; gridData4.horizontalSpan = 2; groupOS.setLayoutData(gridData4); Label osLabel = new Label(groupOS,SWT.NONE); osLabel.setText("Select a operating system"); osCombo = new Combo(groupOS, SWT.VERTICAL | SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY); osCombo.addSelectionListener(listener); Group groupImg = new Group(composite, SWT.NONE); groupImg.setText("Image file creation"); GridLayout gridLayoutImg = new GridLayout(2,false); groupImg.setLayout(gridLayoutImg); GridData gridDataImg = new GridData(SWT.FILL, SWT.CENTER, true, false); gridDataImg.horizontalSpan = 2; checkImg = new Button(groupImg, SWT.CHECK); checkImg.setText("Create image file"); checkImg.setSelection(false); checkImg.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if(e.widget.equals(checkImg)) { if (checkLibPath()) readLib(); if(checkImg.getSelection()) { pathImg.setEnabled(true); pathImg.setText(lastImgPathChoice); browseImg.setEnabled(true); imgFormatCombo.setEnabled(true); indexImgFormat = 0; for (int i = 0; i < Configuration.formatMnemonics.length; i++) { if (lastImgFormatChoice != null && lastImgFormatChoice.equalsIgnoreCase(Configuration.formatMnemonics[i])) indexImgFormat = i; } imgFormatCombo.select(indexImgFormat); createImgFile = true; } else { pathImg.setEnabled(false); pathImg.setText(lastImgPathChoice); browseImg.setEnabled(false); imgFormatCombo.setEnabled(false); indexImgFormat = 0; for (int i = 0; i < Configuration.formatMnemonics.length; i++) { if (lastImgFormatChoice != null && lastImgFormatChoice.equalsIgnoreCase(Configuration.formatMnemonics[i])) indexImgFormat = i; } imgFormatCombo.select(indexImgFormat); createImgFile = false; } } } }); checkImg.setLayoutData(gridDataImg); GridData gridDataImg2 = new GridData(SWT.FILL, SWT.FILL, true, false); pathImg = new Text(groupImg, SWT.SINGLE | SWT.BORDER); pathImg.setLayoutData(gridDataImg2); pathImg.setEnabled(false); pathImg.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { imglocation = pathImg.getText(); if (checkLibPath()) readLib(); } }); browseImg = new Button(groupImg, SWT.PUSH); browseImg.setText("Browse..."); browseImg.setEnabled(false); browseImg.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ if (checkImg.getSelection()) { openImgDirectoryDialog(); if (checkLibPath()) readLib(); } } }); GridData gridDataImg3 = new GridData(SWT.FILL, SWT.FILL, true, false); gridDataImg3.horizontalSpan = 2; Label imgFormatLabel = new Label(groupImg,SWT.NONE); imgFormatLabel.setText("Select image file format"); imgFormatCombo = new Combo(groupImg, SWT.VERTICAL | SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY); imgFormatCombo.setEnabled(false); imgFormatCombo.setLayoutData(gridDataImg3); imgFormatCombo.addSelectionListener(listener); indexImgFormat = 0; for (int i = 0; i < Configuration.formatMnemonics.length; i++) { if (lastImgFormatChoice != null && lastImgFormatChoice.equalsIgnoreCase(Configuration.formatMnemonics[i])) indexImgFormat = i; } imgFormatCombo.select(indexImgFormat); //initial values of Image file creation if(createImgFile){ checkImg.setSelection(true); pathImg.setEnabled(true); pathImg.setText(lastImgPathChoice); browseImg.setEnabled(true); imgFormatCombo.setEnabled(true); } else{ checkImg.setSelection(false); pathImg.setEnabled(false); pathImg.setText(lastImgPathChoice); browseImg.setEnabled(false); imgFormatCombo.setEnabled(false); } if (checkLibPath()) readLib(); else projectSpecificLibPath = null; return composite; } private SelectionAdapter listener = new SelectionAdapter() { public void widgetSelected(SelectionEvent e){ if (e.widget.equals(boardCombo)) { if (boardCombo.getSelectionIndex() != boardCombo.getItemCount() - 1) board = boards[boardCombo.getSelectionIndex()][0]; else board = ""; } if (e.widget.equals(osCombo)) { if (osCombo.getSelectionIndex() != osCombo.getItemCount() - 1) os = osys[osCombo.getSelectionIndex()][0]; else os = ""; } if (e.widget.equals(programmerCombo)) { if (programmerCombo.getSelectionIndex() != programmerCombo.getItemCount() - 1) programmer = programmers[programmerCombo.getSelectionIndex()][0]; else programmer = ""; } if (e.widget.equals(imgFormatCombo)) { if (imgFormatCombo.getSelectionIndex() != imgFormatCombo.getItemCount() - 1) lastImgFormatChoice = Configuration.formatMnemonics[imgFormatCombo.getSelectionIndex()]; else lastImgFormatChoice = ""; } } }; private void readLib() { String libPath = getEffectiveLibPath(); boards = Configuration.searchDescInConfig(new File(libPath + Configuration.boardsPath), Parser.sBoard); String[] str = new String[boards.length + 1]; int index = boards.length; for (int i = 0; i < boards.length; i++) { str[i] = boards[i][1]; // if (pref.get("board", "").equals(boards[i][0])) index = i; if (board != null && board.equals(boards[i][0])) index = i; } str[str.length - 1] = "none"; boardCombo.setItems(str); boardCombo.select(index); programmers = Configuration.searchDescInConfig(new File(libPath.toString() + Configuration.progPath), Parser.sProgrammer); str = new String[programmers.length + 1]; index = programmers.length; for (int i = 0; i < programmers.length; i++) { str[i] = programmers[i][1]; // if (pref.get("programmer", "").equals(programmers[i][0])) index = i; if (programmer != null && programmer.equals(programmers[i][0])) index = i; } str[str.length - 1] = "none"; programmerCombo.setItems(str); programmerCombo.select(index); osys = Configuration.searchDescInConfig(new File(libPath.toString() + Configuration.osPath), Parser.sOperatingSystem); str = new String[osys.length + 1]; index = osys.length; for (int i = 0; i < osys.length; i++) { str[i] = osys[i][1]; // if (pref.get("os", "").equals(os[i][0])) index = i; if (os != null && os.equals(osys[i][0])) index = i; } str[str.length - 1] = "none"; osCombo.setItems(str); osCombo.select(index); String[] strImg = new String[Configuration.formatMnemonics.length + 1]; int indexImg = strImg.length - 1; for (int i = 0; i < Configuration.formatMnemonics.length; i++) { strImg[i] = Configuration.formatMnemonics[i]; if (strImg[i].equalsIgnoreCase(imgFormatCombo.getText())) indexImg = i; } strImg[strImg.length - 1] = "none"; imgFormatCombo.setItems(strImg); if(lastImgFormatChoice == null){ imgFormatCombo.select(indexImgFormat); } else{ imgFormatCombo.select(indexImg); } } private String getEffectiveLibPath() { return projectSpecificLibPath != null ? projectSpecificLibPath : defaultPath; } private void openDirectoryDialog() { DirectoryDialog dlg = new DirectoryDialog(getShell()); dlg.setFilterPath(path.getText()); // Set the initial filter path according to anything they've selected or typed in dlg.setText("deep Library Path Selection"); dlg.setMessage("Select a directory"); String dir = dlg.open(); // Calling open() will open and run the dialog. if (dir != null) { path.setText(dir); projectSpecificLibPath = dir; lastChoice = dir; } } private void openImgDirectoryDialog() { DirectoryDialog dlg = new DirectoryDialog(getShell()); dlg.setFilterPath(pathImg.getText()); // Set the initial filter path according to anything they've selected or typed in dlg.setText("Image File Save Location"); dlg.setMessage("Select a directory"); String dir = dlg.open(); // Calling open() will open and run the dialog. if (dir != null) { pathImg.setText(dir); lastImgPathChoice = dir; } } private boolean checkLibPath() { String libPath = getEffectiveLibPath(); File lib = new File(libPath); if (!lib.exists()) { libState.setText("Given library path is NOT valid target library."); return false; } String[][] boards = Configuration.searchDescInConfig(new File(lib.toString() + Configuration.boardsPath), Parser.sBoard); if (boards == null) { libState.setText("Given library path is NOT valid target library."); return false; } libState.setText(""); return true; } @Override protected void performApply() { saveFiles(); super.performApply(); } @Override public boolean performOk() { saveFiles(); return true; } @Override public boolean performCancel() { return true; } private void saveFiles() { // change deep file IProject project = (IProject) getElement().getAdapter(IProject.class); GregorianCalendar cal = new GregorianCalendar(); dfc.setContent("version", "\"" + cal.getTime().toString() + "\""); if(projectSpecificLibPath != null) dfc.setContent("libpath", "\"" + projectSpecificLibPath + "\""); else dfc.removeContent("libpath"); dfc.setContent("boardtype", board); dfc.setContent("ostype", os); if(programmerCombo.getText().equals("none") && dfc.getContent("programmertype") != null){ dfc.setContent("programmertype", programmer); dfc.commentContent("programmertype"); } else if(programmerCombo.getText().equals("none") && dfc.getContent("programmertype") == null){ } else dfc.setContent("programmertype", programmer); dfc.setContent("rootclasses", rootclasses); if(createImgFile){ //add Line for imgfile dfc.setContent("imgfile", "\"" + lastImgPathChoice + "\\"+ project.getName() + "." + lastImgFormatChoice.toLowerCase() + "\""); dfc.setContent("imgformat", lastImgFormatChoice); } else{ //comment imgfile lines if(dfc.getContent("imgfile") == null){ dfc.commentContent("imgfile"); } if(dfc.getContent("imgformat") == null){ dfc.commentContent("imgformat"); } } dfc.save(); lastChoice = path.getText(); lastImgPathChoice = pathImg.getText(); lastImgFormatChoice = imgFormatCombo.getText(); try { project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { e.printStackTrace(); } } }
apache-2.0
jijeshmohan/webdriver-rb
firefox/src/java/org/openqa/selenium/firefox/internal/CircularOutputStream.java
1979
/* Copyright 2009 WebDriver committers Copyright 2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.firefox.internal; import java.io.OutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; /** * Captures the last N bytes of output. */ public class CircularOutputStream extends OutputStream { private static final int DEFAULT_SIZE = 4096; private int start; private int end; private boolean filled = false; private byte[] buffer; public CircularOutputStream(int maxSize) { buffer = new byte[maxSize]; } public CircularOutputStream() { this(DEFAULT_SIZE); } @Override public void write(int b) throws IOException { if (end == buffer.length) { filled = true; end = 0; } if (filled && end == start) { start = start == buffer.length - 1 ? 0 : start + 1; } buffer[end++] = (byte) b; } @Override public String toString() { int size = filled ? buffer.length : end; byte[] toReturn = new byte[size]; // Handle the partially filled array as a special case if (!filled) { System.arraycopy(buffer, 0, toReturn, 0, end); return new String(toReturn); } System.arraycopy(buffer, start, toReturn, 0, buffer.length - start); System.arraycopy(buffer, 0, toReturn, buffer.length - start, end); return new String(toReturn); } }
apache-2.0
naver/pinpoint
web/src/main/java/com/navercorp/pinpoint/web/service/CacheService.java
991
/* * Copyright 2021 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.web.service; import com.navercorp.pinpoint.web.view.TagApplications; /** * @author yjqg6666 */ public interface CacheService { String DEFAULT_KEY = "DEFAULT"; String APPLICATION_LIST_CACHE_NAME = "applicationNameList"; TagApplications get(String key); void put(String key, TagApplications tagApplications); void remove(String key); }
apache-2.0
ontop/ontop
engine/system/sql/owlapi/src/main/java/it/unibz/inf/ontop/injection/OntopSQLOWLAPIConfiguration.java
648
package it.unibz.inf.ontop.injection; import it.unibz.inf.ontop.injection.impl.OntopSQLOWLAPIConfigurationImpl; public interface OntopSQLOWLAPIConfiguration extends OntopStandaloneSQLConfiguration, OntopSystemOWLAPIConfiguration, OntopMappingSQLAllOWLAPIConfiguration { static Builder<? extends Builder<?>> defaultBuilder() { return new OntopSQLOWLAPIConfigurationImpl.BuilderImpl<>(); } interface Builder<B extends Builder<B>> extends OntopStandaloneSQLConfiguration.Builder<B>, OntopMappingSQLAllOWLAPIConfiguration.Builder<B> { @Override OntopSQLOWLAPIConfiguration build(); } }
apache-2.0
gauthierj/dsm-webapi-client
dsm-webapi-client-filestation/src/main/java/com/github/gauthierj/dsm/webapi/client/filestation/sharelist/ShareListServiceImpl.java
3092
package com.github.gauthierj.dsm.webapi.client.filestation.sharelist; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.gauthierj.dsm.webapi.client.DsmWebapiResponse; import com.github.gauthierj.dsm.webapi.client.filestation.common.PaginationAndSorting; import com.github.gauthierj.dsm.webapi.client.AbstractDsmServiceImpl; import com.github.gauthierj.dsm.webapi.client.DsmWebApiResponseError; import com.github.gauthierj.dsm.webapi.client.DsmWebapiRequest; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; @Component public class ShareListServiceImpl extends AbstractDsmServiceImpl implements ShareListService { // API Infos private static final String API_ID = "SYNO.FileStation.List"; private static final String API_VERSION = "1"; // API Methods private static final String METHOD_LIST_SHARE = "list_share"; // Parameters private static final String PARAMETER_ADDITIONAL = "additional"; private static final String PARAMETER_OFFSET = "offset"; private static final String PARAMETER_ONLYWRITABLE = "onlywritable"; private static final String PARAMETER_LIMIT = "limit"; private static final String PARAMETER_SORT_BY = "sort_by"; private static final String PARAMETER_SORT_DIRECTION = "sort_direction"; // Parameters values private static final String PARAMETER_VALUE_ADDITIONAL = "real_path,owner,time,perm,mount_point_type,sync_share,volume_status"; public ShareListServiceImpl() { super(API_ID); } @Override public ShareList list(PaginationAndSorting paginationAndSorting, Optional<Boolean> onlyWritable) { DsmWebapiRequest request = new DsmWebapiRequest(getApiInfo().getApi(), API_VERSION, getApiInfo().getPath(), METHOD_LIST_SHARE) .parameter(PARAMETER_OFFSET, Integer.toString(paginationAndSorting.getOffset())) .parameter(PARAMETER_LIMIT, Integer.toString(paginationAndSorting.getLimit())) .parameter(PARAMETER_SORT_BY, paginationAndSorting.getSortBy().getRepresentation()) .parameter(PARAMETER_SORT_DIRECTION, paginationAndSorting.getSortDirection().getRepresentation()) .parameter(PARAMETER_ONLYWRITABLE, onlyWritable.orElse(false).toString()) .parameter(PARAMETER_ADDITIONAL, PARAMETER_VALUE_ADDITIONAL); ShareListResponse call = getDsmWebapiClient().call(request, ShareListResponse.class); return call.getData(); } @Override public List<Share> list(boolean onlyWritable) { return list(PaginationAndSorting.DEFAULT_PAGINATION_AND_SORTING, Optional.of(onlyWritable)).getElements(); } @Override public List<Share> list() { return list(false); } private static class ShareListResponse extends DsmWebapiResponse<ShareList> { public ShareListResponse(@JsonProperty("success") boolean success, @JsonProperty("data") ShareList data, @JsonProperty("error") DsmWebApiResponseError error) { super(success, data, error); } } }
apache-2.0
petermichalek/iotan-hs
src/main/java/org/iotus/hs/IMHServlet.java
13426
package org.iotus.hs; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.util.*; import java.util.logging.Logger; import java.util.logging.Level; import javax.servlet.ServletException; import javax.servlet.http.*; import iotus.core.Iotus$; import iotus.core.IMContext; import org.projecthaystack.HGrid; import org.projecthaystack.HRow; import org.projecthaystack.io.HZincWriter; import org.projecthaystack.server.HOp; import org.projecthaystack.util.Base64; // Note: this will be placed in web.xml /* WEB-INF/web.xml <servlet-class>org.iotus.hs.IMHServlet</servlet-class> */ /** * IMHServlet implements the haystack HTTP REST API for * querying entities and history data. * * @see <a href='http://project-haystack.org/doc/Rest'>Project Haystack</a> */ public class IMHServlet extends HttpServlet { // set false to disable auth for testing purposes (but disable never in production) private static boolean AUTH_ENABLED = true; // db connection pool private static DbPool dbPool = new DbPool(); // list of project deemed to exist and accessible at /api/{project} private static List<String> projects = new LinkedList(); ////////////////////////////////////////////////////////////////////////// // Database Hook ////////////////////////////////////////////////////////////////////////// /** * */ private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger("org.iotus"); private static final List<String> UNAUTH_OPS = Arrays.asList( "about", "formats", "ops" ); /** * Number of minutes after login when session expires on inactive connection */ private int sessionExpire = 10; // Interface with singleton Iotus in scala private static Iotus$ iotus = Iotus$.MODULE$; static { //Logger.getLogger("com.datastax.driver.core.Session").setLevel(Level.parse("INFO")); //Logger.getLogger("com.datastax.driver.core.Connection").setLevel(Level.parse("INFO")); logger.setLevel(Level.parse("INFO")); iotus.start(); initProjects(); } private static void initProjects() { HGrid grid = iotus.listProjects(null).toGrid(); //for (int i = 0; i < grid.numRows(); i++) { // HRow row = grid.iterator(); //} logger.info("projects grid: " + HZincWriter.gridToString(grid)); synchronized (projects) { projects.clear(); if (grid.numRows() == 0) { logger.severe("No project configured in the database."); } else { logger.info(String.format("%d projects configured in the database.", grid.numRows())); Iterator<HRow> it = grid.iterator(); while (it.hasNext()) { HRow row = it.next(); projects.add(row.getStr("pid")); } } } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { onService("GET", req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { onService("POST", req, res); } /** * Validates authorization headers * @param req * @return true if validation passed, false otherwise */ private boolean validateAuth(HttpServletRequest req) { boolean rc = false; //logger.info("validateAuth start"); // perform authorization String authHeader = req.getHeader("Authorization"); String username = null; String password = null; if (authHeader != null) { //out.println("Base64-encoded Authorization Value: <em>" + encodedValue); try { String encodedValue = authHeader.split(" ")[1]; String decodedValue = Base64.STANDARD.decode(encodedValue); logger.fine("Authorization decoded:" + decodedValue); String creds[] = decodedValue.split(":"); if (creds.length != 2) { logger.severe("Authorization must be of the form user:password"); } else { username = creds[0]; password = creds[1]; //logger.fine("username: " + username); //logger.fine("password: " + password); HttpSession session = req.getSession(); Object sessionUser = session.getAttribute("user"); if (sessionUser != null && username.equals(sessionUser)) { logger.fine(String.format( "session already validated for user %s. No addtional validateCredentials call needed", username)); rc = true; } else { rc = iotus.validateCredentials(username, password); if (rc) { logger.info("Validation passed: for " + username); session.setAttribute("user", username); session.setMaxInactiveInterval(sessionExpire*60); } else { logger.warning("Validation failed for " + username); } } } } catch(Exception e) { logger.severe("Authorization can't be decoded: " + e); } } else { logger.fine("No Authorization header"); } //logger.info("validateAuth end"); return rc; } /** * Override onService parent, mainly to implement multi-tenant database that can switch between projects. */ private void onService(String method, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { /* dump requests, e.g.: method = GET pathInfo = /test-project/read contextPath = servletPath = /api query = filter=point and dis=="test pt 03" or dis=="test pt 02" headers: Authorization = Basic ZnJhbmt... Accept = ... User-Agent = curl/7.49.1 Host = localhost:1225 */ //dumpReq(req); HttpSession session = req.getSession(); // if root, then redirect to {haystack}/about String path = req.getPathInfo(); if (path == null || path.length() == 0 || path.equals("/")) { res.sendRedirect(req.getServletPath() + "/about"); return; } String user = (String)session.getAttribute("user"); String sessionId = session.getId(); int maxInactiveInterval = session.getMaxInactiveInterval(); logger.fine(String.format("session %s: user=%s, %d", sessionId, user, maxInactiveInterval)); String opName = null; String project = null; // parse URI path into "/{opName}/...." int slash = path.indexOf('/', 1); if (slash < 0) slash = path.length(); int slash2 = path.lastIndexOf('/'); if (slash2 > 0) { project = path.substring(1, slash); opName = path.substring(slash2+1); logger.fine("path, opName, project: " + path + "; " + opName + "; " + project); synchronized (projects) { if (!projects.contains(project)) { // see if new project added since init HGrid grid = iotus.projectByName(project).toGrid(); if (grid.numRows() > 0) { // yes new project added, add it to our list of pid's projects.add(project); } else { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } } if (AUTH_ENABLED) { if (!validateAuth(req)) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); res.setHeader("WWW-Authenticate", "Basic realm=\"Haystack\""); return; } } IMDatabase db = dbPool.checkOut(); IMContext ctx = db.getContext(); // create a new context if for this db context already exists if ( !(ctx != null && db.getContext().pid().equals(project))) { ctx = new IMContext(project, user); db.setContext(ctx); } // if this is an old context and a different author/user, we may need to set the context author if (ctx != null && ctx.getAuthor() != null && !ctx.getAuthor().equals(user)) { ctx.setAuthor(user); } /* TODO: * enable verification of project access in /api/demo/about * enable project specific db connector from db map if needed, or use pooled connector for all projects */ HOp op = null; try { // resolve the op op = db.op(opName, false); if (op == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (Exception e) { dbPool.checkIn(db); res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // route to the op try { op.onService(db, req, res); } catch (Exception e) { e.printStackTrace(); throw new ServletException(e); } finally { dbPool.checkIn(db); } } else { if (slash2 == 0) { // un-authenticate request opName = path.substring(1); logger.fine("path, opName (no project) - processing unauthenticated request: " + path + "; " + opName); // get db for any project IMDatabase db = dbPool.checkOut(); // create a new context if for this db context already exists if ( db.getContext() == null) { IMContext ctx = new IMContext("demo", user); db.setContext(ctx); } HOp op = null; try { if (UNAUTH_OPS.contains(opName)) { // resolve the op op = db.op(opName, false); if (op == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } else { logger.severe("Only unauth operations permitted at non-project /api path"); res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (Exception e) { dbPool.checkIn(db); res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // route to the op try { op.onService(db, req, res); } catch (Exception e) { e.printStackTrace(); throw new ServletException(e); } finally { dbPool.checkIn(db); } } else { //opName = path.substring(slash2+1); // TODO: add unauth db invocation with null project for /api/about etc. String msg = "Incorrect request: can't parse project and operation from path " + path; logger.severe("path, opName: " + path + "; " + opName); throw new ServletException(msg); } } } ////////////////////////////////////////////////////////////////////////// // Debug ////////////////////////////////////////////////////////////////////////// void dumpReq(HttpServletRequest req) { dumpReq(req, null); } void dumpReq(HttpServletRequest req, PrintWriter out) { try { if (out == null) out = new PrintWriter(System.out); out.println("=========================================="); out.println("method = " + req.getMethod()); out.println("pathInfo = " + req.getPathInfo()); out.println("contextPath = " + req.getContextPath()); out.println("servletPath = " + req.getServletPath()); out.println("query = " + (req.getQueryString() == null ? "null" : URLDecoder.decode(req.getQueryString(), "UTF-8"))); out.println("headers:"); Enumeration e = req.getHeaderNames(); while (e.hasMoreElements()) { String key = (String)e.nextElement(); String val = req.getHeader(key); out.println(" " + key + " = " + val); } out.flush(); } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
ngrwork/HelloWorldRest
org.restlet.example/src/org/restlet/example/book/restlet/ch04/sec4/sub2/Mail.java
1993
/** * Copyright 2005-2011 Noelios Technologies. * * The contents of this file are subject to the terms of one of the following * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the * "Licenses"). You can select the license that you prefer but you may not use * this file except in compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1.php * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1.php * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0.php * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package org.restlet.example.book.restlet.ch04.sec4.sub2; /** * The mail representation bean. */ public class Mail { private String status; private String subject; private String content; private String accountRef; public String getAccountRef() { return accountRef; } public String getContent() { return content; } public String getStatus() { return status; } public String getSubject() { return subject; } public void setAccountRef(String accountRef) { this.accountRef = accountRef; } public void setContent(String content) { this.content = content; } public void setStatus(String status) { this.status = status; } public void setSubject(String subject) { this.subject = subject; } }
apache-2.0
leafseelight/GitDemo
timepickerlibrary/src/androidTest/java/com/seelight/leaf/timepickerlibrary/ApplicationTest.java
366
package com.seelight.leaf.timepickerlibrary; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
apache-2.0
anttribe/opengadget
opengadget-runtime/src/main/java/org/anttribe/opengadget/runtime/render/engine/PageEngineException.java
918
/* * 文 件 名: PageEngineException.java * 版 本: opengadget-runtime(Anttribe). All rights reserved * 描 述: <描述> * 修 改 人: zhaoyong * 修改时 间: 2015年1月26日 */ package org.anttribe.opengadget.runtime.render.engine; /** * @author zhaoyong * @version 2014年8月31日 */ public class PageEngineException extends RuntimeException { /** * serialVersionUID */ private static final long serialVersionUID = -5880627517948355223L; /** * @param message */ public PageEngineException(String message) { super(message); } /** * @param cause */ public PageEngineException(Throwable cause) { super(cause); } /** * @param message * @param cause */ public PageEngineException(String message, Throwable cause) { super(message, cause); } }
apache-2.0
lmjacksoniii/hazelcast
hazelcast/src/test/java/com/hazelcast/test/TestStringUtils.java
1202
package com.hazelcast.test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import static com.hazelcast.nio.IOUtil.closeResource; public class TestStringUtils { private static final int READ_BUFFER_SIZE = 8192; public static String fileAsText(File file) { FileInputStream stream = null; InputStreamReader streamReader = null; BufferedReader reader = null; try { stream = new FileInputStream(file); streamReader = new InputStreamReader(stream); reader = new BufferedReader(streamReader); StringBuilder builder = new StringBuilder(); char[] buffer = new char[READ_BUFFER_SIZE]; int read; while ((read = reader.read(buffer, 0, buffer.length)) > 0) { builder.append(buffer, 0, read); } return builder.toString(); } catch (IOException e) { throw new RuntimeException(e); } finally { closeResource(reader); closeResource(streamReader); closeResource(stream); } } }
apache-2.0
griffon/griffon
subprojects/griffon-core-impl/src/main/java/org/codehaus/griffon/runtime/core/configuration/package-info.java
813
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2008-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Configuration implementation <strong>[INTERNAL USE]</strong>. * * @since 2.11.0 */ package org.codehaus.griffon.runtime.core.configuration;
apache-2.0
vladimirdolzhenko/gflogger
perftest/src/test/java/org/gflogger/perftest/Slf4JExample.java
1374
package org.gflogger.perftest; import org.gflogger.GFLoggerBuilder; import org.gflogger.LogLevel; import org.gflogger.LoggerService; import org.gflogger.Slf4JLoggerServiceImpl; import org.gflogger.appender.AppenderFactory; import static org.gflogger.helpers.OptionConverter.getIntProperty; import static org.gflogger.helpers.OptionConverter.getStringProperty; /** * Log4JExample * * @author Vladimir Dolzhenko, vladimir.dolzhenko@gmail.com */ public class Slf4JExample extends AbstractLoggerExample { @Override protected LoggerService createLoggerImpl() { final AppenderFactory[] factories = createAppenderFactories(); final GFLoggerBuilder[] loggers = new GFLoggerBuilder[]{ new GFLoggerBuilder(LogLevel.INFO, "com.db", factories)}; final int count = getIntProperty("org.gflogger.service.count", 1 << 10); final LoggerService impl = new Slf4JLoggerServiceImpl( count, getIntProperty("org.gflogger.service.maxMessageSize", 1 << 8), loggers, factories); return impl; } @Override protected String fileAppenderFileName() { return getStringProperty("org.gflogger.filename", "./logs/dgflogger.log"); } public static void main(final String[] args) throws Throwable { if (args.length > 2) System.in.read(); final Slf4JExample loggerExample = new Slf4JExample(); loggerExample.parseArgs(args); loggerExample.runTest(); } }
apache-2.0
ilscipio/scipio-erp
framework/minilang/src/org/ofbiz/minilang/method/envops/CheckErrors.java
5039
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package org.ofbiz.minilang.method.envops; import java.util.List; import org.ofbiz.base.util.string.FlexibleStringExpander; import org.ofbiz.minilang.MiniLangException; import org.ofbiz.minilang.MiniLangValidate; import org.ofbiz.minilang.SimpleMethod; import org.ofbiz.minilang.method.MethodContext; import org.ofbiz.minilang.method.MethodOperation; import org.w3c.dom.Element; /** * Implements the &lt;check-errors&gt; element. * * @see <a href="https://cwiki.apache.org/confluence/display/OFBIZ/Mini+Language+-+minilang+-+simple-method+-+Reference">Mini-language Referenc</a> */ public final class CheckErrors extends MethodOperation { private final FlexibleStringExpander errorCodeFse; private final FlexibleStringExpander errorListNameFse; public CheckErrors(Element element, SimpleMethod simpleMethod) throws MiniLangException { super(element, simpleMethod); if (MiniLangValidate.validationOn()) { MiniLangValidate.attributeNames(simpleMethod, element, "error-code", "error-list-name"); MiniLangValidate.noChildElements(simpleMethod, element); } this.errorCodeFse = FlexibleStringExpander.getInstance(element.getAttribute("error-code")); this.errorListNameFse = FlexibleStringExpander.getInstance(MiniLangValidate.checkAttribute(element.getAttribute("error-list-name"), "error_list")); } @Override public boolean exec(MethodContext methodContext) throws MiniLangException { if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "Begin check-errors."); } List<Object> messages = methodContext.getEnv(this.errorListNameFse.expandString(methodContext.getEnvMap())); if (messages != null && messages.size() > 0) { if (methodContext.getMethodType() == MethodContext.EVENT) { methodContext.putEnv(simpleMethod.getEventErrorMessageListName(), messages); methodContext.putEnv(this.simpleMethod.getEventResponseCodeName(), getErrorCode(methodContext)); } else { methodContext.putEnv(simpleMethod.getServiceErrorMessageListName(), messages); methodContext.putEnv(this.simpleMethod.getServiceResponseMessageName(), getErrorCode(methodContext)); } if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "Found error messages. Setting error status and halting script execution."); outputTraceMessage(methodContext, "End check-errors."); } return false; } if (methodContext.isTraceOn()) { outputTraceMessage(methodContext, "No error messages found. Continuing script execution."); outputTraceMessage(methodContext, "End check-errors."); } return true; } private String getErrorCode(MethodContext methodContext) { String errorCode = this.errorCodeFse.expandString(methodContext.getEnvMap()); if (errorCode.isEmpty()) { errorCode = this.simpleMethod.getDefaultErrorCode(); } return errorCode; } @Override public String toString() { StringBuilder sb = new StringBuilder("<check-errors "); if (!this.errorCodeFse.isEmpty()) { sb.append("error-code=\"").append(this.errorCodeFse).append("\" "); } if (!"error_list".equals(this.errorListNameFse.getOriginal())) { sb.append("error-list-name=\"").append(this.errorListNameFse).append("\" "); } sb.append("/>"); return sb.toString(); } /** * A factory for the &lt;check-errors&gt; element. */ public static final class CheckErrorsFactory implements Factory<CheckErrors> { @Override public CheckErrors createMethodOperation(Element element, SimpleMethod simpleMethod) throws MiniLangException { return new CheckErrors(element, simpleMethod); } @Override public String getName() { return "check-errors"; } } }
apache-2.0
bibliolabs/rome
rome-modules/src/test/java/com/rometools/modules/base/io/GoogleBaseParserTest.java
35407
/* * GoogleBaseParserTest.java * JUnit based test * * Created on November 17, 2005, 4:49 PM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.rometools.modules.base.io; import java.io.File; import java.net.URL; import java.util.Calendar; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rometools.modules.AbstractTestCase; import com.rometools.modules.base.Article; import com.rometools.modules.base.Course; import com.rometools.modules.base.Event; import com.rometools.modules.base.GoogleBase; import com.rometools.modules.base.Housing; import com.rometools.modules.base.Job; import com.rometools.modules.base.Person; import com.rometools.modules.base.Product; import com.rometools.modules.base.Review; import com.rometools.modules.base.ScholarlyArticle; import com.rometools.modules.base.Service; import com.rometools.modules.base.Travel; import com.rometools.modules.base.Vehicle; import com.rometools.modules.base.Wanted; import com.rometools.modules.base.io.GoogleBaseParser; import com.rometools.modules.base.types.CurrencyEnumeration; import com.rometools.modules.base.types.FloatUnit; import com.rometools.modules.base.types.GenderEnumeration; import com.rometools.modules.base.types.PaymentTypeEnumeration; import com.rometools.modules.base.types.PriceTypeEnumeration; import com.rometools.modules.base.types.ShippingType; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.SyndFeedInput; /** * * @author rcooper */ public class GoogleBaseParserTest extends AbstractTestCase { private static final Logger LOG = LoggerFactory.getLogger(GoogleBaseParserTest.class); public GoogleBaseParserTest(final String testName) { super(testName); } public static Test suite() { final TestSuite suite = new TestSuite(GoogleBaseParserTest.class); return suite; } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testQuickParse() throws Exception { try { LOG.debug("testParse"); final SyndFeedInput input = new SyndFeedInput(); final File testDir = new File(super.getTestFile("xml")); final File[] testFiles = testDir.listFiles(); for (int h = 0; h < testFiles.length; h++) { if (!testFiles[h].getName().endsWith(".xml")) { continue; } SyndFeed feed = null; try { feed = input.build(testFiles[h]); } catch (final Exception e) { throw new RuntimeException(testFiles[h].getAbsolutePath(), e); } final List<SyndEntry> entries = feed.getEntries(); for (int i = 0; i < entries.size(); i++) { final SyndEntry entry = entries.get(i); LOG.debug("{}", entry.getModules().size()); for (int j = 0; j < entry.getModules().size(); j++) { LOG.debug("{}", entry.getModules().get(j).getClass()); if (entry.getModules().get(j) instanceof GoogleBase) { final GoogleBase base = (GoogleBase) entry.getModules().get(j); LOG.debug(testFiles[h].getName()); LOG.debug(super.beanToString(base, false)); } } } } } catch (final Exception e) { e.printStackTrace(); throw e; } } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testCourse2Parse() throws Exception { LOG.debug("testCourse2Parse"); final SyndFeedInput input = new SyndFeedInput(); final SyndFeed feed = input.build(new File(super.getTestFile("xml/courses2.xml"))); final List<SyndEntry> entries = feed.getEntries(); SyndEntry entry = entries.get(0); Course course = (Course) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", course.getImageLinks()[0].toString()); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); cal.set(2005, 10, 30, 0, 0, 0); Assert.assertEquals("Course Date", cal.getTime(), course.getExpirationDate()); String[] labels = new String[] { "robots", "society", "computers" }; this.assertEquals("Labels", labels, course.getLabels()); cal.set(2005, 7, 19, 8, 30, 00); Assert.assertEquals("Start Time", cal.getTime(), course.getCourseDateRange().getStart()); cal.set(2005, 11, 20, 9, 45, 00); Assert.assertEquals("End Time", cal.getTime(), course.getCourseDateRange().getEnd()); Assert.assertEquals("Course Number", "CS 230", course.getCourseNumber()); Assert.assertEquals("Coutse Times", "MWF 08:30-09:00", course.getCourseTimes()); this.assertEquals("Subject", new String[] { "computer science" }, course.getSubjects()); Assert.assertEquals("University", "Johnson State", course.getUniversity()); entry = entries.get(1); course = (Course) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", course.getImageLinks()[0].toString()); cal = Calendar.getInstance(); cal.setTimeInMillis(0); cal.set(2005, 10, 30, 0, 0, 0); Assert.assertEquals("Course Date", cal.getTime(), course.getExpirationDate()); labels = new String[] { "film", "video", "documentary" }; this.assertEquals("Labels", labels, course.getLabels()); cal.set(2005, 7, 19, 8, 30, 00); Assert.assertEquals("Start Time", cal.getTime(), course.getCourseDateRange().getStart()); cal.set(2005, 11, 20, 9, 45, 00); Assert.assertEquals("End Time", cal.getTime(), course.getCourseDateRange().getEnd()); Assert.assertEquals("Course Number", "FS 192", course.getCourseNumber()); Assert.assertEquals("Coutse Times", "TTh 14:00-16:00", course.getCourseTimes()); Assert.assertEquals("Subject", "film", course.getSubjects()[0]); Assert.assertEquals("University", "Johnson State", course.getUniversity()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testEvent2Parse() throws Exception { LOG.debug("testEvent2Parse"); final SyndFeedInput input = new SyndFeedInput(); final SyndFeed feed = input.build(new File(super.getTestFile("xml/events2.xml"))); final List<SyndEntry> entries = feed.getEntries(); SyndEntry entry = entries.get(0); Event event = (Event) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", event.getImageLinks()[0].toString()); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), event.getExpirationDate()); this.assertEquals("Labels", new String[] { "Festival", "Halloween", "Party", "Costumes" }, event.getLabels()); Assert.assertEquals("Currency", CurrencyEnumeration.USD, event.getCurrency()); Assert.assertEquals("Price", 10, event.getPrice().getValue(), 0); Assert.assertEquals("PriceUnit", null, event.getPrice().getUnits()); Assert.assertEquals("PriceType", PriceTypeEnumeration.STARTING, event.getPriceType()); this.assertEquals("Payment Accepted", new PaymentTypeEnumeration[] { PaymentTypeEnumeration.CASH, PaymentTypeEnumeration.CHECK, PaymentTypeEnumeration.VISA }, event.getPaymentAccepted()); Assert.assertEquals("Payment Notes", "Cash only for local orders", event.getPaymentNotes()); /* * <g:event_date_range> <g:start>2005-07-04T20:00:00</g:start> * <g:end>2005-07-04T23:00:00</g:end> </g:event_date_range> */ cal.set(2005, 06, 04, 20, 00, 00); Assert.assertEquals("Start Time", cal.getTime(), event.getEventDateRange().getStart()); cal.set(2005, 06, 04, 23, 00, 00); Assert.assertEquals("End Time", cal.getTime(), event.getEventDateRange().getEnd()); Assert.assertEquals("Location", "1600 Amphitheatre Parkway, Mountain View, CA, 94043", event.getLocation()); Assert.assertEquals("Shipping Price", (float) 32.95, event.getShipping()[0].getPrice().getValue(), 0); // TODO: Determine what to do about the bogus services. Assert.assertEquals("Shipping Country", "US", event.getShipping()[0].getCountry()); Assert.assertEquals("Tax Region", "California", event.getTaxRegion()); Assert.assertEquals("Tax Percentage", new Float(8.25), event.getTaxPercent()); entry = entries.get(1); event = (Event) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image2.jpg", event.getImageLinks()[0].toString()); cal.setTimeInMillis(0); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), event.getExpirationDate()); this.assertEquals("Labels", new String[] { "Concert", "festival", "music" }, event.getLabels()); Assert.assertEquals("Currency", CurrencyEnumeration.USD, event.getCurrency()); Assert.assertEquals("Price", 50, event.getPrice().getValue(), 0); Assert.assertEquals("PriceUnit", null, event.getPrice().getUnits()); Assert.assertEquals("PriceType", PriceTypeEnumeration.STARTING, event.getPriceType()); this.assertEquals("Payment Accepted", new PaymentTypeEnumeration[] { PaymentTypeEnumeration.CASH, PaymentTypeEnumeration.CHECK, PaymentTypeEnumeration.VISA }, event.getPaymentAccepted()); Assert.assertEquals("Payment Notes", "Cash only for local orders", event.getPaymentNotes()); /* * <g:event_date_range> <g:start>2005-08-23T20:00:00</g:start> * <g:end>2005-08-23T23:00:00</g:end> </g:event_date_range> */ cal.set(2005, 07, 23, 20, 00, 00); Assert.assertEquals("Start Time", cal.getTime(), event.getEventDateRange().getStart()); cal.set(2005, 07, 23, 23, 00, 00); Assert.assertEquals("End Time", cal.getTime(), event.getEventDateRange().getEnd()); Assert.assertEquals("Location", "123 Main St, Anytown, CA, 12345, USA", event.getLocation()); Assert.assertEquals("Shipping Price", (float) 32.95, event.getShipping()[0].getPrice().getValue(), 0); // TODO: Determine what to do about the bogus services. Assert.assertEquals("Shipping Country", "US", event.getShipping()[0].getCountry()); Assert.assertEquals("Tax Region", "California", event.getTaxRegion()); Assert.assertEquals("Tax Percentage", new Float(8.25), event.getTaxPercent()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testHousing2Parse() throws Exception { LOG.debug("testHousing2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/housing2.xml"))); final List<SyndEntry> entries = feed.getEntries(); SyndEntry entry = entries.get(0); Housing module = (Housing) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2007, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Housing", "New House", "Sale" }, module.getLabels()); Assert.assertEquals("Currency", CurrencyEnumeration.USD, module.getCurrency()); Assert.assertEquals("Price", 350000, module.getPrice().getValue(), 0); Assert.assertEquals("PriceUnit", null, module.getPrice().getUnits()); Assert.assertEquals("PriceType", PriceTypeEnumeration.STARTING, module.getPriceType()); this.assertEquals("Payment Accepted", new PaymentTypeEnumeration[] { PaymentTypeEnumeration.CASH, PaymentTypeEnumeration.CHECK, PaymentTypeEnumeration.VISA }, module.getPaymentAccepted()); Assert.assertEquals("Payment Notes", "1000 deposit", module.getPaymentNotes()); Assert.assertEquals("Listing Type", new Boolean(true), module.getListingType()); this.assertEquals("PropertyTypes", new String[] { "Townhouse" }, module.getPropertyTypes()); Assert.assertEquals("Location", "123 Main St, Anytown, CA, 12345, USA", module.getLocation()); Assert.assertEquals("Bedrooms", new Integer(3), module.getBedrooms()); Assert.assertEquals("Bathrooms", new Float(3), module.getBathrooms()); Assert.assertEquals("Area", 1300, module.getArea().getValue()); Assert.assertEquals("Area Units", null, module.getArea().getUnits()); Assert.assertEquals("School District", "Union School District", module.getSchoolDistrict()); Assert.assertEquals("HOA Dues", new Float(120), module.getHoaDues()); Assert.assertEquals("Year", "2005", module.getYear().toString()); this.assertEquals("Agents", new String[] { "Sue Smith" }, module.getAgents()); Assert.assertEquals("Tax Region", "California", module.getTaxRegion()); Assert.assertEquals("Tax Percentage", new Float(8.25), module.getTaxPercent()); entry = entries.get(1); module = (Housing) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image2.jpg", module.getImageLinks()[0].toString()); cal.set(2008, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Housing", "rent", "lease" }, module.getLabels()); Assert.assertEquals("Currency", CurrencyEnumeration.USD, module.getCurrency()); Assert.assertEquals("Price", 1400, module.getPrice().getValue(), 0); Assert.assertEquals("PriceUnit", null, module.getPrice().getUnits()); Assert.assertEquals("PriceType", PriceTypeEnumeration.STARTING, module.getPriceType()); this.assertEquals("Payment Accepted", new PaymentTypeEnumeration[] { PaymentTypeEnumeration.CHECK }, module.getPaymentAccepted()); Assert.assertEquals("Payment Notes", "1000 deposit", module.getPaymentNotes()); Assert.assertEquals("Listing Type", new Boolean(false), module.getListingType()); this.assertEquals("PropertyTypes", new String[] { "apartment" }, module.getPropertyTypes()); Assert.assertEquals("Location", "123 Main St, Anytown, CA, 12345, USA", module.getLocation()); Assert.assertEquals("Bedrooms", new Integer(2), module.getBedrooms()); Assert.assertEquals("Bathrooms", new Float(2), module.getBathrooms()); Assert.assertEquals("Area", 1100, module.getArea().getValue()); Assert.assertEquals("Area Units", null, module.getArea().getUnits()); Assert.assertEquals("School District", "Union School District", module.getSchoolDistrict()); Assert.assertEquals("HOA Dues", null, module.getHoaDues()); Assert.assertEquals("Year", "2004", module.getYear().toString()); this.assertEquals("Agents", new String[] { "Sue Smith" }, module.getAgents()); Assert.assertEquals("Tax Region", null, module.getTaxRegion()); Assert.assertEquals("Tax Percentage", null, module.getTaxPercent()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testJobs2Parse() throws Exception { LOG.debug("testJobs2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/jobs2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Job module = (Job) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Coordinator", "Google", "Online Support" }, module.getLabels()); this.assertEquals("Industriy", new String[] { "Internet" }, module.getJobIndustries()); Assert.assertEquals("Employer", "Google, Inc", module.getEmployer()); this.assertEquals("Job Function", new String[] { "Google Coordinator" }, module.getJobFunctions()); LOG.debug("{}", new Object[] { module.getJobTypes() }); this.assertEquals("Job Type", new String[] { "full-time" }, module.getJobTypes()); Assert.assertEquals("Currency", CurrencyEnumeration.USD, module.getCurrency()); Assert.assertEquals("Salary", new Float(40000), module.getSalary()); Assert.assertEquals("Salary Type", PriceTypeEnumeration.STARTING, module.getSalaryType()); Assert.assertEquals("Education", "BS", module.getEducation()); Assert.assertEquals("Immigration", "Permanent Resident", module.getImmigrationStatus()); Assert.assertEquals("Location", "1600 Amphitheatre Parkway, Mountain View, CA, 94043, USA", module.getLocation()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testNews2Parse() throws Exception { LOG.debug("testNews2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/news2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Article module = (Article) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2007, 2, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "news", "old" }, module.getLabels()); Assert.assertEquals("Source", "Journal", module.getNewsSource()); cal.set(1961, 3, 12, 0, 0, 0); Assert.assertEquals("Pub Date", cal.getTime(), module.getPublishDate()); this.assertEquals("Authors", new String[] { "James Smith" }, module.getAuthors()); Assert.assertEquals("Pages", new Integer(1), module.getPages()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testTravel2Parse() throws Exception { LOG.debug("testTravel2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/travel2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Travel module = (Travel) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Vacation", "Train" }, module.getLabels()); Assert.assertEquals("Currency", CurrencyEnumeration.USD, module.getCurrency()); Assert.assertEquals("Price", 250, module.getPrice().getValue(), 0); Assert.assertEquals("PriceUnit", null, module.getPrice().getUnits()); Assert.assertEquals("PriceType", PriceTypeEnumeration.STARTING, module.getPriceType()); this.assertEquals("Payment Accepted", new PaymentTypeEnumeration[] { PaymentTypeEnumeration.CHECK, PaymentTypeEnumeration.VISA }, module.getPaymentAccepted()); Assert.assertEquals("Payment notes", "minimum payment on credit cards:45", module.getPaymentNotes()); Assert.assertEquals("Quantity", new Integer(204), module.getQuantity()); Assert.assertEquals("From", "Mytown, USA", module.getFromLocation()); Assert.assertEquals("To", "Anytown, USA", module.getToLocation()); cal.set(2005, 11, 20, 18, 0, 0); Assert.assertEquals("Start Date", cal.getTime(), module.getTravelDateRange().getStart()); cal.set(2005, 11, 22, 18, 0, 0); Assert.assertEquals("End Date", cal.getTime(), module.getTravelDateRange().getEnd()); Assert.assertEquals("Location", "123 Main St, Mytown, CA, 12345, USA", module.getLocation()); this.assertEquals("Shipping", new ShippingType[] { new ShippingType(new FloatUnit("32.95"), ShippingType.ServiceEnumeration.OVERNIGHT, "US") }, module.getShipping()); Assert.assertEquals("Tax Region", "California", module.getTaxRegion()); Assert.assertEquals("Tax Percentage", new Float(8.25), module.getTaxPercent()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testPersona2Parse() throws Exception { LOG.debug("testPerson2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/personals2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Person module = (Person) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Personals", "m4w" }, module.getLabels()); this.assertEquals("Ethnicity", new String[] { "South Asian" }, module.getEthnicities()); Assert.assertEquals("Gender", GenderEnumeration.MALE, module.getGender()); Assert.assertEquals("Sexual Orientation", "straight", module.getSexualOrientation()); this.assertEquals("Interested In", new String[] { "Single Women" }, module.getInterestedIn()); Assert.assertEquals("Marital Status", "single", module.getMaritalStatus()); Assert.assertEquals("Occupation", "Sales", module.getOccupation()); Assert.assertEquals("Employer", "Google, Inc.", module.getEmployer()); Assert.assertEquals("Age", new Integer(23), module.getAge()); Assert.assertEquals("Location", "Anytown, 12345, USA", module.getLocation()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testProduct2Parse() throws Exception { LOG.debug("testProduct2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/products2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Product module = (Product) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.googlestore.com/appliance/images/products/GO0144E.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "web search", "appliance" }, module.getLabels()); Assert.assertEquals("Currency", CurrencyEnumeration.USD, module.getCurrency()); Assert.assertEquals("Price", 2995, module.getPrice().getValue(), 0); Assert.assertEquals("PriceType", PriceTypeEnumeration.STARTING, module.getPriceType()); this.assertEquals("Payment Accepted", new PaymentTypeEnumeration[] { PaymentTypeEnumeration.CHECK, PaymentTypeEnumeration.MASTERCARD }, module.getPaymentAccepted()); Assert.assertEquals("Payment Notes", "financing available", module.getPaymentNotes()); Assert.assertEquals("Brand", "Google", module.getBrand()); Assert.assertEquals("UPC", "12348573", module.getUpc()); Assert.assertEquals("Manufacturer", "Google", module.getManufacturer()); Assert.assertEquals("ManufacturerId", "2325", module.getManufacturerId()); Assert.assertEquals("Model number", "234", module.getModelNumber()); LOG.debug("{}", module.getSize()); Assert.assertEquals("Size", 10, module.getSize().getLength().getValue(), 0); Assert.assertEquals("Size", 50, module.getSize().getWidth().getValue(), 0); Assert.assertEquals("Size", 20, module.getSize().getHeight().getValue(), 0); Assert.assertEquals("Weight", 2, module.getWeight().getValue(), 0); Assert.assertEquals("Quantity", new Integer(300), module.getQuantity()); Assert.assertEquals("Condition", "new", module.getCondition()); this.assertEquals("Colors", new String[] { "blue" }, module.getColors()); Assert.assertEquals("Location", "1600 Amphitheatre Pkwy Mountain View, CA 94043-1351, US", module.getLocation()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testResearch2Parse() throws Exception { LOG.debug("testResearch2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/research2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final ScholarlyArticle module = (ScholarlyArticle) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Economy", "Tsunami" }, module.getLabels()); cal.set(2005, 1, 25); Assert.assertEquals("PubDate", cal.getTime(), module.getPublishDate()); this.assertEquals("Authors", new String[] { "James Smith" }, module.getAuthors()); Assert.assertEquals("Pub Name", "Tsunami and the Economy", module.getPublicationName()); Assert.assertEquals("Pub Vol", "III", module.getPublicationVolume()); Assert.assertEquals("Pages", new Integer(5), module.getPages()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testReview2Parse() throws Exception { LOG.debug("testReview2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/reviews2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Review module = (Review) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Review", "Earth", "Google" }, module.getLabels()); cal.set(2005, 2, 24); Assert.assertEquals("PubDate", cal.getTime(), module.getPublishDate()); this.assertEquals("Authors", new String[] { "Jimmy Smith" }, module.getAuthors()); Assert.assertEquals("Name of Item Rev", "Google Earth", module.getNameOfItemBeingReviewed()); Assert.assertEquals("Type", "Product", module.getReviewType()); Assert.assertEquals("Rever Type", "editorial", module.getReviewerType()); Assert.assertEquals("Rating", new Float(5), module.getRating()); Assert.assertEquals("URL of Item", new URL("http://earth.google.com/"), module.getUrlOfItemBeingReviewed()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testService2Parse() throws Exception { LOG.debug("testService2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/services2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Service module = (Service) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Food delivery" }, module.getLabels()); cal.set(2005, 2, 24); Assert.assertEquals("Currency", CurrencyEnumeration.USD, module.getCurrency()); Assert.assertEquals("Price", 15, module.getPrice().getValue(), 0); Assert.assertEquals("PriceType", PriceTypeEnumeration.STARTING, module.getPriceType()); this.assertEquals("Payment Accepted", new PaymentTypeEnumeration[] { PaymentTypeEnumeration.VISA, PaymentTypeEnumeration.MASTERCARD }, module.getPaymentAccepted()); Assert.assertEquals("Payment Notes", "minimum payment on credit cards:45", module.getPaymentNotes()); Assert.assertEquals("Service Type", "delivery", module.getServiceType()); Assert.assertEquals("Location", "Anytown, CA, USA", module.getLocation()); Assert.assertEquals("DeliveryRad", 20, module.getDeliveryRadius().getValue(), 0); Assert.assertEquals("Delivery Notes", "will deliver between 9am -5pm", module.getDeliveryNotes()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testVehicle2Parse() throws Exception { LOG.debug("testVehicle2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/vehicles2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Vehicle module = (Vehicle) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "car", "mini" }, module.getLabels()); cal.set(2005, 2, 24); Assert.assertEquals("Currency", CurrencyEnumeration.USD, module.getCurrency()); Assert.assertEquals("Price", 24000, module.getPrice().getValue(), 0); Assert.assertEquals("PriceType", PriceTypeEnumeration.STARTING, module.getPriceType()); this.assertEquals("Payment Accepted", new PaymentTypeEnumeration[] { PaymentTypeEnumeration.CHECK, PaymentTypeEnumeration.VISA, PaymentTypeEnumeration.MASTERCARD }, module.getPaymentAccepted()); Assert.assertEquals("Payment Notes", "financing available", module.getPaymentNotes()); Assert.assertEquals("Vehicle Type", "car", module.getVehicleType()); Assert.assertEquals("Make", "Mini", module.getMake()); Assert.assertEquals("Model", "Cooper S", module.getModel()); Assert.assertEquals("Year", "2006", module.getYear().toString()); Assert.assertEquals("Mileage", new Integer(0), module.getMileage()); this.assertEquals("Colors", new String[] { "red" }, module.getColors()); Assert.assertEquals("Vin", "1M8GDM9AXKP042788", module.getVin()); Assert.assertEquals("Location", "123 Main Street, Anytown, CA, 12345, USA", module.getLocation()); } /** * Test of parse method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testWanted2Parse() throws Exception { LOG.debug("testVehicle2Parse"); final SyndFeedInput input = new SyndFeedInput(); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); final SyndFeed feed = input.build(new File(super.getTestFile("xml/wanted2.xml"))); final List<SyndEntry> entries = feed.getEntries(); final SyndEntry entry = entries.get(0); final Wanted module = (Wanted) entry.getModule(GoogleBase.URI); Assert.assertEquals("Image Link", "http://www.providers-website.com/image1.jpg", module.getImageLinks()[0].toString()); cal.set(2005, 11, 20, 0, 0, 0); Assert.assertEquals("Expiration Date", cal.getTime(), module.getExpirationDate()); this.assertEquals("Labels", new String[] { "Wanted", "Truck" }, module.getLabels()); Assert.assertEquals("Location", "123 Main Street, Anytown, CA, 12345, USA", module.getLocation()); } /** * Test of getNamespaceUri method, of class com.totsp.xml.syndication.base.io.GoogleBaseParser. */ public void testGetNamespaceUri() { LOG.debug("testGetNamespaceUri"); LOG.debug(new GoogleBaseParser().getNamespaceUri()); } }
apache-2.0
mohanvive/siddhi
modules/siddhi-core/src/main/java/io/siddhi/core/aggregation/AggregationRuntime.java
38248
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.core.aggregation; import io.siddhi.core.config.SiddhiQueryContext; import io.siddhi.core.event.ComplexEventChunk; import io.siddhi.core.event.state.MetaStateEvent; import io.siddhi.core.event.state.StateEvent; import io.siddhi.core.event.stream.MetaStreamEvent; import io.siddhi.core.event.stream.StreamEvent; import io.siddhi.core.exception.QueryableRecordTableException; import io.siddhi.core.exception.SiddhiAppCreationException; import io.siddhi.core.executor.ConstantExpressionExecutor; import io.siddhi.core.executor.ExpressionExecutor; import io.siddhi.core.executor.VariableExpressionExecutor; import io.siddhi.core.query.input.stream.single.SingleStreamRuntime; import io.siddhi.core.query.processor.ProcessingMode; import io.siddhi.core.query.processor.stream.window.QueryableProcessor; import io.siddhi.core.query.selector.GroupByKeyGenerator; import io.siddhi.core.table.Table; import io.siddhi.core.util.collection.operator.CompiledCondition; import io.siddhi.core.util.collection.operator.CompiledSelection; import io.siddhi.core.util.collection.operator.IncrementalAggregateCompileCondition; import io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder; import io.siddhi.core.util.parser.ExpressionParser; import io.siddhi.core.util.parser.OperatorParser; import io.siddhi.core.util.parser.helper.QueryParserHelper; import io.siddhi.core.util.snapshot.SnapshotService; import io.siddhi.core.util.statistics.LatencyTracker; import io.siddhi.core.util.statistics.MemoryCalculable; import io.siddhi.core.util.statistics.ThroughputTracker; import io.siddhi.core.util.statistics.metrics.Level; import io.siddhi.query.api.aggregation.TimePeriod; import io.siddhi.query.api.aggregation.Within; import io.siddhi.query.api.definition.AbstractDefinition; import io.siddhi.query.api.definition.AggregationDefinition; import io.siddhi.query.api.definition.Attribute; import io.siddhi.query.api.definition.StreamDefinition; import io.siddhi.query.api.exception.SiddhiAppValidationException; import io.siddhi.query.api.execution.query.selection.OutputAttribute; import io.siddhi.query.api.execution.query.selection.Selector; import io.siddhi.query.api.expression.AttributeFunction; import io.siddhi.query.api.expression.Expression; import io.siddhi.query.api.expression.Variable; import io.siddhi.query.api.expression.condition.Compare; import io.siddhi.query.api.expression.constant.BoolConstant; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static io.siddhi.core.util.SiddhiConstants.AGG_EXTERNAL_TIMESTAMP_COL; import static io.siddhi.core.util.SiddhiConstants.AGG_LAST_TIMESTAMP_COL; import static io.siddhi.core.util.SiddhiConstants.AGG_SHARD_ID_COL; import static io.siddhi.core.util.SiddhiConstants.AGG_START_TIMESTAMP_COL; import static io.siddhi.core.util.SiddhiConstants.UNKNOWN_STATE; import static io.siddhi.query.api.expression.Expression.Time.normalizeDuration; /** * Aggregation runtime managing aggregation operations for aggregation definition. */ public class AggregationRuntime implements MemoryCalculable { private static final Logger LOG = Logger.getLogger(AggregationRuntime.class); private AggregationDefinition aggregationDefinition; private boolean isProcessingOnExternalTime; private boolean isDistributed; private List<TimePeriod.Duration> incrementalDurations; private Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap; private Map<TimePeriod.Duration, Table> aggregationTables; private List<String> tableAttributesNameList; private MetaStreamEvent aggregateMetaSteamEvent; private List<ExpressionExecutor> outputExpressionExecutors; private Map<TimePeriod.Duration, List<ExpressionExecutor>> aggregateProcessingExecutorsMap; private ExpressionExecutor shouldUpdateTimestamp; private Map<TimePeriod.Duration, GroupByKeyGenerator> groupByKeyGeneratorMap; private boolean isOptimisedLookup; private List<OutputAttribute> defaultSelectorList; private List<String> groupByVariablesList; private boolean isLatestEventColAdded; private int baseAggregatorBeginIndex; private List<Expression> finalBaseExpressionsList; private IncrementalDataPurger incrementalDataPurger; private IncrementalExecutorsInitialiser incrementalExecutorsInitialiser; private SingleStreamRuntime singleStreamRuntime; private LatencyTracker latencyTrackerFind; private ThroughputTracker throughputTrackerFind; private boolean isFirstEventArrived; public AggregationRuntime(AggregationDefinition aggregationDefinition, boolean isProcessingOnExternalTime, boolean isDistributed, List<TimePeriod.Duration> incrementalDurations, Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap, Map<TimePeriod.Duration, Table> aggregationTables, List<ExpressionExecutor> outputExpressionExecutors, Map<TimePeriod.Duration, List<ExpressionExecutor>> aggregateProcessingExecutorsMap, ExpressionExecutor shouldUpdateTimestamp, Map<TimePeriod.Duration, GroupByKeyGenerator> groupByKeyGeneratorMap, boolean isOptimisedLookup, List<OutputAttribute> defaultSelectorList, List<String> groupByVariablesList, boolean isLatestEventColAdded, int baseAggregatorBeginIndex, List<Expression> finalBaseExpressionList, IncrementalDataPurger incrementalDataPurger, IncrementalExecutorsInitialiser incrementalExecutorInitialiser, SingleStreamRuntime singleStreamRuntime, MetaStreamEvent tableMetaStreamEvent, LatencyTracker latencyTrackerFind, ThroughputTracker throughputTrackerFind) { this.aggregationDefinition = aggregationDefinition; this.isProcessingOnExternalTime = isProcessingOnExternalTime; this.isDistributed = isDistributed; this.incrementalDurations = incrementalDurations; this.incrementalExecutorMap = incrementalExecutorMap; this.aggregationTables = aggregationTables; this.tableAttributesNameList = tableMetaStreamEvent.getInputDefinitions().get(0).getAttributeList() .stream().map(Attribute::getName).collect(Collectors.toList()); this.outputExpressionExecutors = outputExpressionExecutors; this.aggregateProcessingExecutorsMap = aggregateProcessingExecutorsMap; this.shouldUpdateTimestamp = shouldUpdateTimestamp; this.groupByKeyGeneratorMap = groupByKeyGeneratorMap; this.isOptimisedLookup = isOptimisedLookup; this.defaultSelectorList = defaultSelectorList; this.groupByVariablesList = groupByVariablesList; this.isLatestEventColAdded = isLatestEventColAdded; this.baseAggregatorBeginIndex = baseAggregatorBeginIndex; this.finalBaseExpressionsList = finalBaseExpressionList; this.incrementalDataPurger = incrementalDataPurger; this.incrementalExecutorsInitialiser = incrementalExecutorInitialiser; this.singleStreamRuntime = singleStreamRuntime; this.aggregateMetaSteamEvent = new MetaStreamEvent(); aggregationDefinition.getAttributeList().forEach(this.aggregateMetaSteamEvent::addOutputData); this.latencyTrackerFind = latencyTrackerFind; this.throughputTrackerFind = throughputTrackerFind; } private static void initMetaStreamEvent(MetaStreamEvent metaStreamEvent, AbstractDefinition inputDefinition, String inputReferenceId) { metaStreamEvent.addInputDefinition(inputDefinition); metaStreamEvent.setInputReferenceId(inputReferenceId); metaStreamEvent.initializeAfterWindowData(); inputDefinition.getAttributeList().forEach(metaStreamEvent::addData); } private static MetaStreamEvent alterMetaStreamEvent(boolean isOnDemandQuery, MetaStreamEvent originalMetaStreamEvent, List<Attribute> additionalAttributes) { StreamDefinition alteredStreamDef = new StreamDefinition(); String inputReferenceId = originalMetaStreamEvent.getInputReferenceId(); if (!isOnDemandQuery) { for (Attribute attribute : originalMetaStreamEvent.getLastInputDefinition().getAttributeList()) { alteredStreamDef.attribute(attribute.getName(), attribute.getType()); } if (inputReferenceId == null) { alteredStreamDef.setId(originalMetaStreamEvent.getLastInputDefinition().getId()); } } else { // If it is on-demand query, no original join stream alteredStreamDef.setId("OnDemandQueryStream"); } additionalAttributes.forEach(attribute -> alteredStreamDef.attribute(attribute.getName(), attribute.getType())); initMetaStreamEvent(originalMetaStreamEvent, alteredStreamDef, inputReferenceId); return originalMetaStreamEvent; } private static MetaStreamEvent createMetaStoreEvent(AbstractDefinition tableDefinition, String referenceId) { MetaStreamEvent metaStreamEventForTable = new MetaStreamEvent(); metaStreamEventForTable.setEventType(MetaStreamEvent.EventType.TABLE); initMetaStreamEvent(metaStreamEventForTable, tableDefinition, referenceId); return metaStreamEventForTable; } private static MatchingMetaInfoHolder alterMetaInfoHolderForOnDemandQuery( MetaStreamEvent newMetaStreamEventWithStartEnd, MatchingMetaInfoHolder matchingMetaInfoHolder) { MetaStateEvent metaStateEvent = new MetaStateEvent(2); MetaStreamEvent incomingMetaStreamEvent = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(0); metaStateEvent.addEvent(newMetaStreamEventWithStartEnd); metaStateEvent.addEvent(incomingMetaStreamEvent); return new MatchingMetaInfoHolder(metaStateEvent, 0, 1, newMetaStreamEventWithStartEnd.getLastInputDefinition(), incomingMetaStreamEvent.getLastInputDefinition(), UNKNOWN_STATE); } private static MatchingMetaInfoHolder createNewStreamTableMetaInfoHolder(MetaStreamEvent metaStreamEvent, MetaStreamEvent metaStoreEvent) { MetaStateEvent metaStateEvent = new MetaStateEvent(2); metaStateEvent.addEvent(metaStreamEvent); metaStateEvent.addEvent(metaStoreEvent); return new MatchingMetaInfoHolder(metaStateEvent, 0, 1, metaStreamEvent.getLastInputDefinition(), metaStoreEvent.getLastInputDefinition(), UNKNOWN_STATE); } private static List<OutputAttribute> constructSelectorList(boolean isProcessingOnExternalTime, boolean isDistributed, boolean isLatestEventColAdded, int baseAggregatorBeginIndex, int numGroupByVariables, List<Expression> finalBaseExpressions, AbstractDefinition incomingOutputStreamDefinition, List<Variable> newGroupByList) { List<OutputAttribute> selectorList = new ArrayList<>(); List<Attribute> attributeList = incomingOutputStreamDefinition.getAttributeList(); List<String> queryGroupByNames = newGroupByList.stream() .map(Variable::getAttributeName).collect(Collectors.toList()); Variable maxVariable; if (!isProcessingOnExternalTime) { maxVariable = new Variable(AGG_START_TIMESTAMP_COL); } else if (isLatestEventColAdded) { maxVariable = new Variable(AGG_LAST_TIMESTAMP_COL); } else { maxVariable = new Variable(AGG_EXTERNAL_TIMESTAMP_COL); } int i = 0; //Add timestamp selector OutputAttribute timestampAttribute; if (!isProcessingOnExternalTime && queryGroupByNames.contains(AGG_START_TIMESTAMP_COL)) { timestampAttribute = new OutputAttribute(new Variable(AGG_START_TIMESTAMP_COL)); } else { timestampAttribute = new OutputAttribute(attributeList.get(i).getName(), Expression.function("max", new Variable(AGG_START_TIMESTAMP_COL))); } selectorList.add(timestampAttribute); i++; if (isDistributed) { selectorList.add(new OutputAttribute(AGG_SHARD_ID_COL, Expression.function("max", new Variable(AGG_SHARD_ID_COL)))); i++; } if (isProcessingOnExternalTime) { OutputAttribute externalTimestampAttribute; if (queryGroupByNames.contains(AGG_START_TIMESTAMP_COL)) { externalTimestampAttribute = new OutputAttribute(new Variable(AGG_EXTERNAL_TIMESTAMP_COL)); } else { externalTimestampAttribute = new OutputAttribute(attributeList.get(i).getName(), Expression.function("max", new Variable(AGG_EXTERNAL_TIMESTAMP_COL))); } selectorList.add(externalTimestampAttribute); i++; } for (int j = 0; j < numGroupByVariables; j++) { OutputAttribute groupByAttribute; Variable variable = new Variable(attributeList.get(i).getName()); if (queryGroupByNames.contains(variable.getAttributeName())) { groupByAttribute = new OutputAttribute(variable); } else { groupByAttribute = new OutputAttribute(variable.getAttributeName(), Expression.function("incrementalAggregator", "last", new Variable(attributeList.get(i).getName()), maxVariable)); } selectorList.add(groupByAttribute); i++; } if (isLatestEventColAdded) { baseAggregatorBeginIndex = baseAggregatorBeginIndex - 1; } for (; i < baseAggregatorBeginIndex; i++) { OutputAttribute outputAttribute; Variable variable = new Variable(attributeList.get(i).getName()); if (queryGroupByNames.contains(variable.getAttributeName())) { outputAttribute = new OutputAttribute(variable); } else { outputAttribute = new OutputAttribute(attributeList.get(i).getName(), Expression.function("incrementalAggregator", "last", new Variable(attributeList.get(i).getName()), maxVariable)); } selectorList.add(outputAttribute); } if (isLatestEventColAdded) { OutputAttribute lastTimestampAttribute = new OutputAttribute(AGG_LAST_TIMESTAMP_COL, Expression.function("max", new Variable(AGG_LAST_TIMESTAMP_COL))); selectorList.add(lastTimestampAttribute); i++; } for (Expression finalBaseExpression : finalBaseExpressions) { OutputAttribute outputAttribute = new OutputAttribute(attributeList.get(i).getName(), finalBaseExpression); selectorList.add(outputAttribute); i++; } return selectorList; } public AggregationDefinition getAggregationDefinition() { return aggregationDefinition; } public SingleStreamRuntime getSingleStreamRuntime() { return singleStreamRuntime; } public StreamEvent find(StateEvent matchingEvent, CompiledCondition compiledCondition, SiddhiQueryContext siddhiQueryContext) { try { SnapshotService.getSkipStateStorageThreadLocal().set(true); if (latencyTrackerFind != null && Level.BASIC.compareTo(siddhiQueryContext.getSiddhiAppContext().getRootMetricsLevel()) <= 0) { latencyTrackerFind.markIn(); throughputTrackerFind.eventIn(); } if (!isDistributed && !isFirstEventArrived) { // No need to initialise executors if it is distributed initialiseExecutors(false); } return ((IncrementalAggregateCompileCondition) compiledCondition).find(matchingEvent, incrementalExecutorMap, aggregateProcessingExecutorsMap, groupByKeyGeneratorMap, shouldUpdateTimestamp); } finally { SnapshotService.getSkipStateStorageThreadLocal().set(null); if (latencyTrackerFind != null && Level.BASIC.compareTo(siddhiQueryContext.getSiddhiAppContext().getRootMetricsLevel()) <= 0) { latencyTrackerFind.markOut(); } } } public CompiledCondition compileExpression(Expression expression, Within within, Expression per, List<Variable> queryGroupByList, MatchingMetaInfoHolder matchingMetaInfoHolder, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, Table> tableMap, SiddhiQueryContext siddhiQueryContext) { String aggregationName = aggregationDefinition.getId(); boolean isOptimisedTableLookup = isOptimisedLookup; Map<TimePeriod.Duration, CompiledCondition> withinTableCompiledConditions = new HashMap<>(); CompiledCondition withinInMemoryCompileCondition; CompiledCondition onCompiledCondition; List<Attribute> additionalAttributes = new ArrayList<>(); // Define additional attribute list additionalAttributes.add(new Attribute("_START", Attribute.Type.LONG)); additionalAttributes.add(new Attribute("_END", Attribute.Type.LONG)); int lowerGranularitySize = this.incrementalDurations.size() - 1; List<String> lowerGranularityAttributes = new ArrayList<>(); if (isDistributed) { //Add additional attributes to get base aggregation timestamps based on current timestamps // for values calculated in in-memory in the shards for (int i = 0; i < lowerGranularitySize; i++) { String attributeName = "_AGG_TIMESTAMP_FILTER_" + i; additionalAttributes.add(new Attribute(attributeName, Attribute.Type.LONG)); lowerGranularityAttributes.add(attributeName); } } // Get table definition. Table definitions for all the tables used to persist aggregates are similar. // Therefore it's enough to get the definition from one table. AbstractDefinition tableDefinition = aggregationTables.get(incrementalDurations.get(0)).getTableDefinition(); boolean isOnDemandQuery = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvents().length == 1; // Alter existing meta stream event or create new one if a meta stream doesn't exist // After calling this method the original MatchingMetaInfoHolder's meta stream event would be altered // Alter meta info holder to contain stream event and aggregate both when it's a on-demand query MetaStreamEvent metaStreamEventForTableLookups; if (isOnDemandQuery) { metaStreamEventForTableLookups = alterMetaStreamEvent(true, new MetaStreamEvent(), additionalAttributes); matchingMetaInfoHolder = alterMetaInfoHolderForOnDemandQuery(metaStreamEventForTableLookups, matchingMetaInfoHolder); } else { metaStreamEventForTableLookups = alterMetaStreamEvent(false, matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(0), additionalAttributes); } // Create new MatchingMetaInfoHolder containing newMetaStreamEventWithStartEnd and table meta event String aggReferenceId = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(1).getInputReferenceId(); String referenceName = aggReferenceId == null ? aggregationName : aggReferenceId; MetaStreamEvent metaStoreEventForTableLookups = createMetaStoreEvent(tableDefinition, referenceName); // Create new MatchingMetaInfoHolder containing metaStreamEventForTableLookups and table meta event MatchingMetaInfoHolder metaInfoHolderForTableLookups = createNewStreamTableMetaInfoHolder( metaStreamEventForTableLookups, metaStoreEventForTableLookups); // Create per expression executor ExpressionExecutor perExpressionExecutor; if (per != null) { perExpressionExecutor = ExpressionParser.parseExpression(per, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext); if (perExpressionExecutor.getReturnType() != Attribute.Type.STRING) { throw new SiddhiAppCreationException( "Query " + siddhiQueryContext.getName() + "'s per value expected a string but found " + perExpressionExecutor.getReturnType(), per.getQueryContextStartIndex(), per.getQueryContextEndIndex()); } // Additional Per time function verification at compile time if it is a constant if (perExpressionExecutor instanceof ConstantExpressionExecutor) { String perValue = ((ConstantExpressionExecutor) perExpressionExecutor).getValue().toString(); try { normalizeDuration(perValue); } catch (SiddhiAppValidationException e) { throw new SiddhiAppValidationException( "Aggregation Query's per value is expected to be of a valid time function of the " + "following " + TimePeriod.Duration.SECONDS + ", " + TimePeriod.Duration.MINUTES + ", " + TimePeriod.Duration.HOURS + ", " + TimePeriod.Duration.DAYS + ", " + TimePeriod.Duration.MONTHS + ", " + TimePeriod.Duration.YEARS + "."); } } } else { throw new SiddhiAppCreationException("Syntax Error: Aggregation join query must contain a `per` " + "definition for granularity"); } // Create start and end time expression Expression startEndTimeExpression; ExpressionExecutor startTimeEndTimeExpressionExecutor; if (within != null) { if (within.getTimeRange().size() == 1) { startEndTimeExpression = new AttributeFunction("incrementalAggregator", "startTimeEndTime", within.getTimeRange().get(0)); } else { // within.getTimeRange().size() == 2 startEndTimeExpression = new AttributeFunction("incrementalAggregator", "startTimeEndTime", within.getTimeRange().get(0), within.getTimeRange().get(1)); } startTimeEndTimeExpressionExecutor = ExpressionParser.parseExpression(startEndTimeExpression, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext); } else { throw new SiddhiAppCreationException("Syntax Error : Aggregation read query must contain a `within` " + "definition for filtering of aggregation data."); } // Create within expression Expression timeFilterExpression; if (isProcessingOnExternalTime) { timeFilterExpression = Expression.variable(AGG_EXTERNAL_TIMESTAMP_COL); } else { timeFilterExpression = Expression.variable(AGG_START_TIMESTAMP_COL); } Expression withinExpression; Expression start = Expression.variable(additionalAttributes.get(0).getName()); Expression end = Expression.variable(additionalAttributes.get(1).getName()); Expression compareWithStartTime = Compare.compare(start, Compare.Operator.LESS_THAN_EQUAL, timeFilterExpression); Expression compareWithEndTime = Compare.compare(timeFilterExpression, Compare.Operator.LESS_THAN, end); withinExpression = Expression.and(compareWithStartTime, compareWithEndTime); List<ExpressionExecutor> timestampFilterExecutors = new ArrayList<>(); if (isDistributed) { for (int i = 0; i < lowerGranularitySize; i++) { Expression[] expressionArray = new Expression[]{ new AttributeFunction("", "currentTimeMillis", null), Expression.value(this.incrementalDurations.get(i + 1).toString())}; Expression filterExpression = new AttributeFunction("incrementalAggregator", "getAggregationStartTime", expressionArray); timestampFilterExecutors.add(ExpressionParser.parseExpression(filterExpression, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext)); } } // Create compile condition per each table used to persist aggregates. // These compile conditions are used to check whether the aggregates in tables are within the given duration. // Combine with and on condition for table query boolean shouldApplyReducedCondition = false; Expression reducedExpression = null; //Check if there is no on conditions if (!(expression instanceof BoolConstant)) { // For abstract queryable table AggregationExpressionBuilder aggregationExpressionBuilder = new AggregationExpressionBuilder(expression); AggregationExpressionVisitor expressionVisitor = new AggregationExpressionVisitor( metaStreamEventForTableLookups.getInputReferenceId(), metaStreamEventForTableLookups.getLastInputDefinition().getAttributeList(), this.tableAttributesNameList ); aggregationExpressionBuilder.build(expressionVisitor); shouldApplyReducedCondition = expressionVisitor.applyReducedExpression(); reducedExpression = expressionVisitor.getReducedExpression(); } Expression withinExpressionTable; if (shouldApplyReducedCondition) { withinExpressionTable = Expression.and(withinExpression, reducedExpression); } else { withinExpressionTable = withinExpression; } Variable timestampVariable = new Variable(AGG_START_TIMESTAMP_COL); List<String> queryGroupByNamesList = queryGroupByList.stream() .map(Variable::getAttributeName) .collect(Collectors.toList()); boolean queryGroupByContainsTimestamp = queryGroupByNamesList.remove(AGG_START_TIMESTAMP_COL); boolean isQueryGroupBySameAsAggGroupBy = queryGroupByList.isEmpty() || (queryGroupByList.contains(timestampVariable) && queryGroupByNamesList.equals(groupByVariablesList)); List<VariableExpressionExecutor> variableExpExecutorsForTableLookups = new ArrayList<>(); Map<TimePeriod.Duration, CompiledSelection> withinTableCompiledSelection = new HashMap<>(); if (isOptimisedTableLookup) { Selector selector = Selector.selector(); List<Variable> groupByList = new ArrayList<>(); if (!isQueryGroupBySameAsAggGroupBy) { if (queryGroupByContainsTimestamp) { if (isProcessingOnExternalTime) { groupByList.add(new Variable(AGG_EXTERNAL_TIMESTAMP_COL)); } else { groupByList.add(new Variable(AGG_START_TIMESTAMP_COL)); } //Remove timestamp to process the rest queryGroupByList.remove(timestampVariable); } for (Variable queryGroupBy : queryGroupByList) { String referenceId = queryGroupBy.getStreamId(); if (referenceId == null) { if (tableAttributesNameList.contains(queryGroupBy.getAttributeName())) { groupByList.add(queryGroupBy); } } else if (referenceId.equalsIgnoreCase(referenceName)) { groupByList.add(queryGroupBy); } } // If query group bys are based on joining stream if (groupByList.isEmpty()) { isQueryGroupBySameAsAggGroupBy = true; } } groupByList.forEach((groupBy) -> groupBy.setStreamId(referenceName)); selector.addGroupByList(groupByList); List<OutputAttribute> selectorList; if (!isQueryGroupBySameAsAggGroupBy) { selectorList = constructSelectorList(isProcessingOnExternalTime, isDistributed, isLatestEventColAdded, baseAggregatorBeginIndex, groupByVariablesList.size(), finalBaseExpressionsList, tableDefinition, groupByList); } else { selectorList = defaultSelectorList; } for (OutputAttribute outputAttribute : selectorList) { if (outputAttribute.getExpression() instanceof Variable) { ((Variable) outputAttribute.getExpression()).setStreamId(referenceName); } else { for (Expression parameter : ((AttributeFunction) outputAttribute.getExpression()).getParameters()) { ((Variable) parameter).setStreamId(referenceName); } } } selector.addSelectionList(selectorList); try { aggregationTables.entrySet().forEach( (durationTableEntry -> { CompiledSelection compiledSelection = ((QueryableProcessor) durationTableEntry.getValue()) .compileSelection( selector, tableDefinition.getAttributeList(), metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext ); withinTableCompiledSelection.put(durationTableEntry.getKey(), compiledSelection); }) ); } catch (SiddhiAppCreationException | SiddhiAppValidationException | QueryableRecordTableException e) { if (LOG.isDebugEnabled()) { LOG.debug("Aggregation Query optimization failed for aggregation: '" + aggregationName + "'. " + "Creating table lookup query in normal mode. Reason for failure: " + e.getMessage(), e); } isOptimisedTableLookup = false; } } for (Map.Entry<TimePeriod.Duration, Table> entry : aggregationTables.entrySet()) { CompiledCondition withinTableCompileCondition = entry.getValue().compileCondition(withinExpressionTable, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext); withinTableCompiledConditions.put(entry.getKey(), withinTableCompileCondition); } // Create compile condition for in-memory data. // This compile condition is used to check whether the running aggregates (in-memory data) // are within given duration withinInMemoryCompileCondition = OperatorParser.constructOperator(new ComplexEventChunk<>(), withinExpression, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext); // Create compile condition for in-memory data, in case of distributed // Look at the lower level granularities Map<TimePeriod.Duration, CompiledCondition> withinTableLowerGranularityCompileCondition = new HashMap<>(); Expression lowerGranularity; if (isDistributed) { for (int i = 0; i < lowerGranularitySize; i++) { if (isProcessingOnExternalTime) { lowerGranularity = Expression.and( Expression.compare( Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))), withinExpressionTable ); } else { if (shouldApplyReducedCondition) { lowerGranularity = Expression.and( Expression.compare( Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))), reducedExpression ); } else { lowerGranularity = Expression.compare( Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))); } } TimePeriod.Duration duration = this.incrementalDurations.get(i); String tableName = aggregationName + "_" + duration.toString(); CompiledCondition compiledCondition = tableMap.get(tableName).compileCondition(lowerGranularity, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext); withinTableLowerGranularityCompileCondition.put(duration, compiledCondition); } } QueryParserHelper.reduceMetaComplexEvent(metaInfoHolderForTableLookups.getMetaStateEvent()); // On compile condition. // After finding all the aggregates belonging to within duration, the final on condition (given as // "on stream1.name == aggregator.nickName ..." in the join query) must be executed on that data. // This condition is used for that purpose. onCompiledCondition = OperatorParser.constructOperator(new ComplexEventChunk<>(), expression, matchingMetaInfoHolder, variableExpressionExecutors, tableMap, siddhiQueryContext); return new IncrementalAggregateCompileCondition(isOnDemandQuery, aggregationName, isProcessingOnExternalTime, isDistributed, incrementalDurations, aggregationTables, outputExpressionExecutors, isOptimisedTableLookup, withinTableCompiledSelection, withinTableCompiledConditions, withinInMemoryCompileCondition, withinTableLowerGranularityCompileCondition, onCompiledCondition, additionalAttributes, perExpressionExecutor, startTimeEndTimeExpressionExecutor, timestampFilterExecutors, aggregateMetaSteamEvent, matchingMetaInfoHolder, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups); } public void startPurging() { incrementalDataPurger.executeIncrementalDataPurging(); } public void initialiseExecutors(boolean isFirstEventArrived) { // State only updated when first event arrives to IncrementalAggregationProcessor if (isFirstEventArrived) { this.isFirstEventArrived = true; for (Map.Entry<TimePeriod.Duration, IncrementalExecutor> durationIncrementalExecutorEntry : this.incrementalExecutorMap.entrySet()) { durationIncrementalExecutorEntry.getValue().setProcessingExecutor(true); } } this.incrementalExecutorsInitialiser.initialiseExecutors(); } public void processEvents(ComplexEventChunk<StreamEvent> streamEventComplexEventChunk) { incrementalExecutorMap.get(incrementalDurations.get(0)).execute(streamEventComplexEventChunk); } }
apache-2.0
rdhabalia/pulsar
pulsar-client-tools/src/main/java/com/yahoo/pulsar/client/cli/CmdConsume.java
6161
/** * Copyright 2016 Yahoo Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yahoo.pulsar.client.cli; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.commons.io.HexDump; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.Parameters; import com.google.common.util.concurrent.RateLimiter; import com.yahoo.pulsar.client.api.ClientConfiguration; import com.yahoo.pulsar.client.api.Consumer; import com.yahoo.pulsar.client.api.ConsumerConfiguration; import com.yahoo.pulsar.client.api.Message; import com.yahoo.pulsar.client.api.PulsarClient; import com.yahoo.pulsar.client.api.PulsarClientException; import com.yahoo.pulsar.client.api.SubscriptionType; /** * pulsar-client consume command implementation. * */ @Parameters(commandDescription = "Consume messages from a specified topic") public class CmdConsume { private static final Logger LOG = LoggerFactory.getLogger(PulsarClientTool.class); private static final String MESSAGE_BOUNDARY = "----- got message -----"; @Parameter(description = "TopicName", required = true) private List<String> mainOptions = new ArrayList<String>(); @Parameter(names = { "-t", "--subscription-type" }, description = "Subscription type: Exclusive, Shared, Failover.") private SubscriptionType subscriptionType = SubscriptionType.Exclusive; @Parameter(names = { "-s", "--subscription-name" }, required = true, description = "Subscription name.") private String subscriptionName; @Parameter(names = { "-n", "--num-messages" }, description = "Number of messages to consume, 0 means to consume forever.") private int numMessagesToConsume = 1; @Parameter(names = { "--hex" }, description = "Display binary messages in hex.") private boolean displayHex = false; @Parameter(names = { "-r", "--rate" }, description = "Rate (in msg/sec) at which to consume, " + "value 0 means to consume messages as fast as possible.") private double consumeRate = 0; private String serviceURL = null; ClientConfiguration clientConfig; public CmdConsume() { // Do nothing } /** * Set client configuration. * */ public void updateConfig(String serviceURL, ClientConfiguration newConfig) { this.serviceURL = serviceURL; this.clientConfig = newConfig; } /** * Interprets the message to create a string representation * * @param message * The message to interpret * @param displayHex * Whether to display BytesMessages in hexdump style, ignored for simple text messages * @return String representation of the message */ private String interpretMessage(Message message, boolean displayHex) throws IOException { byte[] msgData = message.getData(); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (!displayHex) { return new String(msgData); } else { HexDump.dump(msgData, 0, out, 0); return new String(out.toByteArray()); } } /** * Run the consume command. * * @return 0 for success, < 0 otherwise */ public int run() throws PulsarClientException, IOException { if (mainOptions.size() != 1) throw (new ParameterException("Please provide one and only one topic name.")); if (this.serviceURL == null || this.serviceURL.isEmpty()) throw (new ParameterException("Broker URL is not provided.")); if (this.subscriptionName == null || this.subscriptionName.isEmpty()) throw (new ParameterException("Subscription name is not provided.")); if (this.numMessagesToConsume < 0) throw (new ParameterException("Number of messages should be zero or positive.")); String topic = this.mainOptions.get(0); int numMessagesConsumed = 0; int returnCode = 0; try { ConsumerConfiguration consumerConf = new ConsumerConfiguration(); consumerConf.setSubscriptionType(this.subscriptionType); PulsarClient client = PulsarClient.create(this.serviceURL, this.clientConfig); Consumer consumer = client.subscribe(topic, this.subscriptionName, consumerConf); RateLimiter limiter = (this.consumeRate > 0) ? RateLimiter.create(this.consumeRate) : null; while (this.numMessagesToConsume == 0 || numMessagesConsumed < this.numMessagesToConsume) { if (limiter != null) limiter.acquire(); Message msg = consumer.receive(20, TimeUnit.SECONDS); if (msg == null) { LOG.warn("No message to consume after waiting for 20 seconds."); } else { numMessagesConsumed += 1; System.out.println(MESSAGE_BOUNDARY); String output = this.interpretMessage(msg, displayHex); System.out.println(output); consumer.acknowledge(msg); } } client.close(); } catch (Exception e) { LOG.error("Error while consuming messages"); LOG.error(e.getMessage(), e); returnCode = -1; } finally { LOG.info("{} messages successfully consumed", numMessagesConsumed); } return returnCode; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-mediapackagevod/src/main/java/com/amazonaws/services/mediapackagevod/model/transform/CreateAssetRequestProtocolMarshaller.java
2603
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediapackagevod.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.mediapackagevod.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * CreateAssetRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreateAssetRequestProtocolMarshaller implements Marshaller<Request<CreateAssetRequest>, CreateAssetRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/assets") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("AWSMediaPackageVod").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public CreateAssetRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<CreateAssetRequest> marshall(CreateAssetRequest createAssetRequest) { if (createAssetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<CreateAssetRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, createAssetRequest); protocolMarshaller.startMarshalling(); CreateAssetRequestMarshaller.getInstance().marshall(createAssetRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
droidranger/xygapp
xyg-library/src/main/java/com/ranger/xyg/library/tkrefreshlayout/utils/DensityUtil.java
682
package com.ranger.xyg.library.tkrefreshlayout.utils; import android.content.Context; public class DensityUtil { /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */ public static int dp2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ public static int px2dp(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
apache-2.0
GIP-RECIA/cas
core/cas-server-core-logging/src/main/java/org/apereo/cas/logging/config/CasLoggingConfiguration.java
3772
package org.apereo.cas.logging.config; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.logging.web.LoggingConfigurationEndpoint; import org.apereo.cas.logging.web.ThreadContextMDCServletFilter; import org.apereo.cas.ticket.registry.TicketRegistry; import org.apereo.cas.ticket.registry.TicketRegistrySupport; import org.apereo.cas.util.CollectionUtils; import org.apereo.cas.web.support.CookieRetrievingCookieGenerator; import lombok.val; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.web.Log4jServletContextListener; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import java.util.HashMap; /** * This is {@link CasLoggingConfiguration}. * * @author Misagh Moayyed * @since 5.0.0 */ @Configuration("casLoggingConfiguration") @EnableConfigurationProperties(CasConfigurationProperties.class) public class CasLoggingConfiguration { @Autowired @Qualifier("ticketGrantingTicketCookieGenerator") private ObjectProvider<CookieRetrievingCookieGenerator> ticketGrantingTicketCookieGenerator; @Autowired @Qualifier("defaultTicketRegistrySupport") private ObjectProvider<TicketRegistrySupport> ticketRegistrySupport; @ConditionalOnBean(value = TicketRegistry.class) @Bean public FilterRegistrationBean threadContextMDCServletFilter() { val initParams = new HashMap<String, String>(); val bean = new FilterRegistrationBean<ThreadContextMDCServletFilter>(); bean.setFilter(new ThreadContextMDCServletFilter(ticketRegistrySupport.getIfAvailable(), this.ticketGrantingTicketCookieGenerator.getIfAvailable())); bean.setUrlPatterns(CollectionUtils.wrap("/*")); bean.setInitParameters(initParams); bean.setName("threadContextMDCServletFilter"); bean.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); return bean; } /** * Log4j configuration. */ @ConditionalOnClass(LoggerContext.class) @Configuration("casLog4jConfiguration") public static class CasLog4jConfiguration { @Autowired private CasConfigurationProperties casProperties; @Autowired private ResourceLoader resourceLoader; @Autowired private Environment environment; @Bean @ConditionalOnEnabledEndpoint public LoggingConfigurationEndpoint loggingConfigurationEndpoint() { return new LoggingConfigurationEndpoint(casProperties, resourceLoader, environment); } @Bean @Lazy public ServletListenerRegistrationBean log4jServletContextListener() { val bean = new ServletListenerRegistrationBean<Log4jServletContextListener>(); bean.setEnabled(true); bean.setListener(new Log4jServletContextListener()); return bean; } } }
apache-2.0
nablarch/nablarch-etl
src/test/java/nablarch/etl/generator/InsertSqlGeneratorTestSupport.java
2673
package nablarch.etl.generator; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import nablarch.common.dao.DatabaseUtil; import nablarch.core.db.connection.DbConnectionContext; import nablarch.core.db.connection.TransactionManagerConnection; import nablarch.test.support.db.helper.VariousDbTestHelper; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import mockit.Mocked; import mockit.Expectations; /** * InsertSqlGeneratorのテストをサポートするクラス。 */ public class InsertSqlGeneratorTestSupport { @Mocked TransactionManagerConnection mockConnection; Connection connection; @BeforeClass public static void setUpClass() throws Exception { VariousDbTestHelper.createTable(EtlInsertGenEntity.class); } @Before public void setUp() throws Exception { connection = VariousDbTestHelper.getNativeConnection(); new Expectations() {{ mockConnection.getConnection(); result = connection; minTimes = 0; }}; DbConnectionContext.setConnection(mockConnection); } @After public void tearDown() throws Exception { connection.close(); DbConnectionContext.removeConnection(); } protected List<String> getColumnNames(String tableName) throws SQLException { final ResultSet columns = connection.getMetaData() .getColumns(null, null, DatabaseUtil.convertIdentifiers(tableName), null); Map<Integer, String> names = new TreeMap<Integer, String>(); while (columns.next()) { names.put( columns.getInt("ORDINAL_POSITION"), columns.getString("COLUMN_NAME") ); } return new ArrayList<String>(names.values()); } @Entity @Table(name = "etl_insert_gen") public static class EtlInsertGenEntity { @Id @Column(name = "TEST_ID", length = 15) public Long id; @Column(name = "last_name") public String lastName; @Column(name = "first_name") public String firstName; @Id @Column(name = "TEST_ID") public Long getId() { return id; } public String getLastName() { return lastName; } public String getFirstName() { return firstName; } } }
apache-2.0
pjain1/sketches-core
sketches/src/main/java/com/yahoo/sketches/theta/JaccardSimilarity.java
6530
/* * Copyright 2016, Yahoo! Inc. Licensed under the terms of the * Apache License 2.0. See LICENSE file at the project root for terms. */ package com.yahoo.sketches.theta; import static com.yahoo.sketches.BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA; import static com.yahoo.sketches.BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA; import static com.yahoo.sketches.BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA; import static com.yahoo.sketches.Util.ceilingPowerOf2; /** * Jaccard similarity of two Theta Sketches. * * @author Lee Rhodes */ public final class JaccardSimilarity { private static final double[] ZEROS = {0.0, 0.0, 0.0}; // LB, Estimate, UB private static final double[] ONES = {1.0, 1.0, 1.0}; /** * Computes the Jaccard similarity ratio with upper and lower bounds. The Jaccard similarity ratio * <i>J(A,B) = (A ^ B)/(A U B)</i> is used to measure how similar the two sketches are to each * other. If J = 1.0, the sketches are considered equal. If J = 0, the two sketches are * distinct from each other. A Jaccard of .95 means the overlap between the two * populations is 95% of the union of the two populations. * * @param sketchA given sketch A * @param sketchB given sketch B * @return a double array {LowerBound, Estimate, UpperBound} of the Jaccard ratio. * The Upper and Lower bounds are for a confidence interval of 95.4% or +/- 2 standard deviations. */ public static double[] jaccard(final Sketch sketchA, final Sketch sketchB) { //Corner case checks if ((sketchA == null) || (sketchB == null)) { return ZEROS.clone(); } if (sketchA == sketchB) { return ONES.clone(); } if (sketchA.isEmpty() && sketchB.isEmpty()) { return ONES.clone(); } if (sketchA.isEmpty() || sketchB.isEmpty()) { return ZEROS.clone(); } final int countA = sketchA.getRetainedEntries(); final int countB = sketchB.getRetainedEntries(); //Create the Union final Union union = SetOperation.builder().buildUnion(ceilingPowerOf2(countA + countB)); union.update(sketchA); union.update(sketchB); final Sketch unionAB = union.getResult(); final long thetaLongUAB = unionAB.getThetaLong(); final long thetaLongA = sketchA.getThetaLong(); final long thetaLongB = sketchB.getThetaLong(); final int countUAB = unionAB.getRetainedEntries(); //Check for identical data if ((countUAB == countA) && (countUAB == countB) && (thetaLongUAB == thetaLongA) && (thetaLongUAB == thetaLongB)) { return ONES.clone(); } //Create the Intersection final Intersection inter = SetOperation.builder().buildIntersection(); inter.update(sketchA); inter.update(sketchB); inter.update(unionAB); //ensures that intersection is a subset of the union final Sketch interABU = inter.getResult(true, null); final double lb = getLowerBoundForBoverA(unionAB, interABU); final double est = getEstimateOfBoverA(unionAB, interABU); final double ub = getUpperBoundForBoverA(unionAB, interABU); return new double[] {lb, est, ub}; } /** * Returns true if the two given sketches have exactly the same hash values and the same * theta values. Thus, they are equivalent. * @param sketchA the given sketch A * @param sketchB the given sketch B * @return true if the two given sketches have exactly the same hash values and the same * theta values. */ public static boolean exactlyEqual(final Sketch sketchA, final Sketch sketchB) { //Corner case checks if ((sketchA == null) || (sketchB == null)) { return false; } if (sketchA == sketchB) { return true; } if (sketchA.isEmpty() && sketchB.isEmpty()) { return true; } if (sketchA.isEmpty() || sketchB.isEmpty()) { return false; } final int countA = sketchA.getRetainedEntries(); final int countB = sketchB.getRetainedEntries(); //Create the Union final Union union = SetOperation.builder().buildUnion(ceilingPowerOf2(countA + countB)); union.update(sketchA); union.update(sketchB); final Sketch unionAB = union.getResult(); final long thetaLongUAB = unionAB.getThetaLong(); final long thetaLongA = sketchA.getThetaLong(); final long thetaLongB = sketchB.getThetaLong(); final int countUAB = unionAB.getRetainedEntries(); //Check for identical counts and thetas if ((countUAB == countA) && (countUAB == countB) && (thetaLongUAB == thetaLongA) && (thetaLongUAB == thetaLongB)) { return true; } return false; } /** * Tests similarity of a measured Sketch against an expected Sketch. * Computes the lower bound of the Jaccard ratio <i>J<sub>LB</sub></i> of the measured and * expected sketches. * if <i>J<sub>LB</sub> &ge; threshold</i>, then the sketches are considered to be * similar with a confidence of 97.7%. * * @param measured the sketch to be tested * @param expected the reference sketch that is considered to be correct. * @param threshold a real value between zero and one. * @return if true, the similarity of the two sketches is greater than the given threshold * with at least 97.7% confidence. */ public static boolean similarityTest(final Sketch measured, final Sketch expected, final double threshold) { //index 0: the lower bound //index 1: the mean estimate //index 2: the upper bound final double jRatioLB = jaccard(measured, expected)[0]; //choosing the lower bound return jRatioLB >= threshold; } /** * Tests dissimilarity of a measured Sketch against an expected Sketch. * Computes the upper bound of the Jaccard ratio <i>J<sub>LB</sub></i> of the measured and * expected sketches. * if <i>J<sub>UB</sub> &le; threshold</i>, then the sketches are considered to be * dissimilar with a confidence of 97.7%. * * @param measured the sketch to be tested * @param expected the reference sketch that is considered to be correct. * @param threshold a real value between zero and one. * @return if true, the dissimilarity of the two sketches is greater than the given threshold * with at least 97.7% confidence. */ public static boolean dissimilarityTest(final Sketch measured, final Sketch expected, final double threshold) { //index 0: the lower bound //index 1: the mean estimate //index 2: the upper bound final double jRatioUB = jaccard(measured, expected)[2]; //choosing the upper bound return jRatioUB <= threshold; } }
apache-2.0
consulo/consulo
modules/base/lang-impl/src/main/java/com/intellij/util/indexing/hash/FileContentHashIndex.java
2441
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing.hash; import com.intellij.openapi.util.Computable; import com.intellij.util.indexing.*; import com.intellij.util.indexing.impl.AbstractUpdateData; import com.intellij.util.indexing.impl.IndexStorage; import com.intellij.util.indexing.impl.forward.MapForwardIndexAccessor; import com.intellij.util.indexing.impl.forward.PersistentMapBasedForwardIndex; import javax.annotation.Nonnull; import java.io.IOException; import java.util.Map; import java.util.function.IntUnaryOperator; public class FileContentHashIndex extends VfsAwareMapReduceIndex<Integer, Void, FileContent> { FileContentHashIndex(@Nonnull FileContentHashIndexExtension extension, IndexStorage<Integer, Void> storage) throws IOException { super(extension, storage, new PersistentMapBasedForwardIndex(IndexInfrastructure.getInputIndexStorageFile(extension.getName())), new MapForwardIndexAccessor<>(new InputMapExternalizer<>(extension)), null, null); } @Nonnull @Override protected Computable<Boolean> createIndexUpdateComputation(@Nonnull AbstractUpdateData<Integer, Void> updateData) { return new HashIndexUpdateComputable(super.createIndexUpdateComputation(updateData), updateData.newDataIsEmpty()); } public int getHashId(int fileId) throws StorageException { Map<Integer, Void> data = getIndexedFileData(fileId); if (data.isEmpty()) return 0; return data.keySet().iterator().next(); } @Nonnull IntUnaryOperator toHashIdToFileIdFunction() { return hash -> { try { ValueContainer<Void> data = getData(hash); assert data.size() == 1; return data.getValueIterator().getInputIdsIterator().next(); } catch (StorageException e) { throw new RuntimeException(e); } }; } final static class HashIndexUpdateComputable implements Computable<Boolean> { @Nonnull private final Computable<Boolean> myUnderlying; private final boolean myEmptyInput; HashIndexUpdateComputable(@Nonnull Computable<Boolean> underlying, boolean isEmptyInput) { myUnderlying = underlying; myEmptyInput = isEmptyInput; } boolean isEmptyInput() { return myEmptyInput; } @Override public Boolean compute() { return myUnderlying.compute(); } } }
apache-2.0
VibyJocke/gocd
server/src/com/thoughtworks/go/server/ui/AgentViewModel.java
8628
/* * Copyright 2016 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.ui; import java.util.*; import com.thoughtworks.go.config.Resource; import com.thoughtworks.go.config.Resources; import com.thoughtworks.go.domain.*; import com.thoughtworks.go.util.comparator.AlphaAsciiComparator; import info.aduna.text.NumericStringComparator; import org.apache.commons.lang.StringUtils; /** * @understands agent information for the UI */ public class AgentViewModel implements Comparable<AgentViewModel>{ static final String MISSING_AGENT_BOOTSTRAPPER_VERSION = "Unknown"; static final String OLDER_AGENT_BOOTSTRAPPER_VERSION = "Older"; private AgentInstance agentInstance; private Set<String> environments; public AgentViewModel(AgentInstance agentInstance) { this(agentInstance, new HashSet<String>()); } public AgentViewModel(AgentInstance agentInstance, Collection<String> environments) { this.agentInstance = agentInstance; this.environments = new TreeSet<>(environments); } public AgentViewModel(AgentInstance agentInstance, String... environments) { this(agentInstance, Arrays.asList(environments)); } public String getHostname() { return agentInstance.getHostname(); } public String getIpAddress() { return agentInstance.getIpAddress(); } public String getLocation() { return agentInstance.getLocation(); } public DiskSpace freeDiskSpace() { return agentInstance.freeDiskSpace(); } public String getBootstrapperVersion() { if(agentInstance.isMissing()){ return MISSING_AGENT_BOOTSTRAPPER_VERSION; } if(agentInstance.getAgentLauncherVersion() == null && !agentInstance.isMissing()){ return OLDER_AGENT_BOOTSTRAPPER_VERSION; } return agentInstance.getAgentLauncherVersion(); } public List<String> getResources() { return resources().resourceNames(); } public Resources resources() { return agentInstance.getResources(); } public AgentStatus getStatus() { return agentInstance.getStatus(); } public AgentRuntimeStatus getRuntimeStatus(){ return agentInstance.getRuntimeStatus(); } public AgentConfigStatus getAgentConfigStatus(){ return agentInstance.getAgentConfigStatus(); } public String getStatusForDisplay() { return isCancelled() ? "Building (Cancelled)" : getStatus().toString(); } public String buildLocator(){ return agentInstance.getBuildLocator(); } public Date getLastHeardTime(){ return agentInstance.getLastHeardTime(); } public String getUuid(){ return agentInstance.getUuid(); } public boolean isBuilding(){ return agentInstance.isBuilding(); } public boolean isCancelled(){ return agentInstance.isCancelled(); } public boolean isEnabled(){ return !agentInstance.isDisabled(); } public static Comparator<AgentViewModel> STATUS_COMPARATOR = new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return agentInstance1.getStatus().compareTo(agentInstance2.getStatus()); } }; public static Comparator<AgentViewModel> HOSTNAME_COMPARATOR = new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return new AlphaAsciiComparator().compare(agentInstance1.getHostname(), agentInstance2.getHostname()); } }; public static Comparator<AgentViewModel> IP_ADDRESS_COMPARATOR = new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return IpAddress.create(agentInstance1.getIpAddress()).compareTo(IpAddress.create(agentInstance2.getIpAddress())); } }; public static Comparator<AgentViewModel> LOCATION_COMPARATOR = new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return agentInstance1.getLocation().compareTo(agentInstance2.getLocation()); } }; public static Comparator<AgentViewModel> USABLE_SPACE_COMPARATOR = new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return agentInstance1.freeDiskSpace().compareTo(agentInstance2.freeDiskSpace()); } }; public static Comparator<AgentViewModel> RESOURCES_COMPARATOR = new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return agentInstance1.resources().compareTo(agentInstance2.resources()); } }; public static Comparator<AgentViewModel> ENVIRONMENTS_COMPARATOR = new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return new AlphaAsciiComparator().compare(StringUtils.join(agentInstance1.getEnvironments().toArray()), StringUtils.join(agentInstance2.getEnvironments().toArray())); } }; public static Comparator<AgentViewModel> OS_COMPARATOR=new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return new AlphaAsciiComparator().compare(agentInstance1.getOperatingSystem(), agentInstance2.getOperatingSystem()); } }; public static Comparator<AgentViewModel> BOOTSTRAPPER_VERSION_COMPARATOR=new Comparator<AgentViewModel>() { public int compare(AgentViewModel agentInstance1, AgentViewModel agentInstance2) { return new NumericStringComparator().compare(agentInstance1.getBootstrapperVersion(), agentInstance2.getBootstrapperVersion()); } }; public int compareTo(AgentViewModel other) { return this.agentInstance.compareTo(other.agentInstance); } public Set<String> getEnvironments() { return environments; } @Override public String toString() { return "hostname= " + agentInstance.getHostname() + " location = " + agentInstance.getLocation() + " environments = " + environments + " resources= " + getResources().toString() + " os= " + getOperatingSystem() + " status = " + getStatus() + " ip = " + getIpAddress() + " bootstrapperVersion = " + getBootstrapperVersion(); } public String getOperatingSystem() { return agentInstance.getOperatingSystem(); } public boolean isNullAgent() { return agentInstance.isNullAgent(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AgentViewModel that = (AgentViewModel) o; if (agentInstance != null ? !agentInstance.equals(that.agentInstance) : that.agentInstance != null) { return false; } if (environments != null ? !environments.equals(that.environments) : that.environments != null) { return false; } return true; } @Override public int hashCode() { int result = agentInstance != null ? agentInstance.hashCode() : 0; result = 31 * result + (environments != null ? environments.hashCode() : 0); return result; } public boolean needsUpgrade() { return agentInstance.needsUpgrade(); } public ConfigErrors errors() { ConfigErrors configErrors = new ConfigErrors(); configErrors.addAll(agentInstance.agentConfig().errors()); for (Resource resource : agentInstance.getResources()) { configErrors.addAll(resource.errors()); } return configErrors; } }
apache-2.0
googlearchive/science-journal
OpenScienceJournal/whistlepunk_library/src/mockclasses/java/com/google/android/apps/forscience/whistlepunk/api/scalarinput/ScalarInputScenario.java
3943
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.forscience.whistlepunk.api.scalarinput; import androidx.annotation.NonNull; import com.google.android.apps.forscience.whistlepunk.Arbitrary; import com.google.android.apps.forscience.whistlepunk.SensorProvider; import com.google.android.apps.forscience.whistlepunk.devicemanager.ConnectableSensor; import com.google.android.apps.forscience.whistlepunk.devicemanager.SensorDiscoverer; import java.util.Map; import java.util.concurrent.Executor; /** * Creates a scenario in which scanning is guaranteed to find a single device and a single sensor. */ public class ScalarInputScenario { public final SensorAppearanceResources appearance = new SensorAppearanceResources(); private String serviceName; private String deviceId; private String deviceName; private String sensorAddress; private String sensorName; private String serviceId; public ScalarInputScenario() { serviceName = Arbitrary.string("serviceName"); deviceId = Arbitrary.string("deviceId"); deviceName = Arbitrary.string("deviceName"); sensorAddress = Arbitrary.string("sensorAddress"); sensorName = Arbitrary.string("sensorName"); serviceId = Arbitrary.string("serviceId"); } public String getServiceName() { return serviceName; } public String getDeviceId() { return deviceId; } public String getDeviceName() { return deviceName; } public String getSensorAddress() { return sensorAddress; } public String getSensorName() { return sensorName; } public String getServiceId() { return serviceId; } @NonNull public ScalarInputDiscoverer buildDiscoverer(Executor uiThread) { final TestSensorDiscoverer discoverer = makeTestSensorDiscoverer(); return discoverer.makeScalarInputDiscoverer(getServiceId(), uiThread); } @NonNull private TestSensorDiscoverer makeTestSensorDiscoverer() { final TestSensorDiscoverer discoverer = new TestSensorDiscoverer(getServiceName()); discoverer.addDevice(getDeviceId(), getDeviceName()); discoverer.addSensor( getDeviceId(), new TestSensor(getSensorAddress(), getSensorName(), appearance)); return discoverer; } @NonNull public Map<String, SensorDiscoverer> makeScalarInputDiscoverers() { return makeTestSensorDiscoverer().makeDiscovererMap(getServiceId()); } @NonNull public ScalarInputSpec makeSpec() { return new ScalarInputSpec( getSensorName(), getServiceId(), getSensorAddress(), new SensorBehavior(), appearance, deviceId); } public Map<String, SensorProvider> makeScalarInputProviders() { return makeTestSensorDiscoverer().makeProviderMap(getServiceId()); } @NonNull TestSensorDiscoverer neverDoneDiscoverer() { return new TestSensorDiscoverer(getServiceName()) { @Override protected void onDevicesDone(IDeviceConsumer c) { // override with empty implementation: we never call c.onScanDone, to test timeout } @Override protected void onSensorsDone(ISensorConsumer c) { // override with empty implementation: we never call c.onScanDone, to test timeout } }; } public ConnectableSensor.Connector makeConnector() { return new ConnectableSensor.Connector(makeScalarInputProviders()); } }
apache-2.0
phac-nml/irida
src/main/java/ca/corefacility/bioinformatics/irida/ria/web/projects/dto/SavedMetadataErrorResponse.java
555
package ca.corefacility.bioinformatics.irida.ria.web.projects.dto; import ca.corefacility.bioinformatics.irida.ria.utilities.SampleMetadataStorage; import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxResponse; /** * Returns the SampleMetadataStorage on error. */ public class SavedMetadataErrorResponse extends AjaxResponse { private SampleMetadataStorage storage; public SavedMetadataErrorResponse(SampleMetadataStorage storage) { this.storage = storage; } public SampleMetadataStorage getStorage() { return storage; } }
apache-2.0
43081438/IMDemo
Wow-master/app/src/main/java/com/dikaros/wow/MainActivity.java
350
package com.dikaros.wow; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //md5算法 } }
apache-2.0
joy-inc/joy-library
library-android/src/com/android/library/view/observablescrollview/ObservableScrollView.java
11401
/* * Copyright 2014 Soichiro Kashima * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.library.view.observablescrollview; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; import java.util.ArrayList; import java.util.List; /** * ScrollView that its scroll position can be observed. */ public class ObservableScrollView extends ScrollView implements Scrollable { // Fields that should be saved onSaveInstanceState private int mPrevScrollY; private int mScrollY; // Fields that don't need to be saved onSaveInstanceState private ObservableScrollViewCallbacks mCallbacks; private List<ObservableScrollViewCallbacks> mCallbackCollection; private ScrollState mScrollState; private boolean mFirstScroll; private boolean mDragging; private boolean mIntercepted; private MotionEvent mPrevMoveEvent; private ViewGroup mTouchInterceptionViewGroup; public ObservableScrollView(Context context) { super(context); } public ObservableScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public ObservableScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; mPrevScrollY = ss.prevScrollY; mScrollY = ss.scrollY; super.onRestoreInstanceState(ss.getSuperState()); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.prevScrollY = mPrevScrollY; ss.scrollY = mScrollY; return ss; } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mCallbacks != null || mCallbackCollection != null) { mScrollY = t; dispatchOnScrollChanged(t, mFirstScroll, mDragging); if (mFirstScroll) { mFirstScroll = false; } if (mPrevScrollY < t) { mScrollState = ScrollState.UP; } else if (t < mPrevScrollY) { mScrollState = ScrollState.DOWN; //} else { // Keep previous state while dragging. // Never makes it STOP even if scrollY not changed. // Before Android 4.4, onTouchEvent calls onScrollChanged directly for ACTION_MOVE, // which makes mScrollState always STOP when onUpOrCancelMotionEvent is called. // STOP state is now meaningless for ScrollView. } mPrevScrollY = t; } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (mCallbacks != null || mCallbackCollection != null) { switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: // Whether or not motion events are consumed by children, // flag initializations which are related to ACTION_DOWN events should be executed. // Because if the ACTION_DOWN is consumed by children and only ACTION_MOVEs are // passed to parent (this view), the flags will be invalid. // Also, applications might implement initialization codes to onDownMotionEvent, // so call it here. mFirstScroll = mDragging = true; dispatchOnDownMotionEvent(); break; } } return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent ev) { if (mCallbacks != null || mCallbackCollection != null) { switch (ev.getActionMasked()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mIntercepted = false; mDragging = false; dispatchOnUpOrCancelMotionEvent(mScrollState); break; case MotionEvent.ACTION_MOVE: if (mPrevMoveEvent == null) { mPrevMoveEvent = ev; } float diffY = ev.getY() - mPrevMoveEvent.getY(); mPrevMoveEvent = MotionEvent.obtainNoHistory(ev); if (getCurrentScrollY() - diffY <= 0) { // Can't scroll anymore. if (mIntercepted) { // Already dispatched ACTION_DOWN event to parents, so stop here. return false; } // Apps can set the interception target other than the direct parent. final ViewGroup parent; if (mTouchInterceptionViewGroup == null) { parent = (ViewGroup) getParent(); } else { parent = mTouchInterceptionViewGroup; } // Get offset to parents. If the parent is not the direct parent, // we should aggregate offsets from all of the parents. float offsetX = 0; float offsetY = 0; for (View v = this; v != null && v != parent; v = (View) v.getParent()) { offsetX += v.getLeft() - v.getScrollX(); offsetY += v.getTop() - v.getScrollY(); } final MotionEvent event = MotionEvent.obtainNoHistory(ev); event.offsetLocation(offsetX, offsetY); if (parent.onInterceptTouchEvent(event)) { mIntercepted = true; // If the parent wants to intercept ACTION_MOVE events, // we pass ACTION_DOWN event to the parent // as if these touch events just have began now. event.setAction(MotionEvent.ACTION_DOWN); // Return this onTouchEvent() first and set ACTION_DOWN event for parent // to the queue, to keep events sequence. post(new Runnable() { @Override public void run() { parent.dispatchTouchEvent(event); } }); return false; } // Even when this can't be scrolled anymore, // simply returning false here may cause subView's click, // so delegate it to super. return super.onTouchEvent(ev); } break; } } return super.onTouchEvent(ev); } @Override public void setScrollViewCallbacks(ObservableScrollViewCallbacks listener) { mCallbacks = listener; } @Override public void addScrollViewCallbacks(ObservableScrollViewCallbacks listener) { if (mCallbackCollection == null) { mCallbackCollection = new ArrayList<>(); } mCallbackCollection.add(listener); } @Override public void removeScrollViewCallbacks(ObservableScrollViewCallbacks listener) { if (mCallbackCollection != null) { mCallbackCollection.remove(listener); } } @Override public void clearScrollViewCallbacks() { if (mCallbackCollection != null) { mCallbackCollection.clear(); } } @Override public void setTouchInterceptionViewGroup(ViewGroup viewGroup) { mTouchInterceptionViewGroup = viewGroup; } @Override public void scrollVerticallyTo(int y) { scrollTo(0, y); } @Override public int getCurrentScrollY() { return mScrollY; } private void dispatchOnDownMotionEvent() { if (mCallbacks != null) { mCallbacks.onDownMotionEvent(); } if (mCallbackCollection != null) { for (int i = 0; i < mCallbackCollection.size(); i++) { ObservableScrollViewCallbacks callbacks = mCallbackCollection.get(i); callbacks.onDownMotionEvent(); } } } private void dispatchOnScrollChanged(int scrollY, boolean firstScroll, boolean dragging) { if (mCallbacks != null) { mCallbacks.onScrollChanged(scrollY, firstScroll, dragging); } if (mCallbackCollection != null) { for (int i = 0; i < mCallbackCollection.size(); i++) { ObservableScrollViewCallbacks callbacks = mCallbackCollection.get(i); callbacks.onScrollChanged(scrollY, firstScroll, dragging); } } } private void dispatchOnUpOrCancelMotionEvent(ScrollState scrollState) { if (mCallbacks != null) { mCallbacks.onUpOrCancelMotionEvent(scrollState); } if (mCallbackCollection != null) { for (int i = 0; i < mCallbackCollection.size(); i++) { ObservableScrollViewCallbacks callbacks = mCallbackCollection.get(i); callbacks.onUpOrCancelMotionEvent(scrollState); } } } static class SavedState extends BaseSavedState { int prevScrollY; int scrollY; /** * Called by onSaveInstanceState. */ SavedState(Parcelable superState) { super(superState); } /** * Called by CREATOR. */ private SavedState(Parcel in) { super(in); prevScrollY = in.readInt(); scrollY = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(prevScrollY); out.writeInt(scrollY); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
apache-2.0
nakag/dddsupport
jp.osdn.dddsupport.basegenerator/src/jp/osdn/dddsupport/basegenerator/model/ImportClasses.java
469
package jp.osdn.dddsupport.basegenerator.model; import java.util.ArrayList; import java.util.List; public class ImportClasses { private List<ImportClass> importClasses; public ImportClasses() { importClasses = new ArrayList<ImportClass>(); } public void add(ImportClass importClass) { if (importClasses.contains(importClass)) { return; } importClasses.add(importClass); } public List<ImportClass> getImportClasses() { return importClasses; } }
apache-2.0
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201403/RateCardFeature.java
2135
package com.google.api.ads.dfp.jaxws.v201403; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * * The feature of a {@link RateCardCustomization} * * * <p>Java class for RateCardFeature complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RateCardFeature"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="RateCardFeature.Type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RateCardFeature", propOrder = { "rateCardFeatureType" }) @XmlSeeAlso({ AdUnitRateCardFeature.class, BrowserRateCardFeature.class, PlacementRateCardFeature.class, UnknownRateCardFeature.class, OperatingSystemRateCardFeature.class, FrequencyCapRateCardFeature.class, GeographyRateCardFeature.class, UserDomainRateCardFeature.class, CustomTargetingRateCardFeature.class, BrowserLanguageRateCardFeature.class, BandwidthRateCardFeature.class }) public abstract class RateCardFeature { @XmlElement(name = "RateCardFeature.Type") protected String rateCardFeatureType; /** * Gets the value of the rateCardFeatureType property. * * @return * possible object is * {@link String } * */ public String getRateCardFeatureType() { return rateCardFeatureType; } /** * Sets the value of the rateCardFeatureType property. * * @param value * allowed object is * {@link String } * */ public void setRateCardFeatureType(String value) { this.rateCardFeatureType = value; } }
apache-2.0
hejingit/Skybird-WorkSpace
coffeeframe/src/main/java/com/coffee/common/persistence/proxy/PaginationMapperRegistry.java
1096
/** * Copyright &copy; 2016-2018 <a href="www.coffee-ease.com/">coffee-ease</a> All rights reserved. */ package com.coffee.common.persistence.proxy; import org.apache.ibatis.binding.BindingException; import org.apache.ibatis.binding.MapperRegistry; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; /** * <p> * . * </p> * * @author poplar.yfyang * @version 1.0 2012-05-13 上午10:06 * @since JDK 1.5 */ public class PaginationMapperRegistry extends MapperRegistry { public PaginationMapperRegistry(Configuration config) { super(config); } @Override public <T> T getMapper(Class<T> type, SqlSession sqlSession) { if (!hasMapper(type)) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return PaginationMapperProxy.newMapperProxy(type, sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } } }
apache-2.0
jitsni/gateway.distribution
gateway.management/src/main/java/org/kaazing/gateway/management/context/DefaultManagementContext.java
37967
/** * Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.kaazing.gateway.management.context; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Resource; import org.kaazing.gateway.management.ManagementService; import org.kaazing.gateway.management.ManagementServiceHandler; import org.kaazing.gateway.management.ManagementStrategy; import org.kaazing.gateway.management.ManagementStrategyChangeListener; import org.kaazing.gateway.management.SummaryManagementInterval; import org.kaazing.gateway.management.config.ClusterConfigurationBean; import org.kaazing.gateway.management.config.ClusterConfigurationBeanImpl; import org.kaazing.gateway.management.config.RealmConfigurationBean; import org.kaazing.gateway.management.config.RealmConfigurationBeanImpl; import org.kaazing.gateway.management.config.SecurityConfigurationBean; import org.kaazing.gateway.management.config.SecurityConfigurationBeanImpl; import org.kaazing.gateway.management.config.ServiceConfigurationBean; import org.kaazing.gateway.management.config.ServiceConfigurationBeanImpl; import org.kaazing.gateway.management.config.ServiceDefaultsConfigurationBean; import org.kaazing.gateway.management.config.ServiceDefaultsConfigurationBeanImpl; import org.kaazing.gateway.management.filter.FullManagementFilterStrategy; import org.kaazing.gateway.management.filter.ManagementFilter; import org.kaazing.gateway.management.filter.ManagementFilterStrategy; import org.kaazing.gateway.management.filter.PassThruManagementFilterStrategy; import org.kaazing.gateway.management.filter.ServiceOnlyManagementFilterStrategy; import org.kaazing.gateway.management.gateway.CollectOnlyManagementGatewayStrategy; import org.kaazing.gateway.management.gateway.FullManagementGatewayStrategy; import org.kaazing.gateway.management.gateway.GatewayManagementBean; import org.kaazing.gateway.management.gateway.GatewayManagementBeanImpl; import org.kaazing.gateway.management.gateway.GatewayManagementListener; import org.kaazing.gateway.management.gateway.ManagementGatewayStrategy; import org.kaazing.gateway.management.service.CollectOnlyManagementServiceStrategy; import org.kaazing.gateway.management.service.FullManagementServiceStrategy; import org.kaazing.gateway.management.service.ManagementServiceStrategy; import org.kaazing.gateway.management.service.ServiceManagementBean; import org.kaazing.gateway.management.service.ServiceManagementBeanFactory; import org.kaazing.gateway.management.service.ServiceManagementListener; import org.kaazing.gateway.management.session.CollectOnlyManagementSessionStrategy; import org.kaazing.gateway.management.session.FullManagementSessionStrategy; import org.kaazing.gateway.management.session.ManagementSessionStrategy; import org.kaazing.gateway.management.session.SessionManagementBean; import org.kaazing.gateway.management.session.SessionManagementBeanImpl; import org.kaazing.gateway.management.session.SessionManagementListener; import org.kaazing.gateway.management.system.CpuListManagementBean; import org.kaazing.gateway.management.system.CpuListManagementBeanImpl; import org.kaazing.gateway.management.system.CpuManagementBean; import org.kaazing.gateway.management.system.FullManagementSystemStrategy; import org.kaazing.gateway.management.system.HostManagementBean; import org.kaazing.gateway.management.system.HostManagementBeanImpl; import org.kaazing.gateway.management.system.JvmManagementBean; import org.kaazing.gateway.management.system.JvmManagementBeanImpl; import org.kaazing.gateway.management.system.ManagementSystemStrategy; import org.kaazing.gateway.management.system.NicListManagementBean; import org.kaazing.gateway.management.system.NicListManagementBeanImpl; import org.kaazing.gateway.management.system.NicManagementBean; import org.kaazing.gateway.management.system.NullManagementSystemStrategy; import org.kaazing.gateway.management.system.SystemDataProvider; import org.kaazing.gateway.management.system.SystemDataProviderFactory; import org.kaazing.gateway.security.RealmContext; import org.kaazing.gateway.security.SecurityContext; import org.kaazing.gateway.server.context.DependencyContext; import org.kaazing.gateway.server.context.GatewayContext; import org.kaazing.gateway.server.context.ServiceDefaultsContext; import org.kaazing.gateway.service.ServiceContext; import org.kaazing.gateway.service.cluster.ClusterContext; import org.kaazing.gateway.util.scheduler.SchedulerProvider; import org.kaazing.mina.core.session.IoSessionEx; import static org.kaazing.gateway.management.service.ServiceManagementBeanFactory.newServiceManagementBeanFactory; public class DefaultManagementContext implements ManagementContext, DependencyContext { public static final int DEFAULT_SUMMARY_DATA_NOTIFICATION_INTERVAL = 5000; // 5 seconds by default public static final int DEFAULT_SYSTEM_SUMMARY_DATA_NOTIFICATION_INTERVAL = 2000; // 5 seconds by default public static final int DEFAULT_SUMMARY_DATA_GATHER_INTERVAL = 500; // 500 ms public static final String NAME = "managementContext"; public static final String SESSION_MANAGEMENT_THRESHOLD_PROP = "session.management.threshold"; public static final String MAX_MANAGEMENT_SESSIONS_PROP = "max.management.sessions"; public static final ManagementFilterStrategy PASS_THRU_FILTER_STRATEGY = new PassThruManagementFilterStrategy(); public static final ManagementFilterStrategy SERVICE_ONLY_FILTER_STRATEGY = new ServiceOnlyManagementFilterStrategy(); public static final ManagementFilterStrategy FULL_FILTER_STRATEGY = new FullManagementFilterStrategy(); public static final ManagementGatewayStrategy COLLECT_ONLY_GATEWAY_STRATEGY = new CollectOnlyManagementGatewayStrategy(); public static final ManagementGatewayStrategy FULL_GATEWAY_STRATEGY = new FullManagementGatewayStrategy(); public static final ManagementServiceStrategy COLLECT_ONLY_SERVICE_STRATEGY = new CollectOnlyManagementServiceStrategy(); public static final ManagementServiceStrategy FULL_SERVICE_STRATEGY = new FullManagementServiceStrategy(); public static final ManagementSessionStrategy COLLECT_ONLY_SESSION_STRATEGY = new CollectOnlyManagementSessionStrategy(); public static final ManagementSessionStrategy FULL_SESSION_STRATEGY = new FullManagementSessionStrategy(); public static final ManagementSystemStrategy COLLECT_ONLY_SYSTEM_STRATEGY = new NullManagementSystemStrategy(); public static final ManagementSystemStrategy FULL_SYSTEM_STRATEGY = new FullManagementSystemStrategy(); // in the following lists, entries are: filter-level, gateway-level, service-level, session-level. private static final ManagementStrategy[] COLLECT_ONLY_STRATEGY = {FULL_FILTER_STRATEGY, // to allow creating session beans COLLECT_ONLY_GATEWAY_STRATEGY, COLLECT_ONLY_SERVICE_STRATEGY, COLLECT_ONLY_SESSION_STRATEGY, COLLECT_ONLY_SYSTEM_STRATEGY}; private static final ManagementStrategy[] FULL_STRATEGY = {FULL_FILTER_STRATEGY, FULL_GATEWAY_STRATEGY, FULL_SERVICE_STRATEGY, FULL_SESSION_STRATEGY, FULL_SYSTEM_STRATEGY}; private final int FILTER_INDEX = 0; private final int GATEWAY_INDEX = 1; private final int SERVICE_INDEX = 2; private final int SESSION_INDEX = 3; private final int SYSTEM_INDEX = 4; private static Map<ServiceContext, Integer> serviceIndexMap = new HashMap<>(); private static Integer serviceIndexCount = 1; private final String localGatewayHostAndPid; // for the Gateway instance this is part of private final AtomicBoolean managementConfigured; private final SummaryManagementInterval gatewaySummaryDataNotificationInterval; private final SummaryManagementInterval serviceSummaryDataNotificationInterval; private final SummaryManagementInterval sessionSummaryDataNotificationInterval; private final SummaryManagementInterval systemSummaryDataGatherInterval; private final SummaryManagementInterval systemSummaryDataNotificationInterval; private final SummaryManagementInterval cpuListSummaryDataGatherInterval; private final SummaryManagementInterval cpuListSummaryDataNotificationInterval; private final SummaryManagementInterval nicListSummaryDataGatherInterval; private final SummaryManagementInterval nicListSummaryDataNotificationInterval; private final SummaryManagementInterval jvmSummaryDataGatherInterval; private final SummaryManagementInterval jvmSummaryDataNotificationInterval; // The set of management strategies currently in force. private ManagementStrategy[] managementStrategy = COLLECT_ONLY_STRATEGY; // The total number of current sessions on either management service. We use this // along with sessionManagementThreshold to modify the level of management. // Currently needs to be atomic because the update may be coming from any session IO thread. private AtomicInteger managementSessionCount = new AtomicInteger(0); // The total number of current sessions, NOT including management. This is the // value that we check against sessionManagementThreshold; // Currently needs to be atomic because the update may be coming from any session IO thread. private AtomicInteger overallSessionCount = new AtomicInteger(0); // The threshold for 'max number of sessions across all services that we // will tolerate. ABOVE this number management will be cut back. EQUAL to this number // we will still do 'full' management stats gathering and notification. // This is set once at DMC initialization, though we'll make it possible to change it // later, in case reading it through a system property isn't sufficient. // NOTE: this includes management sessions as well! // // This is set by the management services from properties private int managementSessionThreshold; // The list of handlers that have been configured for management for this gateway. // These are added during management-service init(). private final List<ManagementServiceHandler> managementServiceHandlers; private final ConcurrentHashMap<ServiceContext, ManagementFilter> managementFilters = new ConcurrentHashMap<ServiceContext, ManagementFilter>(); // The list of GatewayManagementListeners, one per management service type, for gateway // events. The particular listeners for each management service type are currently fixed, // so the list doesn't change for that, but we do want it to change for full/collect-only management. private final List<GatewayManagementListener> gatewayManagementListeners = new CopyOnWriteArrayList<GatewayManagementListener>(); // Similar set of listeners, but for service events. private final List<ServiceManagementListener> serviceManagementListeners = new CopyOnWriteArrayList<ServiceManagementListener>(); // Similar set of listeners, but for session events. private final List<SessionManagementListener> sessionManagementListeners = new CopyOnWriteArrayList<SessionManagementListener>(); // List of objects to be notified when the managemment strategy changes. Generally this // is only used by AbstractSummaryDataProviders, as they need to be notified specifically // to start or stop gathering. But it can be used elsewhere, too private List<ManagementStrategyChangeListener> managementStrategyChangeListeners = new ArrayList<ManagementStrategyChangeListener>(); // injected at startup private SchedulerProvider schedulerProvider; private GatewayContext gatewayContext; // The provider for system data. Depending on whether we have Sigar support or not, // this may or may not return useful data. private SystemDataProvider systemDataProvider; private ScheduledExecutorService managementExecutorService; // when a management service is initialized it will flag the management context as active private boolean active; // The gateway management beans, keyed by a hostname:processId pair. // NOTE: we do not want to expose this to the ManagementProcessors--they should // be processing based on the gateway management bean, not the address. private final ConcurrentHashMap<String, GatewayManagementBean> gatewayManagementBeans = new ConcurrentHashMap<String, GatewayManagementBean>(); // The service management beans, keyed by the address of the service's transport // that they contain. // NOTE: we do not want to expose this to the ManagementProcessors--they should // be processing based on the service management bean, not the address. private final ConcurrentHashMap<ServiceContext, ServiceManagementBean> serviceManagementBeans = new ConcurrentHashMap<ServiceContext, ServiceManagementBean>(); private final ConcurrentHashMap<ServiceContext, ServiceConfigurationBean> serviceConfigBeans = new ConcurrentHashMap<ServiceContext, ServiceConfigurationBean>(); private final ServiceManagementBeanFactory serviceManagmentBeanFactory = newServiceManagementBeanFactory(); public DefaultManagementContext() { this.managementServiceHandlers = new ArrayList<ManagementServiceHandler>(); // The map of GatewayManagementBeans is keyed on the hostname and process ID of the // gateway process. Compute that here so we can create a GatewayManagementBean for // the local gateway. Session and service-level beans will then use the gateway's // index in their data. Turns out (at least for linux and the Sun JDK) that the // The following is claimed to work on most JDKs, but is not guaranteed. localGatewayHostAndPid = ManagementFactory.getRuntimeMXBean().getName(); managementConfigured = new AtomicBoolean(false); gatewaySummaryDataNotificationInterval = new SummaryManagementIntervalImpl(DEFAULT_SUMMARY_DATA_NOTIFICATION_INTERVAL); serviceSummaryDataNotificationInterval = new SummaryManagementIntervalImpl(DEFAULT_SUMMARY_DATA_NOTIFICATION_INTERVAL); sessionSummaryDataNotificationInterval = new SummaryManagementIntervalImpl(DEFAULT_SUMMARY_DATA_NOTIFICATION_INTERVAL); systemSummaryDataGatherInterval = new SummaryManagementIntervalImpl(DEFAULT_SUMMARY_DATA_GATHER_INTERVAL); systemSummaryDataNotificationInterval = new SummaryManagementIntervalImpl(DEFAULT_SYSTEM_SUMMARY_DATA_NOTIFICATION_INTERVAL); nicListSummaryDataGatherInterval = new SummaryManagementIntervalImpl(DEFAULT_SUMMARY_DATA_GATHER_INTERVAL); nicListSummaryDataNotificationInterval = new SummaryManagementIntervalImpl(DEFAULT_SYSTEM_SUMMARY_DATA_NOTIFICATION_INTERVAL); cpuListSummaryDataGatherInterval = new SummaryManagementIntervalImpl(DEFAULT_SUMMARY_DATA_GATHER_INTERVAL); cpuListSummaryDataNotificationInterval = new SummaryManagementIntervalImpl(DEFAULT_SYSTEM_SUMMARY_DATA_NOTIFICATION_INTERVAL); jvmSummaryDataGatherInterval = new SummaryManagementIntervalImpl(DEFAULT_SUMMARY_DATA_GATHER_INTERVAL); jvmSummaryDataNotificationInterval = new SummaryManagementIntervalImpl(DEFAULT_SYSTEM_SUMMARY_DATA_NOTIFICATION_INTERVAL); systemDataProvider = SystemDataProviderFactory.createProvider(); } @Resource(name = "schedulerProvider") public void setSchedulerProvider(SchedulerProvider schedulerProvider) { this.schedulerProvider = schedulerProvider; this.managementExecutorService = schedulerProvider.getScheduler("management", true); } @Override public SchedulerProvider getSchedulerProvider() { return this.schedulerProvider; } @Resource(name = "gatewayContext") public void setGatewayContext(GatewayContext gatewayContext) { this.gatewayContext = gatewayContext; } @Override public ClusterContext getCluster() { if (gatewayContext != null) { return gatewayContext.getCluster(); } return null; } @Override public boolean isActive() { return active; } @Override public void setActive(boolean active) { this.active = active; } @Override public SystemDataProvider getSystemDataProvider() { return this.systemDataProvider; } @Override public int getManagementSessionCount() { return managementSessionCount.get(); } @Override public void incrementManagementSessionCount() { adjustStrategies(managementSessionCount.incrementAndGet(), overallSessionCount.incrementAndGet()); } @Override public void decrementManagementSessionCount() { adjustStrategies(managementSessionCount.decrementAndGet(), overallSessionCount.decrementAndGet()); } @Override public void setManagementSessionThreshold(int managementSessionThreshold) { this.managementSessionThreshold = managementSessionThreshold; } @Override public int getSessionManagementThreshold() { return managementSessionThreshold; } @Override public int getOverallSessionCount() { return overallSessionCount.get(); } @Override public void incrementOverallSessionCount() { adjustStrategies(managementSessionCount.get(), overallSessionCount.incrementAndGet()); } @Override public void decrementOverallSessionCount() { adjustStrategies(managementSessionCount.get(), overallSessionCount.decrementAndGet()); } @Override public List<GatewayManagementListener> getGatewayManagementListeners() { return gatewayManagementListeners; } @Override public void addGatewayManagementListener(GatewayManagementListener listener) { gatewayManagementListeners.add(listener); } @Override public void removeGatewayManagementListener(GatewayManagementListener listener) { gatewayManagementListeners.remove(listener); } @Override public List<ServiceManagementListener> getServiceManagementListeners() { return serviceManagementListeners; } @Override public void addServiceManagementListener(ServiceManagementListener listener) { serviceManagementListeners.add(listener); } @Override public void removeServiceManagementListener(ServiceManagementListener listener) { serviceManagementListeners.remove(listener); } @Override public List<SessionManagementListener> getSessionManagementListeners() { return sessionManagementListeners; } @Override public void addSessionManagementListener(SessionManagementListener listener) { sessionManagementListeners.add(listener); } @Override public void removeSessionManagementListener(SessionManagementListener listener) { sessionManagementListeners.remove(listener); } @Override public List<ManagementStrategyChangeListener> getManagementStrategyChangeListeners() { return managementStrategyChangeListeners; } @Override public void addManagementStrategyChangeListener(ManagementStrategyChangeListener listener) { managementStrategyChangeListeners.add(listener); } @Override public void removeManagementStrategyListener(ManagementStrategyChangeListener listener) { managementStrategyChangeListeners.remove(listener); } private void adjustStrategies(long managementSessionCount, long overallSessionCount) { ManagementStrategy[] newManagementStrategy; if (overallSessionCount > managementSessionThreshold || managementSessionCount == 0) { // too many sessions, or "no management logged in" newManagementStrategy = COLLECT_ONLY_STRATEGY; } else { newManagementStrategy = FULL_STRATEGY; } if (newManagementStrategy != managementStrategy) { managementStrategy = newManagementStrategy; for (ManagementStrategyChangeListener listener : managementStrategyChangeListeners) { listener.managementStrategyChanged(); } } } public List<ManagementServiceHandler> getManagementServiceHandlers() { return managementServiceHandlers; } public void addManagementServiceHandler(ManagementServiceHandler managementServiceHandler) { if (!managementServiceHandlers.contains(managementServiceHandler)) { managementServiceHandlers.add(managementServiceHandler); managementServiceHandler.addGatewayManagementBean(getLocalGatewayManagementBean()); } } public void removeManagementServiceHandler(ManagementServiceHandler managementServiceHandler) { managementServiceHandlers.remove(managementServiceHandler); } @Override public void runManagementTask(Runnable r) { managementExecutorService.execute(r); } public static synchronized int getNextServiceIndex(ServiceContext serviceContext) { Integer index = serviceIndexMap.get(serviceContext); if (index == null) { serviceIndexMap.put(serviceContext, serviceIndexCount); index = serviceIndexCount; serviceIndexCount++; } return index; } private GatewayManagementBean getLocalGatewayManagementBean() { GatewayManagementBean gatewayManagementBean = getGatewayManagementBean(localGatewayHostAndPid); if (gatewayManagementBean == null) { throw new RuntimeException("GatewayManagementBean has not been created, dependency injection failed."); } return gatewayManagementBean; } private GatewayManagementBean getGatewayManagementBean(String hostAndPid) { return gatewayManagementBeans.get(hostAndPid); } private ClusterConfigurationBean addClusterConfigurationBean(ClusterContext clusterContext, GatewayManagementBean gatewayBean) { // Note: per current 4.0 implementation, clusterContext will never be null ClusterConfigurationBean clusterConfigBean = new ClusterConfigurationBeanImpl(clusterContext, gatewayBean); gatewayBean.setClusterContext(clusterContext); if (gatewayBean instanceof GatewayManagementBeanImpl) { clusterContext.getCollectionsFactory() .addEntryListener((GatewayManagementBeanImpl) gatewayBean, ManagementService.MANAGEMENT_SERVICE_MAP_NAME); } for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addClusterConfigurationBean(clusterConfigBean); } return clusterConfigBean; } private SecurityConfigurationBean addSecurityConfigurationBean(SecurityContext securityContext, GatewayManagementBean gatewayBean) { SecurityConfigurationBean securityBean = new SecurityConfigurationBeanImpl(securityContext, gatewayBean); for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addSecurityConfigurationBean(securityBean); } return securityBean; } private RealmConfigurationBean addRealmConfigurationBean(RealmContext realm, GatewayManagementBean gatewayBean) { RealmConfigurationBean realmBean = new RealmConfigurationBeanImpl(realm, gatewayBean); for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addRealmConfigurationBean(realmBean); } return realmBean; } private ServiceConfigurationBean addServiceConfigurationBean(ServiceContext service, GatewayManagementBean gatewayBean) { ServiceConfigurationBean serviceConfigurationBean = new ServiceConfigurationBeanImpl(service, gatewayBean); ServiceConfigurationBean tmpServiceConfigBean = serviceConfigBeans.putIfAbsent(service, serviceConfigurationBean); if (tmpServiceConfigBean != null) { return tmpServiceConfigBean; } for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addServiceConfigurationBean(serviceConfigurationBean); } return serviceConfigurationBean; } private void addVersionInfo(GatewayManagementBean gatewayBean) { for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addVersionInfo(gatewayBean); } } private void addSystemInfo(GatewayManagementBean gatewayBean) { final HostManagementBean systemManagementBean = new HostManagementBeanImpl(gatewayBean); for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addSystemManagementBean(systemManagementBean); } // Get the bean 'started'. NOTE THAT THIS CALL STARTS ON THE IO THREAD! systemManagementBean.managementStrategyChanged(); } /** * Add a controller management bean for the list of CPUs, and individual CPU management beans for the CPUs/cores in the * gateway's system */ private void addCpuListInfo(GatewayManagementBean gatewayBean) { final CpuListManagementBean cpuListManagementBean = new CpuListManagementBeanImpl(gatewayBean); for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addCpuListManagementBean(cpuListManagementBean); } CpuManagementBean[] cpuManagementBeans = cpuListManagementBean.getCpuManagementBeans(); String hostAndPid = gatewayBean.getHostAndPid(); for (int i = 0; i < cpuManagementBeans.length; i++) { for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addCpuManagementBean(cpuManagementBeans[i], hostAndPid); } } // Get the bean 'started'. NOTE THAT THIS CALL STARTS ON THE IO THREAD! cpuListManagementBean.managementStrategyChanged(); } /** * Add management beans for the entire set of NICs on the gateway's host system. */ private void addNicListInfo(GatewayManagementBean gatewayBean) { final NicListManagementBean nicListManagementBean = new NicListManagementBeanImpl(gatewayBean); for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addNicListManagementBean(nicListManagementBean); } NicManagementBean[] nicManagementBeans = nicListManagementBean.getNicManagementBeans(); String hostAndPid = gatewayBean.getHostAndPid(); for (int i = 0; i < nicManagementBeans.length; i++) { for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addNicManagementBean(nicManagementBeans[i], hostAndPid); } } // Get the bean 'started'. NOTE THAT THIS CALL STARTS ON THE IO THREAD! nicListManagementBean.managementStrategyChanged(); } private void addJvmInfo(GatewayManagementBean gatewayBean) { final JvmManagementBean jvmManagementBean = new JvmManagementBeanImpl(gatewayBean); for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addJvmManagementBean(jvmManagementBean); } // Get the bean 'started'. NOTE THAT THIS CALL STARTS ON THE IO THREAD! jvmManagementBean.managementStrategyChanged(); } private ServiceDefaultsConfigurationBean addServiceDefaultsConfigurationBean(ServiceDefaultsContext serviceDefaultsContext, GatewayManagementBean gatewayBean) { ServiceDefaultsConfigurationBean serviceDefaultsConfigurationBean = new ServiceDefaultsConfigurationBeanImpl(serviceDefaultsContext, gatewayBean); for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addServiceDefaultsConfigurationBean(serviceDefaultsConfigurationBean); } return serviceDefaultsConfigurationBean; } private ManagementFilter addManagementFilter(ServiceContext serviceContext, ServiceManagementBean serviceBean) { ManagementFilter managementFilter = new ManagementFilter(serviceBean); managementFilters.put(serviceContext, managementFilter); return managementFilter; } @Override public ManagementFilter getManagementFilter(ServiceContext serviceContext) { ManagementFilter managementFilter = managementFilters.get(serviceContext); if (managementFilter == null) { // Service Management Beans are created in initing, getManagementFilter is done // on service start through session initializer ServiceManagementBean serviceBean = serviceManagementBeans.get(serviceContext); managementFilter = addManagementFilter(serviceContext, serviceBean); } return managementFilter; } @Override public ManagementFilterStrategy getManagementFilterStrategy() { return (ManagementFilterStrategy) managementStrategy[FILTER_INDEX]; } @Override public ManagementGatewayStrategy getManagementGatewayStrategy() { return (ManagementGatewayStrategy) managementStrategy[GATEWAY_INDEX]; } @Override public ManagementServiceStrategy getManagementServiceStrategy() { return (ManagementServiceStrategy) managementStrategy[SERVICE_INDEX]; } @Override public ManagementSessionStrategy getManagementSessionStrategy() { return (ManagementSessionStrategy) managementStrategy[SESSION_INDEX]; } @Override public ManagementSystemStrategy getManagementSystemStrategy() { return (ManagementSystemStrategy) managementStrategy[SYSTEM_INDEX]; } /** * Create a ServiceManagementBean for a resource address on the local Gateway instance. * <p/> * XXX We need to do something more if we're going to support some idea of storing services from another Gateway instance in * the same repository, as we won't generally have ServiceContext to work with (since the other instance will be in a * different process, perhaps on a different machine.) */ @Override public void addServiceManagementBean(ServiceContext serviceContext) { GatewayManagementBean gatewayManagementBean = getLocalGatewayManagementBean(); ServiceManagementBean serviceManagementBean = serviceManagmentBeanFactory.newServiceManagementBean( serviceContext.getServiceType(), gatewayManagementBean, serviceContext); ServiceManagementBean tempBean = serviceManagementBeans.putIfAbsent(serviceContext, serviceManagementBean); if (tempBean == null) { // A bean was not already created for this service for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addServiceManagementBean(serviceManagementBean); } } } /** * Create a SessionManagementBean for a resource address on the local Gateway instance. * <p/> * XXX We need to do something more if we're going to support some idea of storing sessions from another Gateway instance in * the same repository, as we won't generally have ServiceContext or IoSessions to work with (since the other instance will * be in a different process, perhaps on a different machine.) * <p/> * NOTE: we store the service resource address on the management bean because we need it later to do protocol-specific things * like reconstruct JMX session mbean names. NOTE: the managementProcessors are called during the constructor, so the bean * has not yet been loaded into the list of sessionManagement beans. */ @Override public SessionManagementBean addSessionManagementBean(ServiceManagementBean serviceManagementBean, IoSessionEx session) { SessionManagementBean sessionManagementBean = new SessionManagementBeanImpl(serviceManagementBean, session); for (ManagementServiceHandler handler : managementServiceHandlers) { handler.addSessionManagementBean(sessionManagementBean); } return sessionManagementBean; } @Override public void removeSessionManagementBean(SessionManagementBean sessionBean) { for (ManagementServiceHandler handler : managementServiceHandlers) { handler.removeSessionManagementBean(sessionBean); } } @Override public void updateManagementContext(SecurityContext securityContext) { if (managementConfigured.compareAndSet(false, true)) { GatewayManagementBean gatewayBean = getLocalGatewayManagementBean(); // services Collection<? extends ServiceContext> services = gatewayContext.getServices(); if ((services != null) && !services.isEmpty()) { for (ServiceContext service : services) { addServiceConfigurationBean(service, gatewayBean); } } addVersionInfo(gatewayBean); addSystemInfo(gatewayBean); addCpuListInfo(gatewayBean); addNicListInfo(gatewayBean); addJvmInfo(gatewayBean); ClusterContext clusterContext = gatewayContext.getCluster(); if (clusterContext != null) { addClusterConfigurationBean(clusterContext, gatewayBean); } addSecurityConfigurationBean(securityContext, gatewayBean); Collection<? extends RealmContext> realms = gatewayContext.getRealms(); if ((realms != null) && !realms.isEmpty()) { for (RealmContext realm : realms) { addRealmConfigurationBean(realm, gatewayBean); } } ServiceDefaultsContext serviceDefaults = gatewayContext.getServiceDefaults(); if (serviceDefaults != null) { addServiceDefaultsConfigurationBean(serviceDefaults, gatewayBean); } } } @Override public SummaryManagementInterval getGatewaySummaryDataNotificationInterval() { return gatewaySummaryDataNotificationInterval; } @Override public SummaryManagementInterval getServiceSummaryDataNotificationInterval() { return serviceSummaryDataNotificationInterval; } @Override public SummaryManagementInterval getSessionSummaryDataNotificationInterval() { return sessionSummaryDataNotificationInterval; } @Override public SummaryManagementInterval getSystemSummaryDataGatherInterval() { return systemSummaryDataGatherInterval; } @Override public SummaryManagementInterval getSystemSummaryDataNotificationInterval() { return systemSummaryDataNotificationInterval; } @Override public SummaryManagementInterval getCpuListSummaryDataGatherInterval() { return cpuListSummaryDataGatherInterval; } @Override public SummaryManagementInterval getCpuListSummaryDataNotificationInterval() { return cpuListSummaryDataNotificationInterval; } @Override public SummaryManagementInterval getNicListSummaryDataGatherInterval() { return nicListSummaryDataGatherInterval; } @Override public SummaryManagementInterval getNicListSummaryDataNotificationInterval() { return nicListSummaryDataNotificationInterval; } @Override public SummaryManagementInterval getJvmSummaryDataGatherInterval() { return jvmSummaryDataGatherInterval; } @Override public SummaryManagementInterval getJvmSummaryDataNotificationInterval() { return jvmSummaryDataNotificationInterval; } private final class SummaryManagementIntervalImpl implements SummaryManagementInterval { private int interval; private SummaryManagementIntervalImpl(int interval) { this.interval = interval; } @Override public int getInterval() { return interval; } @Override public void setInterval(int interval) { this.interval = interval; } } @Override public String getName() { return "managementContext"; } @Override public void createGatewayManagementBean() { GatewayManagementBean gatewayManagementBean = new GatewayManagementBeanImpl(this, this.gatewayContext, localGatewayHostAndPid); gatewayManagementBeans.put(localGatewayHostAndPid, gatewayManagementBean); } }
apache-2.0
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/package-info.java
88
@org.osgi.annotation.versioning.Version("1.0.0") package osgi.enroute.trains.cloud.api;
apache-2.0
tylerbwong/Pokebase-SQLite
app/src/main/java/me/tylerbwong/pokebase/model/components/Move.java
1991
/* * Copyright 2016 Tyler Wong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.tylerbwong.pokebase.model.components; /** * @author Tyler Wong */ public class Move { private int moveId; private String name; private int typeId; private int power; private int pp; private int accuracy; private String className; private String description; private String typeName; public Move(int moveId, String name, int typeId, int power, int pp, int accuracy, String className) { this.moveId = moveId; this.name = name; this.typeId = typeId; this.power = power; this.pp = pp; this.accuracy = accuracy; this.className = className; } public int getMoveId() { return moveId; } public String getName() { return name; } public int getTypeId() { return typeId; } public int getPower() { return power; } public int getPp() { return pp; } public int getAccuracy() { return accuracy; } public String getClassName() { return className; } public String getDescription() { return description; } public String getTypeName() { return typeName; } public void setDescription(String description) { this.description = description; } public void setTypeName(String typeName) { this.typeName = typeName; } }
apache-2.0
jexp/idea2
platform/lang-api/src/com/intellij/execution/util/EnvVariablesTable.java
6382
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.util; import com.intellij.CommonBundle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.util.IconLoader; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.table.TableView; import com.intellij.util.ui.ColumnInfo; import com.intellij.util.ui.ListTableModel; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Observable; public class EnvVariablesTable extends Observable { private final List<EnvironmentVariable> myVariables = new ArrayList<EnvironmentVariable>(); private final JPanel myPanel = new JPanel(new BorderLayout()); private final ColumnInfo NAME = new ColumnInfo<EnvironmentVariable, String>("Name") { public String valueOf(EnvironmentVariable environmentVariable) { return environmentVariable.getName(); } public Class getColumnClass() { return String.class; } public boolean isCellEditable(EnvironmentVariable environmentVariable) { return environmentVariable.getNameIsWriteable(); } public void setValue(EnvironmentVariable environmentVariable, String s) { if (s.equals(valueOf(environmentVariable))) { return; } environmentVariable.setName(s); setModified(); } }; private final ColumnInfo VALUE = new ColumnInfo<EnvironmentVariable, String>("Value") { public String valueOf(EnvironmentVariable environmentVariable) { return environmentVariable.getValue(); } public Class getColumnClass() { return String.class; } public boolean isCellEditable(EnvironmentVariable environmentVariable) { return !environmentVariable.getIsPredefined(); } public void setValue(EnvironmentVariable environmentVariable, String s) { if (s.equals(valueOf(environmentVariable))) { return; } environmentVariable.setValue(s); setModified(); } }; private final TableView myTableVeiw; private boolean myIsEnabled = true; public EnvVariablesTable() { myTableVeiw = new TableView(new ListTableModel((new ColumnInfo[]{NAME, VALUE}))); myTableVeiw.getTableViewModel().setSortable(false); myPanel.add(ScrollPaneFactory.createScrollPane(myTableVeiw.getComponent()), BorderLayout.CENTER); JComponent toolbarComponent = createToolbar(); myPanel.add(toolbarComponent, BorderLayout.NORTH); myTableVeiw.getComponent().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } private void setModified() { setChanged(); notifyObservers(); } private JComponent createToolbar() { DefaultActionGroup actions = new DefaultActionGroup(); actions.add(new AddAction()); actions.add(new DeleteAction()); JComponent toolbarComponent = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, true).getComponent(); return toolbarComponent; } public JComponent getComponent() { return myPanel; } public void setEnabled() { myTableVeiw.getComponent().setEnabled(true); myIsEnabled = true; } public void setDisabled() { myTableVeiw.getComponent().setEnabled(false); myIsEnabled = false; } public void setValues(List<EnvironmentVariable> envVariables) { myVariables.clear(); for (EnvironmentVariable envVariable : envVariables) { myVariables.add(envVariable.clone()); } myTableVeiw.getTableViewModel().setItems(myVariables); } public List<EnvironmentVariable> getEnvironmentVariables() { return myVariables; } public void refreshValues() { myTableVeiw.getComponent().repaint(); } private final class DeleteAction extends AnAction { public DeleteAction() { super(CommonBundle.message("button.delete"), null, IconLoader.getIcon("/general/remove.png")); } public void update(AnActionEvent e) { EnvironmentVariable selection = getSelection(); Presentation presentation = e.getPresentation(); presentation.setEnabled(selection != null && myIsEnabled && !selection.getIsPredefined()); } public void actionPerformed(AnActionEvent e) { myTableVeiw.stopEditing(); setModified(); EnvironmentVariable selected = getSelection(); if (selected != null) { int selectedIndex = myVariables.indexOf(selected); myVariables.remove(selected); myTableVeiw.getTableViewModel().setItems(myVariables); int prev = selectedIndex - 1; if (prev >= 0) { myTableVeiw.getComponent().getSelectionModel().setSelectionInterval(prev, prev); } else if (selectedIndex < myVariables.size()) { myTableVeiw.getComponent().getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex); } } } } private final class AddAction extends AnAction { public AddAction() { super(CommonBundle.message("button.add"), null, IconLoader.getIcon("/general/add.png")); } public void update(AnActionEvent e) { Presentation presentation = e.getPresentation(); presentation.setEnabled(myIsEnabled); } public void actionPerformed(AnActionEvent e) { myTableVeiw.stopEditing(); setModified(); SwingUtilities.invokeLater(new Runnable() { public void run() { myVariables.add(new EnvironmentVariable("", "", false)); myTableVeiw.getTableViewModel().setItems(myVariables); myTableVeiw.getComponent().editCellAt(myVariables.size() - 1, 0); } }); } } private EnvironmentVariable getSelection() { int selIndex = myTableVeiw.getComponent().getSelectionModel().getMinSelectionIndex(); if (selIndex < 0) { return null; } else { return myVariables.get(selIndex); } } }
apache-2.0
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/yesod/cassius/CassiusFileType.java
1157
package org.jetbrains.yesod.cassius; /** * @author Leyla H */ import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.haskell.icons.HaskellIcons; import org.jetbrains.yesod.cassius.CassiusLanguage; import javax.swing.*; public class CassiusFileType extends LanguageFileType { public static final CassiusFileType INSTANCE = new CassiusFileType(); @NonNls public static final String DEFAULT_EXTENSION = "cassius"; private Icon myIcon; private CassiusFileType() { super(CassiusLanguage.INSTANCE); myIcon = HaskellIcons.HAMLET; } @NotNull public String getName() { return "Cassius file"; } @NotNull public String getDescription() { return "Cassius file"; } @NotNull public String getDefaultExtension() { return DEFAULT_EXTENSION; } public Icon getIcon() { return myIcon; } public String getCharset(@NotNull VirtualFile file, final byte[] content) { return "UTF-8"; } }
apache-2.0
dlwhitehurst/MusicRecital
src/main/java/org/musicrecital/webapp/pages/FileDisplay.java
1502
/** * Copyright 2014 David L. Whitehurst * * Licensed under the Apache License, Version 2.0 * (the "License"); You may not use this file except * in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. * */ package org.musicrecital.webapp.pages; import org.apache.tapestry5.PersistenceConstants; import org.apache.tapestry5.annotations.Persist; import org.apache.tapestry5.annotations.Property; import org.musicrecital.webapp.data.FileData; /** * This class handles the uploading of a file and writing it to * the filesystem. Eventually, it will also addChild support for persisting the * files information into the database. * * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a> * @author Serge Eby * @version $Id$ */ public class FileDisplay { @Persist(PersistenceConstants.FLASH) @Property(write = false) private FileData fileData; public void setFileData(FileData fileData) { this.fileData = fileData; } Object onDone() { return Home.class; } Object onAnotherUpload() { return FileUpload.class; } }
apache-2.0
akarnokd/ReactiveChannel
src/main/java/hu/akarnokd/reactivechannel/ChannelConnection.java
1308
/* * Copyright 2015 David Karnok * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package hu.akarnokd.reactivechannel; import org.reactivestreams.Publisher; /** * Represents the connection between a ChannelPublisher and * a ChannelSubscriber and allows the ChannelSubscriber * to issue requests and close the channel. * * @param <Request> the request type * @param <Response> the response type */ public interface ChannelConnection<Request, Response> { /** * Requests a stream of response for a given value. * @param request the request value, not null * @return the Publisher that contains the response value(s) for the particular request */ Publisher<Response> query(Request request); /** * Closes the connection. */ void close(); }
apache-2.0
consulo/consulo-maven
plugin/src/main/java/org/jetbrains/idea/maven/dom/references/MavenUrlPsiReference.java
1453
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.dom.references; import javax.annotation.Nonnull; import com.intellij.ide.BrowserUtil; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.FakePsiElement; public class MavenUrlPsiReference extends MavenPsiReference { public MavenUrlPsiReference(PsiElement element, String text, TextRange range) { super(element, text, range); } public PsiElement resolve() { return new FakePsiElement() { public PsiElement getParent() { return myElement; } @Override public String getName() { return myText; } @Override public void navigate(boolean requestFocus) { BrowserUtil.launchBrowser(myText); } }; } @Nonnull public Object[] getVariants() { return EMPTY_ARRAY; } }
apache-2.0
funny5258/txstack
stack-common/src/main/java/com/funny/txstack/base/BaseServiceImpl.java
1223
package com.funny.txstack.base; import java.util.List; /** * 基础Service接口实现<br> * 处理公用的CRUD、分页等 * * @author fangli 2014-7-28 */ public abstract class BaseServiceImpl<T extends BaseEntity> implements BaseService<T> { protected abstract BaseMapper<T> baseMapper(); /** * 保存实体 * * @throws Exception */ @Override public int insert(T entity) throws Exception { return baseMapper().insert(entity); } /** * 更新实体(根据主键ID) * * @throws Exception */ @Override public int updateById(T entity) throws Exception { return baseMapper().updateById(entity); } /** * 返回实体 * * @return * @throws Exception */ @Override public T findById(Long id) throws Exception { return baseMapper().findById(id); } /** * 返回实体List * * @return * @throws Exception */ @Override public List<T> findList(T entity) throws Exception { return baseMapper().findList(entity); } @Override public int count(T entity) throws Exception { return baseMapper().count(entity); } }
apache-2.0
kite-sdk/kite
kite-morphlines/kite-morphlines-tika-core/src/test/java/org/kitesdk/morphline/tika/DetectMimeTypesTest.java
13394
/* * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.morphline.tika; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import org.kitesdk.morphline.api.AbstractMorphlineTest; import org.kitesdk.morphline.api.Command; import org.kitesdk.morphline.api.Record; import org.kitesdk.morphline.base.Fields; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.io.Files; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; public class DetectMimeTypesTest extends AbstractMorphlineTest { private Map<List, Command> morphlineCache = new HashMap(); private static final String AVRO_MIME_TYPE = "avro/binary"; // ReadAvroContainerBuilder.MIME_TYPE; private static final File AVRO_FILE = new File(RESOURCES_DIR + "/test-documents/sample-statuses-20120906-141433.avro"); private static final File JPG_FILE = new File(RESOURCES_DIR + "/test-documents/testJPEG_EXIF.jpg"); @Test public void testDetectMimeTypesWithFile() throws Exception { // config file uses mimeTypesFiles : [src/test/resources/org/apache/tika/mime/custom-mimetypes.xml] testDetectMimeTypesInternal("test-morphlines/detectMimeTypesWithFile"); } @Test public void testDetectMimeTypesWithString() throws Exception { // config file uses mimeTypesString : """ some mime types go here """ testDetectMimeTypesInternal("test-morphlines/detectMimeTypesWithString"); } private void testDetectMimeTypesInternal(String configFile) throws Exception { // verify that Avro is classified as Avro morphline = createMorphline(configFile); Record record = new Record(); record.put(Fields.ATTACHMENT_BODY, Files.toByteArray(AVRO_FILE)); startSession(); morphline.process(record); assertEquals(AVRO_MIME_TYPE, collector.getFirstRecord().getFirstValue(Fields.ATTACHMENT_MIME_TYPE)); // verify that JPG isnt' classified as JPG because this morphline uses includeDefaultMimeTypes : false collector.reset(); record = new Record(); record.put(Fields.ATTACHMENT_BODY, Files.toByteArray(JPG_FILE)); startSession(); morphline.process(record); assertEquals("application/octet-stream", collector.getFirstRecord().getFirstValue(Fields.ATTACHMENT_MIME_TYPE)); } @Test public void testDetectMimeTypesWithDefaultMimeTypes() throws Exception { morphline = createMorphline("test-morphlines/detectMimeTypesWithDefaultMimeTypes"); Record record = new Record(); record.put(Fields.ATTACHMENT_BODY, Files.toByteArray(JPG_FILE)); startSession(); morphline.process(record); assertEquals("image/jpeg", collector.getFirstRecord().getFirstValue(Fields.ATTACHMENT_MIME_TYPE)); } @Test public void testMimeTypeAlreadySpecifiedOnInputRemainsUnchanged() throws Exception { morphline = createMorphline("test-morphlines/detectMimeTypesWithDefaultMimeTypes"); Record record = new Record(); record.put(Fields.ATTACHMENT_BODY, Files.toByteArray(JPG_FILE)); record.put(Fields.ATTACHMENT_MIME_TYPE, "foo/bar"); startSession(); morphline.process(record); assertEquals("foo/bar", collector.getFirstRecord().getFirstValue(Fields.ATTACHMENT_MIME_TYPE)); } @Test public void testPlainText() throws Exception { Record event = createEvent("foo".getBytes("UTF-8")); assertEquals("text/plain", detect(event, false)); } @Test public void testUnknownType() throws Exception { Record event = createEvent(new byte[] {3, 4, 5, 6}); assertEquals("application/octet-stream", detect(event, false)); } @Test public void testUnknownEmptyType() throws Exception { Record event = createEvent(new byte[0]); assertEquals("application/octet-stream", detect(event, false)); } @Ignore @Test public void testNullType() throws Exception { Record event = createEvent(null); assertEquals("application/octet-stream", detect(event, false)); } @Test public void testXML() throws Exception { Record event = createEvent("<?xml version=\"1.0\"?><foo/>".getBytes("UTF-8")); assertEquals("application/xml", detect(event, false)); } public void testXML11() throws Exception { Record event = createEvent("<?xml version=\"1.1\"?><foo/>".getBytes("UTF-8")); assertEquals("application/xml", detect(event, false)); } public void testXMLAnyVersion() throws Exception { Record event = createEvent("<?xml version=\"\"?><foo/>".getBytes("UTF-8")); assertEquals("application/xml", detect(event, false)); } @Test public void testXMLasTextPlain() throws Exception { Record event = createEvent("<foo/>".getBytes("UTF-8")); assertEquals("text/plain", detect(event, false)); } @Test public void testVariousFileTypes() throws Exception { String path = RESOURCES_DIR + "/test-documents"; String[] files = new String[] { path + "/testBMPfp.txt", "text/plain", "text/plain", path + "/boilerplate.html", "application/xhtml+xml", "application/xhtml+xml", path + "/NullHeader.docx", "application/zip", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", path + "/testWORD_various.doc", "application/x-tika-msoffice", "application/msword", path + "/testPDF.pdf", "application/pdf", "application/pdf", path + "/testJPEG_EXIF.jpg", "image/jpeg", "image/jpeg", path + "/testXML.xml", "application/xml", "application/xml", path + "/cars.tsv", "text/plain", "text/tab-separated-values", path + "/cars.ssv", "text/plain", "text/space-separated-values", path + "/cars.csv", "text/plain", "text/csv", path + "/cars.csv.gz", "application/gzip", "application/gzip", path + "/cars.tar.gz", "application/gzip", "application/gzip", path + "/sample-statuses-20120906-141433.avro", "avro/binary", "avro/binary", path + "/testPPT_various.ppt", "application/x-tika-msoffice", "application/vnd.ms-powerpoint", path + "/testPPT_various.pptx", "application/x-tika-ooxml", "application/vnd.openxmlformats-officedocument.presentationml.presentation", path + "/testEXCEL.xlsx", "application/x-tika-ooxml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", path + "/testEXCEL.xls", "application/vnd.ms-excel", "application/vnd.ms-excel", path + "/testPages.pages", "application/zip", "application/vnd.apple.pages", // path + "/testNumbers.numbers", "application/zip", "application/vnd.apple.numbers", // path + "/testKeynote.key", "application/zip", "application/vnd.apple.keynote", path + "/testRTFVarious.rtf", "application/rtf", "application/rtf", path + "/complex.mbox", "text/plain", "application/mbox", path + "/test-outlook.msg", "application/x-tika-msoffice", "application/vnd.ms-outlook", path + "/testEMLX.emlx", "message/x-emlx", "message/x-emlx", path + "/testRFC822", "message/rfc822", "message/rfc822", path + "/rsstest.rss", "application/rss+xml", "application/rss+xml", path + "/testDITA.dita", "application/dita+xml; format=task", "application/dita+xml; format=task", path + "/testMP3i18n.mp3", "audio/mpeg", "audio/mpeg", path + "/testAIFF.aif", "audio/x-aiff", "audio/x-aiff", path + "/testFLAC.flac", "audio/x-flac", "audio/x-flac", path + "/testFLAC.oga", "application/ogg", "audio/ogg", path + "/testVORBIS.ogg", "audio/vorbis", "audio/vorbis", path + "/testMP4.m4a", "audio/mp4", "audio/mp4", path + "/testWAV.wav", "audio/x-wav", "audio/x-wav", path + "/testWMA.wma", "audio/x-ms-wma", "audio/x-ms-wma", path + "/testFLV.flv", "video/x-flv", "video/x-flv", path + "/testWMV.wmv", "video/x-ms-wmv", "video/x-ms-wmv", path + "/testBMP.bmp", "image/x-ms-bmp", "image/x-ms-bmp", path + "/testPNG.png", "image/png", "image/png", path + "/testPSD.psd", "image/vnd.adobe.photoshop", "image/vnd.adobe.photoshop", path + "/testSVG.svg", "image/svg+xml", "image/svg+xml", path + "/testTIFF.tif", "image/tiff", "image/tiff", path + "/test-documents.7z", "application/x-7z-compressed", "application/x-7z-compressed", path + "/test-documents.cpio", "application/x-cpio", "application/x-cpio", path + "/test-documents.tar", "application/x-gtar", "application/x-gtar", path + "/test-documents.tbz2", "application/x-bzip2", "application/x-bzip2", path + "/test-documents.tgz", "application/gzip", "application/gzip", path + "/test-documents.zip", "application/zip", "application/zip", path + "/test-zip-of-zip.zip", "application/zip", "application/zip", path + "/testJAR.jar", "application/zip", "application/java-archive", path + "/testKML.kml", "application/vnd.google-earth.kml+xml", "application/vnd.google-earth.kml+xml", path + "/testRDF.rdf", "application/rdf+xml", "application/rdf+xml", path + "/testVISIO.vsd", "application/x-tika-msoffice", "application/vnd.visio", path + "/testWAR.war", "application/zip", "application/x-tika-java-web-archive", path + "/testWindows-x86-32.exe", "application/x-msdownload; format=pe32", "application/x-msdownload; format=pe32", path + "/testWINMAIL.dat", "application/vnd.ms-tnef", "application/vnd.ms-tnef", path + "/testWMF.wmf", "application/x-msmetafile", "application/x-msmetafile", }; for (int i = 0; i < files.length; i += 3) { byte[] body = Files.toByteArray(new File(files[i+0])); ListMultimap<String, Object> emptyMap = ArrayListMultimap.create(); Record event = createEvent(new ByteArrayInputStream(body), emptyMap); assertEquals(files[i+1], detect(event, false)); } for (int i = 0; i < files.length; i += 3) { byte[] body = Files.toByteArray(new File(files[i+0])); ListMultimap headers = ImmutableListMultimap.of(Fields.ATTACHMENT_NAME, new File(files[i+0]).getName()); Record event = createEvent(new ByteArrayInputStream(body), headers); assertEquals(files[i+2], detect(event, true)); } for (int i = 0; i < files.length; i += 3) { byte[] body = Files.toByteArray(new File(files[i+0])); ListMultimap headers = ImmutableListMultimap.of(Fields.ATTACHMENT_NAME, new File(files[i+0]).getPath()); Record event = createEvent(new ByteArrayInputStream(body), headers); assertEquals(files[i+2], detect(event, true)); } // test excludeParameters flag: boolean excludeParameters = true; byte[] body = Files.toByteArray(new File(path + "/testWindows-x86-32.exe")); ListMultimap headers = ImmutableListMultimap.of(Fields.ATTACHMENT_NAME, new File(path + "/testWindows-x86-32.exe").getPath()); Record event = createEvent(new ByteArrayInputStream(body), headers); assertEquals("application/x-msdownload", detect(event, true, excludeParameters)); } private Record createEvent(byte[] bytes) { ListMultimap<String, Object> emptyMap = ArrayListMultimap.create(); return createEvent(new ByteArrayInputStream(bytes), emptyMap); } private Record createEvent(InputStream in, ListMultimap<String, Object> headers) { Record record = new Record(); record.getFields().putAll(headers); record.replaceValues(Fields.ATTACHMENT_BODY, in); return record; } private String detect(Record event, boolean includeMetaData) throws IOException { return detect(event, includeMetaData, false); } private String detect(Record event, boolean includeMetaData, boolean excludeParameters) throws IOException { List key = Arrays.asList(includeMetaData, excludeParameters); Command cachedMorphline = morphlineCache.get(key); if (cachedMorphline == null) { // avoid recompiling time and again (performance) Config override = ConfigFactory.parseString("INCLUDE_META_DATA : " + includeMetaData + "\nEXCLUDE_PARAMETERS : " + excludeParameters); cachedMorphline = createMorphline("test-morphlines/detectMimeTypesWithDefaultMimeTypesAndFile", override); morphlineCache.put(key, cachedMorphline); } collector.reset(); assertTrue(cachedMorphline.process(event)); String mimeType = (String) collector.getFirstRecord().getFirstValue(Fields.ATTACHMENT_MIME_TYPE); return mimeType; } }
apache-2.0
drochetti/jnap-core
src/main/java/org/jnap/core/mvc/view/StreamView.java
3114
package org.jnap.core.mvc.view; import static java.text.MessageFormat.format; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.springframework.util.Assert; import org.springframework.web.servlet.View; /** * @author Daniel Rochetti */ public class StreamView implements View { protected static final String CONTENT_DISPOSITION_INLINE = "inline"; protected static final String CONTENT_DISPOSITION_ATTACHMENT = "attachment; filename=\"{0}\""; private String contentType; private InputStream inputStream; private String contentDisposition = CONTENT_DISPOSITION_INLINE; private String fileName; private int bufferSize = 1024; public StreamView(String contentType, InputStream inputStream) { this.contentType = contentType; this.inputStream = inputStream; } public StreamView(String contentType, File file) { this.contentType = contentType; try { this.inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { throw new IllegalStateException("Could open read stream to file", e); } this.setFileName(file.getName()); } @Override public String getContentType() { return this.contentType; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Assert.notNull(this.inputStream); OutputStream out = response.getOutputStream(); // writting the output try { byte[] buffer = new byte[this.bufferSize]; int totalLength = 0; int length = 0; while ((length = this.inputStream.read(buffer)) != -1) { out.write(buffer, 0, length); totalLength += length; } // configuring response response.setContentLength(totalLength); response.setContentType(this.contentType); response.addHeader("Content-Disposition", this.contentDisposition); } finally { IOUtils.closeQuietly(this.inputStream); out.flush(); IOUtils.closeQuietly(out); } } /** * * @see #asAttachment(String) * @return the {@code StreamView} itself for fluent method call. */ public StreamView asAttachment() { String fileName = this.fileName != null ? this.fileName : "file"; setContentDisposition(format(CONTENT_DISPOSITION_ATTACHMENT, fileName)); return this; } /** * Serve the stream as an attachment. * @param fileName * @return the {@code StreamView} itself for fluent method call. */ public StreamView asAttachment(String fileName) { setFileName(fileName); return asAttachment(); } public StreamView asInline() { setContentDisposition(CONTENT_DISPOSITION_INLINE); return this; } public void setContentDisposition(String contentDisposition) { this.contentDisposition = contentDisposition; } public void setFileName(String fileName) { this.fileName = fileName; } public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } }
apache-2.0
ekoshkin/teamcity-kubernetes-plugin
teamcity-kubernetes-plugin-agent/src/main/java/jetbrains/buildServer/helm/HelmCommandArgumentsProvider.java
391
package jetbrains.buildServer.helm; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; /** * Created by Evgeniy Koshkin (evgeniy.koshkin@jetbrains.com) on 29.11.17. */ public interface HelmCommandArgumentsProvider { @NotNull String getCommandId(); @NotNull List<String> getArguments(@NotNull Map<String, String> runnerParameters); }
apache-2.0
JorgePereiraUFRN/Myeclone
Myeclone/src/br/ufrn/Myeclone/controler/Service/PostagemService.java
4259
package br.ufrn.Myeclone.controler.Service; import java.sql.Time; import java.util.Calendar; import java.util.Date; import java.util.List; import br.ufrn.Myeclone.DAO.AtividadeDAO; import br.ufrn.Myeclone.DAO.AtividadesDaoInterface; import br.ufrn.Myeclone.DAO.PostagemDAO; import br.ufrn.Myeclone.DAO.PostagemDaoInterface; import br.ufrn.Myeclone.Exceptions.DAOException; import br.ufrn.Myeclone.Exceptions.ObjetoNuloException; import br.ufrn.Myeclone.Exceptions.ServiceException; import br.ufrn.Myeclone.apifb.FBConnection; import br.ufrn.Myeclone.controler.AgendarPostagem; import br.ufrn.Myeclone.model.Atividade; import br.ufrn.Myeclone.model.Postagem; import java.util.logging.Level; import java.util.logging.Logger; public class PostagemService extends Service<Postagem> { PostagemDaoInterface postagemDAO; public PostagemService() { postagemDAO = factory.getPostagemDAO(); } private boolean validarPostagem(Postagem postagem) throws ObjetoNuloException, ValorNuloException { if (postagem == null) { throw new ObjetoNuloException("postagem is null"); } if (postagem.getAtividade().trim().equals("")) { throw new ValorNuloException("postagem.atividade is null"); } if (postagem.getData() == null) { throw new ValorNuloException("postagem.data is null"); } return true; } @Override public Postagem create(Postagem entity) throws ServiceException { try { if (validarPostagem(entity)) { try { return postagemDAO.save(entity); } catch (DAOException e) { throw new ServiceException("Erro ao salvar no BD "+e.getMessage()); } } } catch (ObjetoNuloException | ValorNuloException e) { throw new ServiceException(e.getMessage()); } return null; } @Override public Postagem update(Postagem entity) throws ServiceException { try { if (validarPostagem(entity) && entity.getId() != null) { try { return postagemDAO.update(entity); } catch (DAOException e) { throw new ServiceException("Erro ao alterar no BD "+e.getMessage()); } } } catch (ObjetoNuloException | ValorNuloException e) { throw new ServiceException(e.getMessage()); } return null; } @Override public void destroy(Postagem entity) throws ServiceException { try { postagemDAO.delete(entity); } catch (DAOException ex) { throw new ServiceException("Erro ao deletar a postagem"); } } @Override public Postagem retrieve(Long id) throws ServiceException { // TODO Auto-generated method stub return null; } @Override public List<Postagem> list() throws ServiceException { try { return postagemDAO.findAll(Postagem.class); } catch (DAOException e) { throw new ServiceException(e.getMessage()); } } public static void main(String args[]){ Postagem p = new Postagem(); Calendar c = Calendar.getInstance(); c.set(2014, 5, 25); p.setToken("CAAB3hpwGrPgBAGxmMHSZC5Myi4aozmhui7kT0f0v7e9w3PSpTFgLJlDIreM3VxJjubH4hsUh8WrRD8J9js1FnqmjBRE58tRoZABbzLhkKce6pbPWKrP7ZAAO2XUnYPDkQjq1aE7XLO7Go4uayilkHDQlZBoWZBDlZCnhC9jZCHCTdrlcycLeh4J3bJYl0fP9ZCUZD"); p.setDescricao("Testando RestFB"); p.setHorario(new Time(22, 30, 0)); p.setAtividade("postagemfb"); p.setCumprido(false); p.setData(c.getTime()); PostagemService ps = new PostagemService(); try { ps.create(p); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public List<Postagem> listByHora(Time inicio, Time fim) throws ServiceException { try { return postagemDAO.listByHour(inicio, fim); } catch (DAOException e) { throw new ServiceException(e.getMessage()); } } public void postar(String mensagem){ FBConnection fb = new FBConnection("131420027006200 ", "e0a0e740a7b895596c1c7beb4aa33dfd", "CAAB3hpwGrPgBAPiKnJQMqi8aQB1ZBsuHd453deFeHZAIjjA3PzqZCtdPk1C8F8QJ6MTkkcKLlBZC3Rm2BZBFR3KCm8h7h6qbQRDRznPSigBPGN3loS4KGTUrxenAE5ey0B9nUeMbPxZCASiw84gceUBcKVXJGYLL4nUd6ufL4hsLO7vRbaVGJqjaf1IexcPjHHRTepSHmnYAZDZD"); fb.enviarMensagem(mensagem); } }
apache-2.0
darrendao/kafka.play.time
clients/src/main/java/kafka/common/errors/ApiException.java
771
package kafka.common.errors; import kafka.common.KafkaException; /** * Any API exception that is part of the public protocol and should be a subclass of this class and be part of this * package. */ public abstract class ApiException extends KafkaException { private static final long serialVersionUID = 1L; public ApiException(String message, Throwable cause) { super(message, cause); } public ApiException(String message) { super(message); } public ApiException(Throwable cause) { super(cause); } public ApiException() { super(); } /* avoid the expensive and useless stack trace for api exceptions */ @Override public Throwable fillInStackTrace() { return this; } }
apache-2.0
androidertc/iLocker
src/com/qc4w/ilocker/ui/view/NameImageView.java
1358
package com.qc4w.ilocker.ui.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.ImageView; import com.qc4w.ilocker.R; import com.qc4w.ilocker.config.ConfigManager; import com.qc4w.ilocker.util.BitmapUtils; import com.qc4w.ilocker.util.ContourMapper; import com.qc4w.ilocker.util.ImageUtils; public class NameImageView extends FrameLayout { private ImageView ivBoder; private ImageView ivImage; public NameImageView(Context context, AttributeSet attrs) { super(context, attrs); inflate(context, R.layout.layout_name_image_view, this); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.NameImageView, 0, 0); array.recycle(); ivBoder = (ImageView) findViewById(R.id.iv_boder); ivImage = (ImageView) findViewById(R.id.iv_image); loadImage(); } public void loadImage() { ConfigManager config = ConfigManager.getInstance(getContext()); Bitmap boder = BitmapFactory.decodeResource(getResources(), ContourMapper.contourPresseds[config.getNameImageContour()]); ivBoder.setImageBitmap(BitmapUtils.getBitmap(config.getNameImageTextColor(), boder, 0.5f)); ivImage.setImageBitmap(ImageUtils.getNameImage(getContext())); } }
apache-2.0
xose/java-persona-verifier
src/main/java/com/github/xose/persona/verifier/RemoteVerifier.java
2533
/** * Copyright 2013 José Martínez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.xose.persona.verifier; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.Request; import com.ning.http.client.RequestBuilder; import com.ning.http.client.Response; public final class RemoteVerifier implements Verifier { public static final String DEFAULT_URL = "https://verifier.login.persona.org/verify"; private final AsyncHttpClient client; private final String verifyUrl; public RemoteVerifier() { this(DEFAULT_URL); } public RemoteVerifier(final String verifyUrl) { this.verifyUrl = checkNotNull(verifyUrl); client = new AsyncHttpClient(); } @Override public ListenableFuture<VerifyResult> verify(String assertion, String audience) { final SettableFuture<VerifyResult> future = SettableFuture.create(); Request request = new RequestBuilder("POST").setUrl(verifyUrl) .addParameter("assertion", assertion) .addParameter("audience", audience).build(); try { client.executeRequest(request, new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws IOException { if (200 != response.getStatusCode()) { future.setException(new Exception("HTTP Code " + response.getStatusCode())); return response; } try { future.set(VerifyResultParser.fromJSONString(response.getResponseBody())); } catch (Throwable e) { future.setException(new Exception("JSON parsing error", e)); } return response; } @Override public void onThrowable(Throwable t) { future.setException(t); } }); } catch (IOException e) { future.setException(e); } return future; } }
apache-2.0
vespa-engine/vespa
documentapi/src/test/java/com/yahoo/documentapi/VisitorParametersTestCase.java
5460
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.documentapi; import com.yahoo.document.fieldset.AllFields; import com.yahoo.documentapi.messagebus.loadtypes.LoadType; import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol; import org.junit.Test; import static org.junit.Assert.*; public class VisitorParametersTestCase { private LoadType loadType = new LoadType(3, "samnmax", DocumentProtocol.Priority.HIGH_3); @SuppressWarnings("removal")// TODO: Vespa 8: remove private VisitorParameters createVisitorParameters() { VisitorParameters params = new VisitorParameters(""); params.setDocumentSelection("id.user==5678"); params.setBucketSpace("narnia"); params.setFromTimestamp(9001); params.setToTimestamp(10001); params.setVisitorLibrary("CoolVisitor"); params.setLibraryParameter("groovy", "dudes"); params.setLibraryParameter("ninja", "turtles"); params.setMaxBucketsPerVisitor(55); params.setPriority(DocumentProtocol.Priority.HIGHEST); params.setRoute("extraterrestrial/highway"); params.setTimeoutMs(1337); params.setMaxPending(111); params.setFieldSet(AllFields.NAME); params.setLoadType(loadType); params.setVisitRemoves(true); params.setVisitInconsistentBuckets(true); params.setTraceLevel(9); params.setResumeFileName("foo.txt"); params.setResumeToken(new ProgressToken()); params.setRemoteDataHandler("mars_rover"); params.setControlHandler(new VisitorControlHandler()); params.setMaxFirstPassHits(555); params.setMaxTotalHits(777); params.setDynamicallyIncreaseMaxBucketsPerVisitor(true); params.setDynamicMaxBucketsIncreaseFactor(2.5f); params.skipBucketsOnFatalErrors(true); return params; } @SuppressWarnings("removal")// TODO: Vespa 8: remove @Test public void testCopyConstructor() { VisitorParameters params = createVisitorParameters(); VisitorParameters copy = new VisitorParameters(params); assertEquals("id.user==5678", copy.getDocumentSelection()); assertEquals(9001, copy.getFromTimestamp()); assertEquals(10001, copy.getToTimestamp()); assertEquals("CoolVisitor", copy.getVisitorLibrary()); assertEquals(2, copy.getLibraryParameters().size()); assertEquals("dudes", new String(copy.getLibraryParameters().get("groovy"))); assertEquals("turtles", new String(copy.getLibraryParameters().get("ninja"))); assertEquals(55, copy.getMaxBucketsPerVisitor()); assertEquals(DocumentProtocol.Priority.HIGHEST, copy.getPriority()); assertEquals("extraterrestrial/highway", copy.getRoute().toString()); assertEquals(1337, copy.getTimeoutMs()); assertEquals(111, copy.getMaxPending()); assertEquals(AllFields.NAME, copy.getFieldSet()); assertEquals(loadType, copy.getLoadType()); assertEquals(true, copy.getVisitRemoves()); assertEquals(true, copy.getVisitInconsistentBuckets()); assertEquals(9, copy.getTraceLevel()); assertEquals("foo.txt", copy.getResumeFileName()); assertEquals(params.getResumeToken(), copy.getResumeToken()); // instance compare assertEquals("mars_rover", copy.getRemoteDataHandler()); assertEquals(params.getControlHandler(), copy.getControlHandler()); assertEquals(555, copy.getMaxFirstPassHits()); assertEquals(777, copy.getMaxTotalHits()); assertEquals(true, copy.getDynamicallyIncreaseMaxBucketsPerVisitor()); assertEquals(2.5f, copy.getDynamicMaxBucketsIncreaseFactor(), 0.0001); assertEquals(true, copy.skipBucketsOnFatalErrors()); // Test local data handler copy VisitorParameters params2 = new VisitorParameters(""); params2.setLocalDataHandler(new SimpleVisitorDocumentQueue()); VisitorParameters copy2 = new VisitorParameters(params2); assertEquals(params2.getLocalDataHandler(), copy2.getLocalDataHandler()); // instance compare } @Test public void testToString() { VisitorParameters params = createVisitorParameters(); assertEquals( "VisitorParameters(\n" + " Document selection: id.user==5678\n" + " Bucket space: narnia\n" + " Visitor library: CoolVisitor\n" + " Max pending: 111\n" + " Timeout (ms): 1337\n" + " Time period: 9001 - 10001\n" + " Visiting remove entries\n" + " Visiting inconsistent buckets\n" + " Visitor library parameters:\n" + " groovy : dudes\n" + " ninja : turtles\n" + " Field set: [all]\n" + " Route: extraterrestrial/highway\n" + " Weight: 1.0\n" + " Max firstpass hits: 555\n" + " Max total hits: 777\n" + " Max buckets: 55\n" + " Priority: HIGHEST\n" + " Dynamically increasing max buckets per visitor\n" + " Increase factor: 2.5\n" + ")", params.toString()); } }
apache-2.0
sladecek/jmaze
src/test/java/com/github/sladecek/maze/jmaze/makers/moebius/Moebius3dMapperTest.java
4115
package com.github.sladecek.maze.jmaze.makers.moebius; import com.github.sladecek.maze.jmaze.geometry.Point2DDbl; import com.github.sladecek.maze.jmaze.geometry.Point2DInt; import com.github.sladecek.maze.jmaze.geometry.Point3D; import com.github.sladecek.maze.jmaze.print3d.maze3dmodel.Altitude; import com.github.sladecek.maze.jmaze.print3d.maze3dmodel.ILocalCoordinateSystem; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Tests the <code>{@link Moebius3dMapper}</code> class. */ public class Moebius3dMapperTest { @Before public void setup() { mapper = new Moebius3dMapper(4,16, 10.0, 2.2); } @Test public void isAltitudeVisible() throws Exception { assertFalse(mapper.isAltitudeVisible(Altitude.FRAME)); assertFalse(mapper.isAltitudeVisible(Altitude.GROUND)); assertTrue(mapper.isAltitudeVisible(Altitude.FLOOR)); assertTrue(mapper.isAltitudeVisible(Altitude.CEILING)); } @Test public void testConstruction() throws Exception { assertEquals(16*(10+2.2), mapper.getLength(), epsilon); assertEquals(12.2, mapper.getCellStep(), epsilon); } @Test public void imageComputation_0() throws Exception { Point3D img = mapper.computeImagePoint(new Point2DDbl(0, 2), Altitude.GROUND); assertEquals(0, img.getX(), epsilon); assertEquals(0, img.getY(), epsilon); assertEquals(0, img.getZ(), epsilon); } @Test public void imageComputationAcrossDown() throws Exception { Point3D img = mapper.computeImagePoint(new Point2DDbl(0, 1), Altitude.GROUND); assertEquals(0, img.getX(), epsilon); assertEquals(-12.2, img.getY(), epsilon); assertEquals(0, img.getZ(), epsilon); } @Test public void imageComputationAcrossUp() throws Exception { Point3D img = mapper.computeImagePoint(new Point2DDbl(0, 4), Altitude.GROUND); assertEquals(0, img.getX(), epsilon); assertEquals(2*12.2, img.getY(), epsilon); assertEquals(0, img.getZ(), epsilon); } @Test public void imageComputationAlongDown() throws Exception { Point3D img = mapper.computeImagePoint(new Point2DDbl(-1, 2), Altitude.GROUND); assertEquals(-12.2, img.getX(), epsilon); assertEquals(0, img.getY(), epsilon); assertEquals(0, img.getZ(), epsilon); } @Test public void imageComputationAlongUp() throws Exception { Point3D img = mapper.computeImagePoint(new Point2DDbl(1, 2), Altitude.GROUND); assertEquals(12.2, img.getX(), epsilon); assertEquals(0, img.getY(), epsilon); assertEquals(0, img.getZ(), epsilon); } @Test public void imageComputationCeiling() throws Exception { Point3D img = mapper.computeImagePoint(new Point2DDbl(0, 2), Altitude.CEILING); assertEquals(0, img.getX(), epsilon); assertEquals(0, img.getY(), epsilon); assertEquals(2, mapper.mapAltitude(Altitude.CEILING), epsilon); assertEquals(2, img.getZ(), epsilon); } @Test public void map() throws Exception { // mapping is tested in MoebiusStripGeometryTest; image computation tested above // here only function composition is tested Point2DDbl p = new Point2DDbl(-1.222, 1.333); Point3D img = mapper.computeImagePoint(p, Altitude.FLOOR); Point3D r1 = mapper.getGeometry().transform(img); Point3D r2 = mapper.map(p, Altitude.FLOOR); assertEquals(r1.getX(), r2.getX(), epsilon); assertEquals(r1.getY(), r2.getY(), epsilon); assertEquals(r1.getZ(), r2.getZ(), epsilon); } @Test public void createLocalCoordinateSystem() throws Exception { ILocalCoordinateSystem lcs=mapper.createLocalCoordinateSystem(new Point2DInt(0,2)); Point2DDbl lp = lcs.transformToLocal(new Point2DDbl(15,3)); assertEquals(-1.0, lp.getX(), epsilon); assertEquals(3, lp.getY(), epsilon); } private static final double epsilon = 0.0000001; private Moebius3dMapper mapper; }
apache-2.0
ctripcorp/x-pipe
core/src/main/java/com/ctrip/xpipe/netty/commands/NettyClientFactory.java
4285
package com.ctrip.xpipe.netty.commands; import com.ctrip.xpipe.api.endpoint.Endpoint; import com.ctrip.xpipe.api.proxy.ProxyEnabled; import com.ctrip.xpipe.lifecycle.AbstractStartStoppable; import com.ctrip.xpipe.netty.NettySimpleMessageHandler; import com.ctrip.xpipe.utils.ThreadUtils; import com.ctrip.xpipe.utils.XpipeThreadFactory; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.logging.LoggingHandler; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @author wenchao.meng * * Jul 1, 2016 */ public class NettyClientFactory extends AbstractStartStoppable implements PooledObjectFactory<NettyClient> { private static final AtomicInteger poolId = new AtomicInteger(); private NioEventLoopGroup eventLoopGroup; private final boolean useGlobalResources; private Bootstrap b = new Bootstrap(); private int connectTimeoutMilli = 5000; private static Logger logger = LoggerFactory.getLogger(NettyClientFactory.class); private Endpoint endpoint; public NettyClientFactory(Endpoint endpoint) { this(endpoint, true); } public NettyClientFactory(Endpoint endpoint, boolean useGlobalResources) { this.endpoint = endpoint; this.useGlobalResources = useGlobalResources; } @Override protected void doStart() throws Exception { if (useGlobalResources) { eventLoopGroup = NettyClientResource.getGlobalEventLoopGroup(); } else { eventLoopGroup = new NioEventLoopGroup(1, XpipeThreadFactory.create("NettyClientFactory-" + poolId.incrementAndGet())); } b.group(eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler()); p.addLast(new NettySimpleMessageHandler()); p.addLast(new NettyClientHandler()); } }); } @Override protected void doStop() { if (!useGlobalResources) eventLoopGroup.shutdownGracefully(); } @Override public PooledObject<NettyClient> makeObject() throws Exception { ChannelFuture f = b.connect(endpoint.getHost(), endpoint.getPort()); f.get(connectTimeoutMilli, TimeUnit.MILLISECONDS); Channel channel = f.channel(); sendProxyProtocolIfNeeded(channel); logger.info("[makeObject]{}", channel); NettyClient nettyClient = new DefaultNettyClient(channel); channel.attr(NettyClientHandler.KEY_CLIENT).set(nettyClient); return new DefaultPooledObject<NettyClient>(nettyClient); } private void sendProxyProtocolIfNeeded(Channel channel) { if(endpoint instanceof ProxyEnabled) { channel.writeAndFlush(((ProxyEnabled) endpoint).getProxyProtocol()); } } @Override public void destroyObject(PooledObject<NettyClient> p) throws Exception { logger.info("[destroyObject]{}, {}", endpoint, p.getObject()); p.getObject().channel().close(); } @Override public boolean validateObject(PooledObject<NettyClient> p) { return p.getObject().channel().isActive(); } @Override public void activateObject(PooledObject<NettyClient> p) throws Exception { } @Override public void passivateObject(PooledObject<NettyClient> p) throws Exception { } @Override public String toString() { return String.format("T:%s", endpoint.toString()); } private static final class NettyClientResource { private static NioEventLoopGroup globalEventLoopGroup; public static NioEventLoopGroup getGlobalEventLoopGroup() { if (null != globalEventLoopGroup) { return globalEventLoopGroup; } synchronized(NettyClientResource.class) { if (null == globalEventLoopGroup) { globalEventLoopGroup = new NioEventLoopGroup(ThreadUtils.bestEffortThreadNums(), XpipeThreadFactory.create("NettyClientFactory-Global")); } } return globalEventLoopGroup; } } }
apache-2.0
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/segmentation/parser/value/NullValueNode.java
554
package com.wonderpush.sdk.segmentation.parser.value; import com.wonderpush.sdk.segmentation.parser.ASTValueNode; import com.wonderpush.sdk.segmentation.parser.ASTValueVisitor; import com.wonderpush.sdk.segmentation.parser.ParsingContext; import org.json.JSONObject; public class NullValueNode extends ASTValueNode<Object> { public NullValueNode(ParsingContext context) { super(context, JSONObject.NULL); } @Override public <U> U accept(ASTValueVisitor<U> visitor) { return visitor.visitNullValueNode(this); } }
apache-2.0
leafclick/intellij-community
java/idea-ui/src/com/intellij/jarRepository/RepositoryLibraryRootsComponentDescriptor.java
4112
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.jarRepository; import com.intellij.ide.IdeBundle; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.ui.AttachRootButtonDescriptor; import com.intellij.openapi.roots.libraries.ui.LibraryRootsComponentDescriptor; import com.intellij.openapi.roots.libraries.ui.OrderRootTypePresentation; import com.intellij.openapi.roots.libraries.ui.RootDetector; import com.intellij.openapi.roots.ui.configuration.libraryEditor.DefaultLibraryRootsComponentDescriptor; import com.intellij.openapi.roots.ui.configuration.libraryEditor.LibraryEditor; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties; import java.io.File; import java.util.Collections; import java.util.List; class RepositoryLibraryRootsComponentDescriptor extends LibraryRootsComponentDescriptor { private static final Logger LOG = Logger.getInstance(RepositoryLibraryRootsComponentDescriptor.class); @Nullable @Override public OrderRootTypePresentation getRootTypePresentation(@NotNull OrderRootType type) { return DefaultLibraryRootsComponentDescriptor.getDefaultPresentation(type); } @NotNull @Override public List<? extends RootDetector> getRootDetectors() { return Collections.singletonList(DefaultLibraryRootsComponentDescriptor.createAnnotationsRootDetector()); } @NotNull @Override public FileChooserDescriptor createAttachFilesChooserDescriptor(@Nullable String libraryName) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(); descriptor.setTitle(IdeBundle.message("attach.external.annotations")); descriptor.setDescription(IdeBundle.message("select.directory.where.external.annotations.are.located")); return descriptor; } @Override public String getAttachFilesActionName() { return "Attach Annotations..."; } @NotNull @Override public List<? extends AttachRootButtonDescriptor> createAttachButtons() { return Collections.emptyList(); } @NotNull @Override public RootRemovalHandler createRootRemovalHandler() { return new RootRemovalHandler() { @Override public void onRootRemoved(@NotNull String rootUrl, @NotNull OrderRootType rootType, @NotNull LibraryEditor libraryEditor) { if (rootType == OrderRootType.CLASSES) { String coordinates = getMavenCoordinates(rootUrl); if (coordinates != null) { RepositoryLibraryProperties properties = (RepositoryLibraryProperties)libraryEditor.getProperties(); properties.setExcludedDependencies(ContainerUtil.append(properties.getExcludedDependencies(), coordinates)); } else { LOG.warn("Cannot determine Maven coordinates for removed library root " + rootUrl); } } } }; } @Nullable private static String getMavenCoordinates(@NotNull String jarUrl) { File jarFile = new File(PathUtil.getLocalPath(VfsUtilCore.urlToPath(jarUrl))); if (jarFile.getParentFile() == null) return null; File artifactDir = jarFile.getParentFile().getParentFile(); if (artifactDir == null) return null; File localRepoRoot = JarRepositoryManager.getLocalRepositoryPath(); if (!FileUtil.isAncestor(localRepoRoot, artifactDir, true)) return null; String relativePath = FileUtil.getRelativePath(localRepoRoot, artifactDir.getParentFile()); if (relativePath == null) return null; return relativePath.replace(File.separatorChar, '.') + ":" + artifactDir.getName(); } }
apache-2.0
sarah-happy/happy-archive
archive/src/main/java/org/yi/happy/archive/commandLine/CommandParseException.java
1279
package org.yi.happy.archive.commandLine; /** * Represents an error in command line parsing. Because the command line is * typically provided by the user this is a checked exception, an error expected * to need to be checked for in normal operation. */ public class CommandParseException extends Exception { /** * */ private static final long serialVersionUID = 8090206810674900265L; /** * Constructs a new exception without a detail message. */ public CommandParseException() { super(); } /** * Constructs a new exception with a detail message and cause. * * @param message * the detail message. * @param cause * the cause. */ public CommandParseException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with a detail message. * * @param message * the detail message. */ public CommandParseException(String message) { super(message); } /** * Constructs a new exception with a cause. * * @param cause * the cause. */ public CommandParseException(Throwable cause) { super(cause); } }
apache-2.0
thedsv/java_pft
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactAddressTests.java
660
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class ContactAddressTests extends TestBase { @Test public void testContactAddress() { app.goTo().homePage(); ContactData contact = app.contact().all().iterator().next(); ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact); assertThat(contact.getAddress(), equalTo(contactInfoFromEditForm.getAddress())); } }
apache-2.0
jaowl/practice-java
patterns/src/ru/fedinskiy/Main.java
716
package ru.fedinskiy; import ru.fedinskiy.chain.BabkiRumors; import ru.fedinskiy.chain.OfficeRumors; import ru.fedinskiy.chain.TeshaRumors; import ru.fedinskiy.keeper.CareTaker; import ru.fedinskiy.keeper.Level; import ru.fedinskiy.strategy.BankStrategy; import ru.fedinskiy.strategy.Context; import ru.fedinskiy.strategy.MailStrategy; import ru.fedinskiy.strategy.WebMoneyStrategy; /** * Created by fedinskiy on 08.03.17. */ public class Main { public static void main(String[] args) { Context context=new Context(); context.addStrateguy(new BankStrategy().withPercent(13)); context.addStrateguy(new MailStrategy()); context.addStrateguy(new WebMoneyStrategy()); context.sendMoney(1000_000); } }
apache-2.0
dahlstrom-g/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/GroovyFileType.java
2408
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.util.containers.ContainerUtil; import icons.JetgroovyIcons; import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; public final class GroovyFileType extends LanguageFileType { /** * @deprecated implement {@link GroovyEnabledFileType} in the FileType, * or extend {@link LanguageFileType} and specify {@link GroovyLanguage#INSTANCE} */ @SuppressWarnings("DeprecatedIsStillUsed") @ScheduledForRemoval(inVersion = "2021.1") @Deprecated public static final List<FileType> GROOVY_FILE_TYPES = new ArrayList<>(); public static final @NotNull GroovyFileType GROOVY_FILE_TYPE = new GroovyFileType(); @NonNls public static final String DEFAULT_EXTENSION = "groovy"; private GroovyFileType() { super(GroovyLanguage.INSTANCE); } @Override @NotNull @NonNls public String getName() { return "Groovy"; } @Override @NotNull public String getDescription() { return GroovyBundle.message("language.groovy"); } @Override @NotNull @NonNls public String getDefaultExtension() { return DEFAULT_EXTENSION; } @Override public Icon getIcon() { return JetgroovyIcons.Groovy.Groovy_16x16; } @Override public boolean isJVMDebuggingSupported() { return true; } public static @NotNull FileType @NotNull [] getGroovyEnabledFileTypes() { Collection<FileType> result = new LinkedHashSet<>(GROOVY_FILE_TYPES); result.addAll(ContainerUtil.filter( FileTypeManager.getInstance().getRegisteredFileTypes(), GroovyFileType::isGroovyEnabledFileType )); return result.toArray(FileType.EMPTY_ARRAY); } private static boolean isGroovyEnabledFileType(FileType ft) { return ft instanceof GroovyEnabledFileType || ft instanceof LanguageFileType && ((LanguageFileType)ft).getLanguage() == GroovyLanguage.INSTANCE; } }
apache-2.0
SimbaService/Simba
server/gateway/src/com/necla/simba/server/gateway/client/ClientState.java
13317
/******************************************************************************* * Copyright 2015 Dorian Perkins, Younghwan Go, Nitin Agrawal, Akshat Aranya * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.necla.simba.server.gateway.client; import io.netty.channel.Channel; import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.ByteString; import com.necla.simba.client.SeqNumManager; import com.necla.simba.protocol.Client.BitmapNotify; import com.necla.simba.protocol.Client.ClientMessage; import com.necla.simba.protocol.Client.ClientMultiMessage; import com.necla.simba.protocol.Client.Notify; import com.necla.simba.protocol.Server.ClientSubscription; import com.necla.simba.protocol.Server.RequestClientSubscriptions; import com.necla.simba.protocol.Server.RestoreClientSubscriptions; import com.necla.simba.protocol.Server.SaveClientSubscription; import com.necla.simba.protocol.Server.SimbaMessage; import com.necla.simba.server.gateway.client.ClientState; import com.necla.simba.server.gateway.Main; import com.necla.simba.server.gateway.client.notification.NotificationManager; import com.necla.simba.server.gateway.client.notification.NotificationTask; import com.necla.simba.server.gateway.client.sync.SyncScheduler; import com.necla.simba.server.gateway.server.backend.BackendConnector; import com.necla.simba.server.gateway.subscription.Subscription; import com.necla.simba.server.gateway.subscription.SubscriptionManager; import com.necla.simba.util.ConsistentHash; public class ClientState { private static final Logger LOG = LoggerFactory .getLogger(ClientState.class); private String deviceId; private String token; private Channel pc; private BitSet bitmap; public boolean isConnected; Long lastConnect; public ArrayList<Subscription> subscriptions; private SyncScheduler scheduler; private SubscriptionManager subscriptionManager; private BackendConnector client; private HashMap<Integer, String> transactions = new HashMap<Integer, String>(); private final ReadWriteLock subscriptionReadWriteLock = new ReentrantReadWriteLock(); public final Lock subscriptionRead = subscriptionReadWriteLock.readLock(); final Lock subscriptionWrite = subscriptionReadWriteLock.writeLock(); private final ReadWriteLock bitmapReadWriteLock = new ReentrantReadWriteLock(); public final Lock bitmapRead = bitmapReadWriteLock.readLock(); public final Lock bitmapWrite = bitmapReadWriteLock.writeLock(); private ConsistentHash hasher; private NotificationManager nom; private SeqNumManager sequencer; private static boolean BITMAP_NOTIFICATION = Boolean .parseBoolean(Main.properties.getProperty("bitmap.notification")); private static int NO_DELAY = 0; public ClientState(String id, Channel pc, String token, SubscriptionManager subscriptionManager, NotificationManager nom, BackendConnector client, SeqNumManager seq) { // public ClientState(String id, PacketChannel pc, String token, boolean // restore){ bitmap = new BitSet(); this.deviceId = id; this.token = token; this.pc = pc; this.nom = nom; this.subscriptions = new ArrayList<Subscription>(); this.isConnected = true; this.subscriptionManager = subscriptionManager; this.client = client; this.scheduler = new SyncScheduler(this); this.sequencer = seq; hasher = new ConsistentHash(); // if(restore){ // requestClientSubscriptions(); // } } public void addTransaction(int transId, String table) { transactions.put(transId, table); } public String getTransaction(int transId) { return transactions.get(transId); } public SyncScheduler getSyncScheduler() { if (this.scheduler == null) this.scheduler = new SyncScheduler(this); return this.scheduler; } public void processNotification(String table) { LOG.debug("Setting bit for table: " + table + "(" + subscriptions.indexOf(new Subscription(table, 0, 0)) + ")"); // LOG.debug("Current # of subscriptions:" + subscriptions.size()); // LOG.debug("Subscription list:"); // for(String n : subscriptions){ // LOG.debug(n); // } // LOG.debug("Index of " + table + ": " ); Subscription sub; int index; subscriptionRead.lock(); try { // find index of matching subscription index = subscriptions.indexOf(new Subscription(table, 0, 0)); // get subscription sub = subscriptions.get(index); } finally { subscriptionRead.unlock(); } // check for zero period special case // table is using STRONG consistency if (sub.period == 0) { // send notification immediately if (this.isConnected) { // create new temporary bitmap with the bit set for this table BitSet notification = new BitSet(); subscriptionRead.lock(); try { notification.set(subscriptions.indexOf(new Subscription( table, 0, 0))); } finally { subscriptionRead.unlock(); } // build message ClientMessage.Builder m = ClientMessage.newBuilder(); if (BITMAP_NOTIFICATION) { BitmapNotify n = BitmapNotify .newBuilder() .setBitmap( ByteString.copyFrom(NotificationTask .bitsToByteArray(notification))) .build(); m.setType(ClientMessage.Type.BITMAP_NOTIFY) .setBitmapNotify(n).setSeq(this.sequencer.getSeq()) .build(); System.out.println("Queueing BITMAP_NOTIFY for " + this.deviceId); } else { Notify n = Notify.newBuilder().build(); m.setType(ClientMessage.Type.NOTIFY).setNotify(n) .setSeq(this.sequencer.getSeq()).build(); System.out.println("Queueing SINGLE BIT NOTIFY for " + this.deviceId); } // schedule message this.scheduler.schedule(m.build(), NO_DELAY); } else { LOG.debug("Client is not connected"); } } else { // normal case bitmapWrite.lock(); try { // set bit for this table subscription in bitmap bitmap.set(index); } finally { bitmapWrite.unlock(); } } } public void addSubscription(String app, String table, int period, int dt, boolean restore, int version, Integer seq) { boolean isNewSubscription = true; // add to subscription list String tablename = app + "." + table; LOG.debug("Add subscription for table=" + tablename + " at period " + period); Subscription sub = new Subscription(tablename, period, dt); subscriptionWrite.lock(); try { for (int i = 0; i < subscriptions.size(); i++) { if (sub.equals(subscriptions.get(i))) { isNewSubscription = false; LOG.debug("found existing subscription"); subscriptions.set(i, sub); } } if (isNewSubscription) { subscriptions.add(sub); } } finally { subscriptionWrite.unlock(); } LOG.debug("Add subscription for SEQ=" + seq); if (period != 0) { if (!isNewSubscription) { // remove the existing timer task before adding the new one nom.removeTask(tablename, this); } // add subscription to bucket for this timer. nom.addTask(sub, this); } // this will overwrite an existing subscription for a given <client, // table> combo subscriptionManager.subscribe(this, app, table, version, seq, token); // save new subscription to cassandra // only if not a restore operation if (!restore) { saveClientSubscription(sub); } // send ACK to client // TODO: add control message for subscription addition } public void removeSubscription(String app, String table) { // remove subscription from table subscriptionWrite.lock(); try { subscriptions.remove(app + "." + table); } finally { subscriptionWrite.unlock(); } // Remove subscription to subscription manager subscriptionManager.unsubscribe(this, app, table); // send ACK to client // TODO: add control message for subscription removal } public void restoreClientState(RestoreClientSubscriptions rcs) { LOG.debug("Restoring subscriptions for client " + deviceId); for (ClientSubscription sub : rcs.getSubList()) { LOG.debug("Restoring subscription for " + sub.getTable() + ", p=" + sub.getPeriod() + ", DT=" + sub.getDt()); String[] words = sub.getTable().split("\\."); addSubscription(words[0], words[1], sub.getPeriod(), sub.getDt(), true, -1, null); // TODO: which version number does client have on a restore? } } public void requestClientSubscriptions() { LOG.debug("Requesting subscriptions for client " + deviceId); RequestClientSubscriptions.Builder rcs = RequestClientSubscriptions .newBuilder(); rcs.setClientId(deviceId); SimbaMessage msg = SimbaMessage.newBuilder() .setType(SimbaMessage.Type.REQUEST_CLIENT_SUBSCRIPTIONS) .setRequestClientSubscriptions(rcs.build()).build(); try { client.sendTo(this.deviceId, msg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void saveClientSubscription(Subscription sub) { // save a single subscription SaveClientSubscription.Builder scs = SaveClientSubscription .newBuilder(); scs.setClientId(deviceId); ClientSubscription.Builder s = ClientSubscription.newBuilder(); s.setTable(sub.table).setPeriod(sub.period).setDt(sub.delayTolerance) .build(); scs.setSub(s); SimbaMessage msg = SimbaMessage.newBuilder() .setType(SimbaMessage.Type.SAVE_CLIENT_SUBSCRIPTION) .setSaveClientSubscription(scs.build()).build(); try { client.sendTo(this.deviceId, msg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // String server = client.hasher.getNode(this.deviceId); // SocketChannel socket = client.serverSockets.get(server); // try { // client.send(msg.toByteArray(), socket); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } // private void saveAllClientSubscriptions(){ // SaveClientSubscriptions.Builder scs = // SaveClientSubscriptions.newBuilder(); // scs.setClientId(deviceId); // // ClientSubscription.Builder s = ClientSubscription.newBuilder(); // for (Subscription sub : this.subscriptions){ // s.setTable(sub.table) // .setPeriod(sub.period) // .setDt(sub.delayTolerance) // .build(); // // scs.addSub(s); // } // // SimbaMessage msg = SimbaMessage.newBuilder() // .setType(SimbaMessage.Type.SAVE_CLIENT_SUBSCRIPTIONS) // .setSaveClientSubscriptions(scs.build()) // .build(); // // String server = Main.client.hasher.getNode(this.deviceId); // SocketChannel socket = Main.client.serverSockets.get(server); // try { // Main.client.send(msg.toByteArray(), socket); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } public void sendMessage(ClientMessage m) throws IOException { LOG.debug("Sending msg type=" + m.getType() + " to " + this.pc); // sendMessageInternal(this.pc, // ClientMultiMessage.newBuilder().addElementMessages(m).build()); // StatsCollector.write(System.currentTimeMillis() + " seq " + // m.getSeq() + " type " + m.getType().name() +" out"); sendMessageInternal(this.pc, ClientMultiMessage.newBuilder() .addMessages(m).build()); } public static void sendMessage(Channel pc, ClientMessage m) throws IOException { LOG.debug("Sending msg type=" + m.getType() + " to " + pc); // sendMessageInternal(pc, // ClientMultiMessage.newBuilder().addElementMessages(m).build()); sendMessageInternal(pc, ClientMultiMessage.newBuilder().addMessages(m) .build()); } /* * combine the two into one: provider a function that they both can call to * compress */ private static void sendMessageInternal(Channel pc, ClientMultiMessage m) throws IOException { pc.writeAndFlush(m); } public void sendMultiMessage(ClientMultiMessage mm) throws IOException { sendMessageInternal(this.pc, mm); } public void update(String token, Channel pc) { this.token = token; this.pc = pc; } public void updatePacketChannel(Channel pc) { this.pc = pc; } public void updateToken(String token) { this.token = token; } public String getToken() { return this.token; } public Channel getSocket() { return this.pc; } public BitSet getBitmap() { bitmapRead.lock(); try { return this.bitmap; } finally { bitmapRead.unlock(); } } public void clearBitmap() { bitmapWrite.lock(); try { this.bitmap.clear(); } finally { bitmapWrite.unlock(); } } public String getDeviceId() { return this.deviceId; } }
apache-2.0
matthew-compton/NerdRoll
NerdRoll-MortarAndFlow/app/src/main/java/com/bignerdranch/android/nerdroll/view/DieView.java
1453
package com.bignerdranch.android.nerdroll.view; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; import com.bignerdranch.android.nerdroll.R; import com.bignerdranch.android.nerdroll.screen.DieScreen; import java.util.Random; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import mortar.Mortar; public class DieView extends LinearLayout { @Inject DieScreen.Presenter presenter; @InjectView(R.id.view_die_random) public TextView mRandomTextView; @InjectView(R.id.view_die_value) public TextView mValueTextView; public DieView(Context context, AttributeSet attrs) { super(context, attrs); Mortar.inject(context, this); } @Override protected void onFinishInflate() { super.onFinishInflate(); ButterKnife.inject(this); presenter.takeView(this); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); presenter.dropView(this); } public void updateRandomText(CharSequence text) { mRandomTextView.setText(text); } public void updateValueText(CharSequence text) { mValueTextView.setText(text); } public void roll(int sides) { Random r = new Random(); int num = r.nextInt(sides) + 1; updateValueText(Integer.toString(num)); } }
apache-2.0
mifos/1.4.x
acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/MifosPage.java
3584
/* * Copyright (c) 2005-2009 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.test.acceptance.framework; import org.mifos.test.acceptance.framework.login.LoginPage; import com.thoughtworks.selenium.Selenium; /** * Responsible for common actions that are executable by a logged-in user. * */ public class MifosPage extends AbstractPage { public MifosPage() { super(); } public MifosPage(Selenium selenium) { super(selenium); } public LoginPage logout() { selenium.open("loginAction.do?method=logout"); waitForPageToLoad(); return new LoginPage(selenium); } protected void typeTextIfNotEmpty(String locator, String value) { if (!isEmpty(value)) { selenium.type(locator, value); } } protected void selectIfNotEmpty(String locator, String value) { if (!isEmpty(value)) { selenium.select(locator, "label=" + value); } } /** * This is the equivalent of seleftIfNotEmpty for integers. * @see #selectIfNotEmpty(String, String) * @param locator * @param value */ protected void selectValueIfNotZero(String locator, int value) { if (value != 0) { selenium.select(locator, "value=" + value); } } protected void checkIfNotEmpty(String locator, String value) { if (!isEmpty(value)) { selenium.check(locator); } } protected void selectAndWaitIfNotEmpty(String locator, String value) { if (!isEmpty(value)) { selenium.select(locator, "label=" + value); waitForPageToLoad(); } } private boolean isEmpty(String value) { boolean empty = true; if (value!= null && !value.isEmpty()) { empty = false; } return empty; } @SuppressWarnings("PMD.OnlyOneReturn") public boolean isErrorMessageDisplayed() { // the error message span id is always <page_id>.error.message so // using a wildcard we check to see if that span has text or not. // wildcards are not supported in id tags so we use a css selector. String errorMessage = selenium.getText("css=span[id*=\"error.message\"]"); if (isEmpty(errorMessage)) { return false; } return true; } @SuppressWarnings("PMD.OnlyOneReturn") public boolean isCollectionSheetAccountErrorMessageDisplayed(final String mainStr, final String detailStr) { String bodyText = selenium.getBodyText(); Integer positionOfMainStrInBodyText = bodyText.indexOf(mainStr); if (positionOfMainStrInBodyText == -1) { return false; } if ((detailStr != null) && (bodyText.indexOf(detailStr) <= positionOfMainStrInBodyText)) { return false; } return true; } }
apache-2.0
tyazid/Exoplayer_VLC
Studio_Project/ExoPlayerLib/src/main/java/com/google/android/exoplayer/raw/RawBufferedSource.java
3602
package com.google.android.exoplayer.raw; import android.util.Log; import com.google.android.exoplayer.upstream.DataSource; import com.google.android.exoplayer.upstream.DataSpec; import java.io.IOException; /** * Created by ataldir on 26/02/2015. */ public class RawBufferedSource implements DataSource { private final String TAG = "RawBufferedSource"; private final int BUFFER_LENGTH = 16*1024; private final int SAMPLE_LENGTH = 4*1024; private DataSource dataSource; private byte[] buffer; private int read_pos = 0; private int write_pos = 0; public RawBufferedSource(DataSource dataSource) { this.dataSource = dataSource; } /* * * Implements DataSource * */ @Override public long open(DataSpec dataSpec) throws IOException { Log.d(TAG, "open(): --> <--"); long result = this.dataSource.open(dataSpec); this.read_pos = 0; this.write_pos = 0; this.buffer = new byte[BUFFER_LENGTH]; return result; } @Override public void close() throws IOException { this.buffer = null; this.dataSource.close(); } @Override public int read(byte[] buffer, int offset, int readLength) throws IOException { //return this.dataSource.read(buffer, offset, readLength); //Log.d(TAG, "read(): want size="+readLength+", on available="+getContentLength()); while( getContentLength()< readLength ) { int read = internalReadFromSource(); //Log.d(TAG, "read(): ... read="+read+", getContentLength()="+getContentLength()); } if( write_pos >= read_pos ) { if( write_pos-read_pos >= readLength ) { System.arraycopy(this.buffer, read_pos, buffer, 0, readLength); read_pos += readLength; return readLength; } else { Log.d(TAG, "Not enough data to read from"); return 0; } } else { int len = Math.min(BUFFER_LENGTH-read_pos, readLength); System.arraycopy(this.buffer, read_pos, buffer, 0, len); read_pos += len; if( read_pos >= BUFFER_LENGTH ) read_pos = 0; if( len < readLength ) { int rest = readLength-len; System.arraycopy(this.buffer, read_pos, buffer, len, rest); read_pos += rest; } return readLength; } } /* * * private methods * */ private long getContentLength() { long content_length = 0; if( write_pos >= read_pos ) content_length = write_pos-read_pos; else content_length = BUFFER_LENGTH-read_pos + write_pos; return content_length; } private int internalReadFromSource() throws IOException { int read = 0; if( write_pos >= read_pos ) { int len = Math.min(BUFFER_LENGTH-write_pos, SAMPLE_LENGTH); read = this.dataSource.read(this.buffer, write_pos, len); write_pos += read; if( write_pos >= BUFFER_LENGTH ) write_pos = 0; } else if( write_pos < read_pos-1 ) { int len = Math.min(read_pos-write_pos-1, SAMPLE_LENGTH); read = this.dataSource.read(this.buffer, write_pos, len); write_pos += read; } return read; } }
apache-2.0
yangjunlin-const/WhileTrueCoding
JavaBase/src/main/java/com/yjl/javabase/thinkinjava/exceptions/ExtraFeatures.java
1944
package com.yjl.javabase.thinkinjava.exceptions;//: exceptions/ExtraFeatures.java // Further embellishment of exception classes. import static com.yjl.javabase.thinkinjava.net.mindview.util.Print.*; class MyException2 extends Exception { private int x; public MyException2() {} public MyException2(String msg) { super(msg); } public MyException2(String msg, int x) { super(msg); this.x = x; } public int val() { return x; } public String getMessage() { return "Detail Message: "+ x + " "+ super.getMessage(); } } public class ExtraFeatures { public static void f() throws MyException2 { print("Throwing MyException2 from f()"); throw new MyException2(); } public static void g() throws MyException2 { print("Throwing MyException2 from g()"); throw new MyException2("Originated in g()"); } public static void h() throws MyException2 { print("Throwing MyException2 from h()"); throw new MyException2("Originated in h()", 47); } public static void main(String[] args) { try { f(); } catch(MyException2 e) { e.printStackTrace(System.out); } try { g(); } catch(MyException2 e) { e.printStackTrace(System.out); } try { h(); } catch(MyException2 e) { e.printStackTrace(System.out); System.out.println("e.val() = " + e.val()); } } } /* Output: Throwing MyException2 from f() MyException2: Detail Message: 0 null at ExtraFeatures.f(ExtraFeatures.java:22) at ExtraFeatures.main(ExtraFeatures.java:34) Throwing MyException2 from g() MyException2: Detail Message: 0 Originated in g() at ExtraFeatures.g(ExtraFeatures.java:26) at ExtraFeatures.main(ExtraFeatures.java:39) Throwing MyException2 from h() MyException2: Detail Message: 47 Originated in h() at ExtraFeatures.h(ExtraFeatures.java:30) at ExtraFeatures.main(ExtraFeatures.java:44) e.val() = 47 *///:~
apache-2.0
vincent-pp/AmazingWeather
src/com/amazingweather/app/activity/WeatherActivity.java
4760
package com.amazingweather.app.activity; import com.amazingweather.app.R; import com.amazingweather.app.service.AutoUpdateService; import com.amazingweather.app.util.HttpCallbackListener; import com.amazingweather.app.util.HttpUtil; import com.amazingweather.app.util.Utility; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; private TextView cityNameText; private TextView publishText; private TextView weatherDespText; private TextView templowText; private TextView temphighText; private TextView currentDateText; private Button switchCity; private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); weatherInfoLayout=(LinearLayout) findViewById(R.id.weather_info_layout); cityNameText=(TextView) findViewById(R.id.city_name); publishText=(TextView) findViewById(R.id.publish_text); weatherDespText=(TextView) findViewById(R.id.weather_desp); templowText=(TextView) findViewById(R.id.templow); temphighText=(TextView) findViewById(R.id.temphigh); currentDateText=(TextView) findViewById(R.id.current_date); switchCity=(Button) findViewById(R.id.switch_city); refreshWeather=(Button) findViewById(R.id.refresh_weather); switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); String countyCode=getIntent().getStringExtra("county_code"); if(!TextUtils.isEmpty(countyCode)){ publishText.setText("ͬ²½ÖÐ..."); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); } else{ showWeather(); } } @Override public void onClick(View v){ switch(v.getId()){ case R.id.switch_city: Intent intent=new Intent(this,ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.refresh_weather: publishText.setText("ͬ²½ÖÐ..."); SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); String weatherCode=prefs.getString("weather_code", ""); if(!TextUtils.isEmpty(weatherCode)){ queryWeatherInfo(weatherCode); } break; default: break; } } private void queryWeatherCode(String countyCode){ String address="http://www.weather.com.cn/data/list3/city"+countyCode+".xml"; queryFromServer(address,"countyCode"); } private void queryWeatherInfo(String weatherCode){ String address="http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html"; queryFromServer(address,"weatherCode"); } private void queryFromServer(final String address,final String type){ HttpUtil.sendHttpRequest(address,new HttpCallbackListener(){ @Override public void onFinish(String response){ boolean result=false; if("countyCode".equals(type)){ if(!TextUtils.isEmpty(response)){ String[] array=response.split("\\|"); if(array!=null&&array.length==2){ String weatherCode=array[1]; queryWeatherInfo(weatherCode); } } } else if("weatherCode".equals(type)){ Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable(){ @Override public void run(){ showWeather(); } }); } } @Override public void onError(Exception e){ e.printStackTrace(); runOnUiThread(new Runnable(){ @Override public void run(){ publishText.setText("ͬ²½Ê§°Ü"); } }); } }); } private void showWeather(){ SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText(prefs.getString("city_name", "")); templowText.setText(prefs.getString("temp_low", "")); temphighText.setText(prefs.getString("temp_high", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText(prefs.getString("publish_time", "")+"·¢²¼"); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); Intent serviceIntent=new Intent(this,AutoUpdateService.class); startService(serviceIntent); } }
apache-2.0
marciojrtorres/tecnicas-praticas-codificacao
interface-fluente/src/fluente/HtmlForm.java
1980
package fluente; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class HtmlForm { private String id; private String action; private String method; private List<String> classes = new ArrayList<String>(); private List<HtmlElement> elementos = new ArrayList<HtmlElement>(); public HtmlForm setId(String id) { this.id = id; return this; } public HtmlForm setAction(String action) { this.action = action; return this; } public HtmlForm setMethod(String method) { this.method = method; return this; } public HtmlForm addClass(String clazz) { this.classes.add(clazz); return this; } public HtmlForm addElement(HtmlElement element) { this.elementos.add(element); return this; } public String getId() { return id; } public String getAction() { return action; } public String getMethod() { return method; } public List<String> getClasses() { return classes; } public List<HtmlElement> getElementos() { return elementos; } public String getHtmlString() { StringBuilder builder = new StringBuilder(); builder.append("<form"); if (id != null) builder.append(" id=\"").append(id).append("\""); if (action != null) builder.append(" action=\"").append(action).append("\""); if (method != null) builder.append(" method=\"").append(method).append("\""); if (classes.size() > 0) { builder.append(" class=\""); Iterator<String> it = classes.iterator(); while (it.hasNext()) { builder.append(it.next()); if (it.hasNext()) builder.append(" "); } builder.append("\""); } builder.append(">"); if (elementos.size() > 0) { for (HtmlElement e : elementos) { builder.append("\n"); builder.append(" ").append(e.getHtmlString()); } } return builder.append("\n</form>").toString(); } }
apache-2.0
AndyZhu1991/elegance-interpolator
library/src/main/java/andy/zhu/android/eleganceinterpolator/OppositeInterpolator.java
512
package andy.zhu.android.eleganceinterpolator; import android.view.animation.Interpolator; /** * Created by Andy.Zhu on 2017/4/25. */ public class OppositeInterpolator implements Interpolator { private Interpolator mOriginInterpolator; public OppositeInterpolator(Interpolator originInterpolator) { mOriginInterpolator = originInterpolator; } @Override public float getInterpolation(float input) { return 1 - (mOriginInterpolator.getInterpolation(1 - input)); } }
apache-2.0
gilsonrochasilva/musd
musd-web/src/main/java/br/com/musd/dao/ModeloMigracaoDAO.java
217
package br.com.musd.dao; import br.com.musd.administrativo.ModeloMigracao; import br.com.musd.dao.common.DAO; /** * Created by gilson on 23/06/15. */ public class ModeloMigracaoDAO extends DAO<ModeloMigracao> { }
apache-2.0
michael-rapp/AndroidMaterialDialog
library/src/main/java/de/mrapp/android/dialog/model/HeaderDialog.java
943
/* * Copyright 2014 - 2020 Michael Rapp * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package de.mrapp.android.dialog.model; /** * Defines the interface a dialog, which is designed according to Android 5's Material design * guidelines even on pre-Lollipop devices and may contain a header, must implement. * * @author Michael Rapp * @since 3.2.0 */ public interface HeaderDialog extends MaterialDialog, HeaderDialogDecorator { }
apache-2.0
mpmunasinghe/product-ei
integration/mediation-tests/tests-service/src/test/java/org/wso2/carbon/esb/proxyservice/test/transformerProxy/InvalidXSLTTestCase.java
3736
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.esb.proxyservice.test.transformerProxy; import org.apache.axis2.AxisFault; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceExceptionException; import org.wso2.esb.integration.common.clients.registry.ResourceAdminServiceClient; import org.wso2.esb.integration.common.utils.ESBIntegrationTest; import javax.activation.DataHandler; import javax.xml.xpath.XPathExpressionException; import java.net.URL; import java.rmi.RemoteException; public class InvalidXSLTTestCase extends ESBIntegrationTest { @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { super.init(); uploadResourcesToConfigRegistry(); loadESBConfigurationFromClasspath( "/artifacts/ESB/proxyconfig/proxy/transformerProxy/invalid_xslt_test.xml"); } @Test(groups = "wso2.esb", description = "- Transformer proxy" + "- Invalid XSLT referred, AxisFault Expected", expectedExceptions = AxisFault.class) public void testTransformerProxy() throws Exception { axis2Client.sendCustomQuoteRequest(getProxyServiceURLHttp("StockQuoteProxy"), null, "WSO2"); } @AfterClass(alwaysRun = true) public void destroy() throws Exception { clearUploadedResource(); super.cleanup(); } private void uploadResourcesToConfigRegistry() throws Exception { ResourceAdminServiceClient resourceAdminServiceStub = new ResourceAdminServiceClient(context.getContextUrls().getBackEndUrl(), getSessionCookie()); resourceAdminServiceStub.deleteResource("/_system/config/script_xslt"); resourceAdminServiceStub.addCollection("/_system/config/", "script_xslt", "", "Contains test xslt files"); resourceAdminServiceStub.addResource( "/_system/config/script_xslt/invalid_transform.xslt", "application/xml", "xslt files", new DataHandler(new URL("file:///" + getESBResourceLocation() + "/proxyconfig/proxy/utils/invalid_transform.xslt"))); Thread.sleep(1000); resourceAdminServiceStub.addResource( "/_system/config/script_xslt/transform_back.xslt", "application/xml", "xslt files", new DataHandler(new URL("file:///" + getESBResourceLocation() + "/mediatorconfig/xslt/transform_back.xslt"))); Thread.sleep(1000); } private void clearUploadedResource() throws InterruptedException, ResourceAdminServiceExceptionException, RemoteException, XPathExpressionException { ResourceAdminServiceClient resourceAdminServiceStub = new ResourceAdminServiceClient(context.getContextUrls().getBackEndUrl(), getSessionCookie()); resourceAdminServiceStub.deleteResource("/_system/config/script_xslt"); } }
apache-2.0
skunkiferous/Util
shared/src/main/java/com/blockwithme/util/shared/converters/ByteConverterBase.java
2237
/* * Copyright (C) 2014 Sebastien Diot. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blockwithme.util.shared.converters; import com.blockwithme.util.shared.Any; import com.blockwithme.util.shared.AnyArray; /** * Base class for ByteConverter. * * @author monster */ public abstract class ByteConverterBase<CONTEXT, E> extends ConverterBase<CONTEXT, E> implements ByteConverter<CONTEXT, E> { /** * Creates a ByteConverterBase. * * @param theType * @param theBits */ protected ByteConverterBase(final Class<E> theType) { super(theType, DEFAULT_BITS); } /** * Creates a ByteConverterBase. * * @param theType * @param theBits */ protected ByteConverterBase(final Class<E> theType, final int theBits) { super(theType, theBits); } /** {@inheritDoc} */ @Override public final void objectToAny(final CONTEXT context, final E obj, final Any any) { any.setByte(fromObject(context, obj)); } /** {@inheritDoc} */ @Override public final E anyToObject(final CONTEXT context, final Any any) { return toObject(context, any.getByte()); } /** {@inheritDoc} */ @Override public final void objectToAny(final CONTEXT context, final E obj, final AnyArray anyArray, final int index) { anyArray.setByte(index, fromObject(context, obj)); } /** {@inheritDoc} */ @Override public final E anyToObject(final CONTEXT context, final AnyArray anyArray, final int index) { return toObject(context, anyArray.getByte(index)); } }
apache-2.0
fabric8io/kubernetes-client
crd-generator/api/src/main/java/io/fabric8/crd/generator/v1beta1/decorator/CustomResourceDefinitionDecorator.java
1052
/** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.crd.generator.v1beta1.decorator; import io.fabric8.crd.generator.decorator.NamedResourceDecorator; import io.fabric8.kubernetes.api.model.ObjectMeta; public class CustomResourceDefinitionDecorator<T> extends NamedResourceDecorator<T> { public CustomResourceDefinitionDecorator(String name) { super("CustomResourceDefinition", name); } @Override public void andThenVisit(T item, ObjectMeta resourceMeta) { } }
apache-2.0
AlexeiVainshtein/jenkins-artifactory-plugin
src/main/java/org/jfrog/hudson/generic/ArtifactoryGenericConfigurator.java
17872
package org.jfrog.hudson.generic; import com.google.common.collect.Lists; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.matrix.MatrixConfiguration; import hudson.model.*; import hudson.tasks.BuildWrapper; import hudson.util.ListBoxModel; import hudson.util.XStream2; import jenkins.model.Jenkins; import org.apache.commons.lang.StringUtils; import org.jfrog.build.api.Artifact; import org.jfrog.build.api.Dependency; import org.jfrog.build.api.dependency.BuildDependency; import org.jfrog.build.client.ProxyConfiguration; import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient; import org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryDependenciesClient; import org.jfrog.hudson.*; import org.jfrog.hudson.action.ActionableHelper; import org.jfrog.hudson.release.promotion.UnifiedPromoteBuildAction; import org.jfrog.hudson.util.*; import org.jfrog.hudson.util.converters.DeployerResolverOverriderConverter; import org.jfrog.hudson.util.plugins.MultiConfigurationUtils; import org.jfrog.hudson.util.plugins.PluginsUtils; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.bind.JavaScriptMethod; import org.kohsuke.stapler.interceptor.RequirePOST; import java.io.IOException; import java.util.Collection; import java.util.List; /** * Freestyle Generic configurator * * @author Shay Yaakov */ public class ArtifactoryGenericConfigurator extends BuildWrapper implements DeployerOverrider, ResolverOverrider, BuildInfoAwareConfigurator, MultiConfigurationAware { private final ServerDetails deployerDetails; private final ServerDetails resolverDetails; private final CredentialsConfig deployerCredentialsConfig; private final CredentialsConfig resolverCredentialsConfig; private final Boolean useSpecs; private final SpecConfiguration uploadSpec; private final SpecConfiguration downloadSpec; private final String deployPattern; private final String resolvePattern; private final String deploymentProperties; private final boolean deployBuildInfo; /** * Include environment variables in the generated build info */ private final boolean includeEnvVars; private final IncludesExcludes envVarsPatterns; private final boolean discardOldBuilds; private final boolean discardBuildArtifacts; private final boolean asyncBuildRetention; private transient List<Dependency> publishedDependencies; private transient List<BuildDependency> buildDependencies; private String artifactoryCombinationFilter; private boolean multiConfProject; private String customBuildName; private boolean overrideBuildName; /** * @deprecated: Use org.jfrog.hudson.generic.ArtifactoryGenericConfigurator#getDeployerCredentials()() */ @Deprecated private Credentials overridingDeployerCredentials; /** * @deprecated: Use org.jfrog.hudson.generic.ArtifactoryGenericConfigurator#getResolverCredentialsId()() */ @Deprecated private Credentials overridingResolverCredentials; /** * @deprecated: The following deprecated variables have corresponding converters to the variables replacing them */ @Deprecated private final ServerDetails details = null; @Deprecated private final String matrixParams = null; @DataBoundConstructor public ArtifactoryGenericConfigurator(ServerDetails details, ServerDetails deployerDetails, ServerDetails resolverDetails, CredentialsConfig deployerCredentialsConfig, CredentialsConfig resolverCredentialsConfig, String deployPattern, String resolvePattern, String matrixParams, String deploymentProperties, boolean useSpecs, SpecConfiguration uploadSpec, SpecConfiguration downloadSpec, boolean deployBuildInfo, boolean includeEnvVars, IncludesExcludes envVarsPatterns, boolean discardOldBuilds, boolean discardBuildArtifacts, boolean asyncBuildRetention, boolean multiConfProject, String artifactoryCombinationFilter, String customBuildName, boolean overrideBuildName) { this.deployerDetails = deployerDetails; this.resolverDetails = resolverDetails; this.deployerCredentialsConfig = deployerCredentialsConfig; this.resolverCredentialsConfig = resolverCredentialsConfig; this.deployPattern = deployPattern; this.resolvePattern = resolvePattern; this.useSpecs = useSpecs; this.uploadSpec = uploadSpec; this.downloadSpec = downloadSpec; this.deploymentProperties = deploymentProperties; this.deployBuildInfo = deployBuildInfo; this.includeEnvVars = includeEnvVars; this.envVarsPatterns = envVarsPatterns; this.discardOldBuilds = discardOldBuilds; this.discardBuildArtifacts = discardBuildArtifacts; this.asyncBuildRetention = asyncBuildRetention; this.multiConfProject = multiConfProject; this.artifactoryCombinationFilter = artifactoryCombinationFilter; this.customBuildName = customBuildName; this.overrideBuildName = overrideBuildName; } public String getArtifactoryName() { return getDeployerDetails() != null ? getDeployerDetails().artifactoryName : null; } public String getArtifactoryResolverName() { return resolverDetails != null ? resolverDetails.artifactoryName : null; } public String getArtifactoryUrl() { ArtifactoryServer server = getArtifactoryServer(); return server != null ? server.getUrl() : null; } public boolean isOverridingDefaultDeployer() { return deployerCredentialsConfig != null && deployerCredentialsConfig.isCredentialsProvided(); } public String getRepositoryKey() { return getDeployerDetails().getDeployReleaseRepository().getRepoKey(); } public String getDefaultPromotionTargetRepository() { //Not implemented return null; } public ServerDetails getDeployerDetails() { return deployerDetails; } public ServerDetails getResolverDetails() { return resolverDetails; } public Credentials getOverridingDeployerCredentials() { return overridingDeployerCredentials; } public CredentialsConfig getDeployerCredentialsConfig() { return deployerCredentialsConfig; } public String getDeployPattern() { return deployPattern; } public String getResolvePattern() { return resolvePattern; } public boolean isUseSpecs() { // useSpecs may be null in Jenkins Job DSL return useSpecs == null || useSpecs; } public SpecConfiguration getUploadSpec() { return uploadSpec; } public SpecConfiguration getDownloadSpec() { return downloadSpec; } public String getDeploymentProperties() { return deploymentProperties; } public boolean isDeployBuildInfo() { return deployBuildInfo; } public boolean isIncludeEnvVars() { return includeEnvVars; } public IncludesExcludes getEnvVarsPatterns() { return envVarsPatterns; } public boolean isDiscardOldBuilds() { return discardOldBuilds; } public boolean isDiscardBuildArtifacts() { return discardBuildArtifacts; } public boolean isAsyncBuildRetention() { return asyncBuildRetention; } public boolean isEnableIssueTrackerIntegration() { return false; } public boolean isAggregateBuildIssues() { return false; } public String getAggregationBuildStatus() { return null; } public String getArtifactoryCombinationFilter() { return artifactoryCombinationFilter; } public boolean isMultiConfProject() { return multiConfProject; } public String getCustomBuildName() { return customBuildName; } public boolean isOverrideBuildName() { return overrideBuildName; } public ArtifactoryServer getArtifactoryServer() { return RepositoriesUtils.getArtifactoryServer(getArtifactoryName(), getDescriptor().getArtifactoryServers()); } public ArtifactoryServer getArtifactoryResolverServer() { String serverId = getArtifactoryResolverName(); if (serverId == null) { throw new RuntimeException("Artifactory server for dependencies resolution is null"); } ArtifactoryServer server = RepositoriesUtils.getArtifactoryServer(serverId, getDescriptor().getArtifactoryServers()); if (server == null) { throw new RuntimeException(String.format("The job is configured to use an Artifactory server with ID '%s' for dependencies resolution. This server however does not exist", serverId)); } return server; } public List<Repository> getReleaseRepositoryList() { if (getDeployerDetails().getDeploySnapshotRepository() == null) { return Lists.newArrayList(); } return RepositoriesUtils.collectRepositories(getDeployerDetails().getDeploySnapshotRepository().getKeyFromSelect()); } @Override public Collection<? extends Action> getProjectActions(AbstractProject project) { if (isOverrideBuildName()) { return ActionableHelper.getArtifactoryProjectAction(getArtifactoryName(), project, getCustomBuildName()); } else { return ActionableHelper.getArtifactoryProjectAction(getArtifactoryName(), project); } } @Override public Environment setUp(final AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { listener.getLogger().println("Jenkins Artifactory Plugin version: " + ActionableHelper.getArtifactoryPluginVersion()); RepositoriesUtils.validateServerConfig(build, listener, getArtifactoryServer(), getArtifactoryUrl()); if (StringUtils.isBlank(getArtifactoryName())) { return super.setUp(build, launcher, listener); } // Resolve process: ArtifactoryServer resolverServer = getArtifactoryResolverServer(); CredentialsConfig preferredResolver = CredentialManager.getPreferredResolver(ArtifactoryGenericConfigurator.this, resolverServer); String username = preferredResolver.provideUsername(build.getProject()); String password = preferredResolver.providePassword(build.getProject()); ProxyConfiguration proxyConfiguration = null; hudson.ProxyConfiguration proxy = Jenkins.getInstance().proxy; if (proxy != null && !resolverServer.isBypassProxy()) { proxyConfiguration = ArtifactoryServer.createProxyConfiguration(proxy); } ArtifactoryDependenciesClient dependenciesClient = null; try { if (isUseSpecs()) { String spec = SpecUtils.getSpecStringFromSpecConf(downloadSpec, build.getEnvironment(listener), build.getExecutor().getCurrentWorkspace(), listener.getLogger()); FilePath workspace = build.getExecutor().getCurrentWorkspace(); publishedDependencies = workspace.act(new FilesResolverCallable( new JenkinsBuildInfoLog(listener), username, password, resolverServer.getUrl(), spec, proxyConfiguration)); } else { dependenciesClient = resolverServer.createArtifactoryDependenciesClient(username, password, proxyConfiguration, listener); GenericArtifactsResolver artifactsResolver = new GenericArtifactsResolver(build, listener, dependenciesClient); publishedDependencies = artifactsResolver.retrievePublishedDependencies(resolvePattern); buildDependencies = artifactsResolver.retrieveBuildDependencies(resolvePattern); } return createEnvironmentOnSuccessfulSetup(); } catch (Exception e) { e.printStackTrace(listener.error(e.getMessage())); build.setResult(Result.FAILURE); } finally { if (dependenciesClient != null) { dependenciesClient.close(); } } return null; } private Environment createEnvironmentOnSuccessfulSetup() { return new Environment() { @Override public boolean tearDown(AbstractBuild build, BuildListener listener) { Result result = build.getResult(); if (result != null && result.isWorseThan(Result.SUCCESS)) { return true; // build failed. Don't publish } ArtifactoryServer server = getArtifactoryServer(); CredentialsConfig preferredDeployer = CredentialManager.getPreferredDeployer(ArtifactoryGenericConfigurator.this, server); ArtifactoryBuildInfoClient client = server.createArtifactoryClient(preferredDeployer.provideUsername(build.getProject()), preferredDeployer.providePassword(build.getProject()), ArtifactoryServer.createProxyConfiguration(Jenkins.getInstance().proxy)); server.setLog(listener, client); try { boolean isFiltered = false; if (isMultiConfProject(build)) { if (multiConfProject && StringUtils.isBlank(getArtifactoryCombinationFilter())) { String error = "The field \"Combination Matches\" is empty, but is defined as mandatory!"; listener.getLogger().println(error); build.setResult(Result.FAILURE); throw new IllegalArgumentException(error); } isFiltered = MultiConfigurationUtils.isfiltrated(build, getArtifactoryCombinationFilter()); } if (!isFiltered) { GenericArtifactsDeployer artifactsDeployer = new GenericArtifactsDeployer(build, ArtifactoryGenericConfigurator.this, listener, preferredDeployer); artifactsDeployer.deploy(); List<Artifact> deployedArtifacts = artifactsDeployer.getDeployedArtifacts(); if (deployBuildInfo) { new GenericBuildInfoDeployer(ArtifactoryGenericConfigurator.this, client, build, listener, deployedArtifacts, buildDependencies, publishedDependencies).deploy(); String buildName = BuildUniqueIdentifierHelper.getBuildNameConsiderOverride(ArtifactoryGenericConfigurator.this, build); // add the result action (prefer always the same index) build.getActions().add(0, new BuildInfoResultAction(getArtifactoryUrl(), build, buildName)); build.getActions().add(new UnifiedPromoteBuildAction(build, ArtifactoryGenericConfigurator.this)); } } return true; } catch (Exception e) { e.printStackTrace(listener.error(e.getMessage())); } finally { client.close(); } // failed build.setResult(Result.FAILURE); return true; } }; } private boolean isMultiConfProject(AbstractBuild build) { return (build.getProject().getClass().equals(MatrixConfiguration.class)); } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } public boolean isOverridingDefaultResolver() { return resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided(); } public Credentials getOverridingResolverCredentials() { return overridingResolverCredentials; } public CredentialsConfig getResolverCredentialsConfig() { return resolverCredentialsConfig; } @Extension(optional = true) public static class DescriptorImpl extends AbstractBuildWrapperDescriptor { private static final String DISPLAY_NAME = "Generic-Artifactory Integration"; private static final String CONFIG_PREFIX = "generic"; public DescriptorImpl() { super(ArtifactoryGenericConfigurator.class, DISPLAY_NAME, CONFIG_PREFIX); } @SuppressWarnings("unused") @JavaScriptMethod public RefreshServerResponse refreshFromArtifactory(String url, String credentialsId, String username, String password, boolean overrideCredentials) { return super.refreshDeployersFromArtifactory(url, credentialsId, username, password, overrideCredentials, false); } @SuppressWarnings("unused") @RequirePOST public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project) { return PluginsUtils.fillPluginCredentials(project); } } /** * Page Converter */ public static final class ConverterImpl extends DeployerResolverOverriderConverter { public ConverterImpl(XStream2 xstream) { super(xstream); } } }
apache-2.0
Enterprise-Content-Management/documentum-rest-client-java
src/main/java/com/emc/documentum/rest/client/sample/model/json/JsonLifecycle.java
6692
/* * Copyright (c) 2018. Open Text Corporation. All Rights Reserved. */ package com.emc.documentum.rest.client.sample.model.json; import java.util.Date; import java.util.List; import java.util.Objects; import com.emc.documentum.rest.client.sample.client.util.Equals; import com.emc.documentum.rest.client.sample.model.Lifecycle; import com.emc.documentum.rest.client.sample.model.json.JsonLifecycleState.JsonModule; import com.emc.documentum.rest.client.sample.model.json.JsonLifecycleState.JsonProcedure; import com.fasterxml.jackson.annotation.JsonProperty; public class JsonLifecycle extends JsonInlineLinkableBase implements Lifecycle { private String id; private String name; private String title; private String subject; private List<String> keywords; private String owner; private Date created; private Date modified; @JsonProperty("implementation-type") private String implementationType; @JsonProperty("version-labels") private List<String> versionLabels; @JsonProperty("alias-sets") private List<String> aliasSets; @JsonProperty("type-inclusions") private List<JsonTypeInclusion> typeInclusions; @JsonProperty("states") private List<JsonLifecycleState> states; @JsonProperty("user-validation-service") private JsonModule userValidationService; @JsonProperty("app-validation") private JsonProcedure appValidation; private String status; private String statusMessage; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public List<String> getKeywords() { return keywords; } public void setKeywords(List<String> keywords) { this.keywords = keywords; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getModified() { return modified; } public void setModified(Date modified) { this.modified = modified; } public String getImplementationType() { return implementationType; } public void setImplementationType(String implementationType) { this.implementationType = implementationType; } public List<String> getVersionLabels() { return versionLabels; } public void setVersionLabels(List<String> versionLabels) { this.versionLabels = versionLabels; } public List<String> getAliasSets() { return aliasSets; } public void setAliasSets(List<String> aliasSets) { this.aliasSets = aliasSets; } @SuppressWarnings({ "rawtypes", "unchecked" }) public List<TypeInclusion> getTypeInclusions() { return (List)typeInclusions; } public void setTypeInclusions(List<JsonTypeInclusion> typeInclusions) { this.typeInclusions = typeInclusions; } @SuppressWarnings({ "rawtypes", "unchecked" }) public List<LifecycleState> getStates() { return (List)states; } public void setStates(List<JsonLifecycleState> states) { this.states = states; } public Module getUserValidationService() { return userValidationService; } public void setUserValidationService(JsonModule userValidationService) { this.userValidationService = userValidationService; } public Procedure getAppValidation() { return appValidation; } public void setAppValidation(JsonProcedure appValidation) { this.appValidation = appValidation; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getStatusMessage() { return statusMessage; } public void setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; } @Override public boolean equals(Object obj) { JsonLifecycle that = (JsonLifecycle) obj; return Equals.equal(id, that.id) && Equals.equal(name, that.name) && Equals.equal(title, that.title) && Equals.equal(subject, that.subject) && Equals.equal(keywords, that.keywords) && Equals.equal(owner, that.owner) && Equals.equal(created, that.created) && Equals.equal(modified, that.modified) && Equals.equal(implementationType, that.implementationType) && Equals.equal(versionLabels, that.versionLabels) && Equals.equal(aliasSets, that.aliasSets) && Equals.equal(typeInclusions, that.typeInclusions) && Equals.equal(states, that.states) && Equals.equal(userValidationService, that.userValidationService) && Equals.equal(appValidation, that.appValidation) && Equals.equal(status, that.status) && Equals.equal(statusMessage, that.statusMessage) && super.equals(obj); } @Override public int hashCode() { return Objects.hash(id, name, states, getSrc(), getContentType()); } public static class JsonTypeInclusion implements TypeInclusion { private String type; @JsonProperty("include-subtypes") private boolean includeSubtypes; public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isIncludeSubtypes() { return includeSubtypes; } public void setIncludeSubtypes(boolean includeSubtypes) { this.includeSubtypes = includeSubtypes; } @Override public boolean equals(Object obj) { JsonTypeInclusion that = (JsonTypeInclusion) obj; return Equals.equal(type, that.type) && Equals.equal(includeSubtypes, that.includeSubtypes); } @Override public int hashCode() { return Objects.hash(type, includeSubtypes); } } }
apache-2.0
Qi4j/qi4j-core
runtime/src/main/java/org/qi4j/runtime/bootstrap/ValueAssemblyImpl.java
11637
/* * Copyright (c) 2007, Rickard Öberg. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.qi4j.runtime.bootstrap; import org.qi4j.api.association.GenericAssociationInfo; import org.qi4j.api.association.ManyAssociation; import org.qi4j.api.common.*; import org.qi4j.api.constraint.Constraint; import org.qi4j.api.association.Association; import org.qi4j.api.property.GenericPropertyInfo; import org.qi4j.api.property.Immutable; import org.qi4j.api.property.Property; import org.qi4j.api.util.Annotations; import org.qi4j.api.util.Classes; import org.qi4j.api.value.ValueComposite; import org.qi4j.bootstrap.StateDeclarations; import org.qi4j.bootstrap.ValueAssembly; import org.qi4j.functional.Iterables; import org.qi4j.runtime.composite.CompositeMethodsModel; import org.qi4j.runtime.composite.MixinsModel; import org.qi4j.runtime.composite.ValueConstraintsInstance; import org.qi4j.runtime.composite.ValueConstraintsModel; import org.qi4j.runtime.association.AssociationModel; import org.qi4j.runtime.association.AssociationsModel; import org.qi4j.runtime.association.ManyAssociationModel; import org.qi4j.runtime.association.ManyAssociationsModel; import org.qi4j.runtime.property.PropertiesModel; import org.qi4j.runtime.property.PropertyModel; import org.qi4j.runtime.value.ValueModel; import org.qi4j.runtime.value.ValueStateModel; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Member; import java.util.ArrayList; import java.util.List; import static org.qi4j.api.util.Annotations.isType; import static org.qi4j.functional.Iterables.filter; import static org.qi4j.functional.Iterables.first; /** * Declaration of a ValueComposite. */ public final class ValueAssemblyImpl extends CompositeAssemblyImpl implements ValueAssembly { List<Class<?>> concerns = new ArrayList<Class<?>>(); List<Class<?>> sideEffects = new ArrayList<Class<?>>(); List<Class<?>> mixins = new ArrayList<Class<?>>(); List<Class<?>> types = new ArrayList<Class<?>>(); MetaInfo metaInfo = new MetaInfo(); Visibility visibility = Visibility.module; protected AssociationsModel associationsModel; protected ManyAssociationsModel manyAssociationsModel; public ValueAssemblyImpl( Class<?> compositeType ) { this.compositeType = compositeType; } @Override public Class<?> type() { return compositeType; } ValueModel newValueModel( StateDeclarations stateDeclarations, AssemblyHelper helper ) { this.stateDeclarations = stateDeclarations; try { this.helper = helper; metaInfo = new MetaInfo( metaInfo ).withAnnotations( compositeType ); addAnnotationsMetaInfo( compositeType, metaInfo ); immutable = metaInfo.get( Immutable.class ) != null; propertiesModel = new PropertiesModel(); associationsModel = new AssociationsModel( ); manyAssociationsModel = new ManyAssociationsModel(); stateModel = new ValueStateModel( propertiesModel, associationsModel, manyAssociationsModel ); mixinsModel = new MixinsModel(); compositeMethodsModel = new CompositeMethodsModel( mixinsModel ); // The composite must always implement ValueComposite, as a marker interface if (!ValueComposite.class.isAssignableFrom(compositeType)) { types.add( ValueComposite.class ); } // Implement composite methods Iterable<Class<? extends Constraint<?, ?>>> constraintClasses = constraintDeclarations( compositeType ); Iterable<Class<?>> concernClasses = Iterables.<Class<?>, Iterable<Class<?>>>flatten( concerns, concernDeclarations( compositeType ) ); Iterable<Class<?>> sideEffectClasses = Iterables.<Class<?>, Iterable<Class<?>>>flatten( sideEffects, sideEffectDeclarations( compositeType ) ); Iterable<Class<?>> mixinClasses = Iterables.<Class<?>, Iterable<Class<?>>>flatten( mixins, mixinDeclarations( compositeType ) ); implementMixinType( compositeType, constraintClasses, concernClasses, sideEffectClasses, mixinClasses); // Implement additional type methods for( Class<?> type : types ) { Iterable<Class<? extends Constraint<?, ?>>> typeConstraintClasses = Iterables.<Class<? extends Constraint<?, ?>>, Iterable<Class<? extends Constraint<?, ?>>>>flatten( constraintClasses, constraintDeclarations( type ) ); Iterable<Class<?>> typeConcernClasses = Iterables.<Class<?>, Iterable<Class<?>>>flatten( concernClasses, concernDeclarations( type ) ); Iterable<Class<?>> typeSideEffectClasses = Iterables.<Class<?>, Iterable<Class<?>>>flatten( sideEffectClasses, sideEffectDeclarations( type ) ); Iterable<Class<?>> typeMixinClasses = Iterables.<Class<?>, Iterable<Class<?>>>flatten( mixinClasses, mixinDeclarations( type ) ); implementMixinType( type, typeConstraintClasses, typeConcernClasses, typeSideEffectClasses, typeMixinClasses); } // Add state from methods and fields addState(constraintClasses); ValueModel valueModel = new ValueModel( compositeType, Iterables.prepend(compositeType, types), visibility, metaInfo, mixinsModel, (ValueStateModel) stateModel, compositeMethodsModel ); return valueModel; } catch( Exception e ) { throw new InvalidApplicationException( "Could not register " + compositeType.getName(), e ); } } protected void addStateFor( AccessibleObject accessor, Iterable<Class<? extends Constraint<?, ?>>> constraintClasses ) { String stateName = QualifiedName.fromAccessor( accessor ).name(); if (registeredStateNames.contains( stateName )) return; // Skip already registered names Class<?> accessorType = Classes.RAW_CLASS.map( Classes.TYPE_OF.map( accessor ) ); if( Property.class.isAssignableFrom( accessorType ) ) { propertiesModel.addProperty( newPropertyModel( accessor, constraintClasses ) ); registeredStateNames.add( stateName ); } else if( Association.class.isAssignableFrom( accessorType ) ) { associationsModel.addAssociation( newAssociationModel( accessor, constraintClasses ) ); registeredStateNames.add( stateName ); } else if( ManyAssociation.class.isAssignableFrom( accessorType ) ) { manyAssociationsModel.addManyAssociation( newManyAssociationModel( accessor, constraintClasses ) ); registeredStateNames.add( stateName ); } } @Override protected PropertyModel newPropertyModel( AccessibleObject accessor, Iterable<Class<? extends Constraint<?, ?>>> constraintClasses ) { Iterable<Annotation> annotations = Annotations.getAccessorAndTypeAnnotations( accessor ); boolean optional = first( filter( isType( Optional.class ), annotations ) ) != null; ValueConstraintsModel valueConstraintsModel = constraintsFor( annotations, GenericPropertyInfo.getPropertyType( accessor ), ((Member) accessor) .getName(), optional, constraintClasses, accessor ); ValueConstraintsInstance valueConstraintsInstance = null; if( valueConstraintsModel.isConstrained() ) { valueConstraintsInstance = valueConstraintsModel.newInstance(); } MetaInfo metaInfo = stateDeclarations.getMetaInfo( accessor ); boolean useDefaults = metaInfo.get( UseDefaults.class ) != null || stateDeclarations.isUseDefaults( accessor ); Object initialValue = stateDeclarations.getInitialValue( accessor ); return new PropertyModel( accessor, true, useDefaults, valueConstraintsInstance, metaInfo, initialValue ); } public AssociationModel newAssociationModel( AccessibleObject accessor, Iterable<Class<? extends Constraint<?, ?>>> constraintClasses ) { Iterable<Annotation> annotations = Annotations.getAccessorAndTypeAnnotations( accessor ); boolean optional = first( filter( isType( Optional.class ), annotations ) ) != null; // Constraints for Association references ValueConstraintsModel valueConstraintsModel = constraintsFor( annotations, GenericAssociationInfo .getAssociationType( accessor ), ((Member) accessor).getName(), optional, constraintClasses, accessor ); ValueConstraintsInstance valueConstraintsInstance = null; if( valueConstraintsModel.isConstrained() ) { valueConstraintsInstance = valueConstraintsModel.newInstance(); } // Constraints for the Association itself valueConstraintsModel = constraintsFor( annotations, Association.class, ((Member) accessor).getName(), optional, constraintClasses, accessor ); ValueConstraintsInstance associationValueConstraintsInstance = null; if( valueConstraintsModel.isConstrained() ) { associationValueConstraintsInstance = valueConstraintsModel.newInstance(); } MetaInfo metaInfo = stateDeclarations.getMetaInfo( accessor ); AssociationModel associationModel = new AssociationModel( accessor, valueConstraintsInstance, associationValueConstraintsInstance, metaInfo ); return associationModel; } public ManyAssociationModel newManyAssociationModel( AccessibleObject accessor, Iterable<Class<? extends Constraint<?, ?>>> constraintClasses ) { Iterable<Annotation> annotations = Annotations.getAccessorAndTypeAnnotations( accessor ); boolean optional = first( filter( isType( Optional.class ), annotations ) ) != null; // Constraints for entities in ManyAssociation ValueConstraintsModel valueConstraintsModel = constraintsFor( annotations, GenericAssociationInfo .getAssociationType( accessor ), ((Member) accessor).getName(), optional, constraintClasses, accessor ); ValueConstraintsInstance valueConstraintsInstance = null; if( valueConstraintsModel.isConstrained() ) { valueConstraintsInstance = valueConstraintsModel.newInstance(); } // Constraints for the ManyAssociation itself valueConstraintsModel = constraintsFor( annotations, ManyAssociation.class, ((Member) accessor).getName(), optional, constraintClasses, accessor ); ValueConstraintsInstance manyValueConstraintsInstance = null; if( valueConstraintsModel.isConstrained() ) { manyValueConstraintsInstance = valueConstraintsModel.newInstance(); } MetaInfo metaInfo = stateDeclarations.getMetaInfo( accessor ); ManyAssociationModel associationModel = new ManyAssociationModel( accessor, valueConstraintsInstance, manyValueConstraintsInstance, metaInfo ); return associationModel; } }
apache-2.0
fabric8io/kubernetes-client
kubernetes-model-generator/kubernetes-model-core/src/generated/java/io/fabric8/kubernetes/api/model/TopologySpreadConstraint.java
3489
package io.fabric8.kubernetes.api.model; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.sundr.builder.annotations.Buildable; import lombok.EqualsAndHashCode; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; @JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "apiVersion", "kind", "metadata", "labelSelector", "maxSkew", "topologyKey", "whenUnsatisfiable" }) @ToString @EqualsAndHashCode @Setter @Accessors(prefix = { "_", "" }) @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = true, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder") public class TopologySpreadConstraint implements KubernetesResource { @JsonProperty("labelSelector") private LabelSelector labelSelector; @JsonProperty("maxSkew") private Integer maxSkew; @JsonProperty("topologyKey") private String topologyKey; @JsonProperty("whenUnsatisfiable") private String whenUnsatisfiable; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public TopologySpreadConstraint() { } /** * * @param whenUnsatisfiable * @param maxSkew * @param labelSelector * @param topologyKey */ public TopologySpreadConstraint(LabelSelector labelSelector, Integer maxSkew, String topologyKey, String whenUnsatisfiable) { super(); this.labelSelector = labelSelector; this.maxSkew = maxSkew; this.topologyKey = topologyKey; this.whenUnsatisfiable = whenUnsatisfiable; } @JsonProperty("labelSelector") public LabelSelector getLabelSelector() { return labelSelector; } @JsonProperty("labelSelector") public void setLabelSelector(LabelSelector labelSelector) { this.labelSelector = labelSelector; } @JsonProperty("maxSkew") public Integer getMaxSkew() { return maxSkew; } @JsonProperty("maxSkew") public void setMaxSkew(Integer maxSkew) { this.maxSkew = maxSkew; } @JsonProperty("topologyKey") public String getTopologyKey() { return topologyKey; } @JsonProperty("topologyKey") public void setTopologyKey(String topologyKey) { this.topologyKey = topologyKey; } @JsonProperty("whenUnsatisfiable") public String getWhenUnsatisfiable() { return whenUnsatisfiable; } @JsonProperty("whenUnsatisfiable") public void setWhenUnsatisfiable(String whenUnsatisfiable) { this.whenUnsatisfiable = whenUnsatisfiable; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
apache-2.0
MOCraftStudio/Nagato
src/org/mocraft/Nagato/Levy.java
537
package org.mocraft.Nagato; public class Levy { private String name; private int time; private int[] reward = new int[4]; public Levy(String n, int t, int[] r) { this.name = n; this.time = t; for(int i = 0; i < 4; ++i) { this.reward[i] = r[i]; } } public String getName() { return name; } public int getTime() { return time; } public int getOil() { return reward[0]; } public int getBullet() { return reward[1]; } public int getSteel() { return reward[2]; } public int getAluminum() { return reward[3]; } }
apache-2.0
oneliang/common-util
src/main/java/com/oneliang/util/logging/ComplexLogger.java
866
package com.oneliang.util.logging; import java.util.List; public class ComplexLogger extends AbstractLogger { private List<AbstractLogger> loggerList = null; /** * constructor * * @param level * @param loggerList */ public ComplexLogger(Level level, List<AbstractLogger> loggerList) { super(level); this.loggerList = loggerList; } /** * log */ protected void log(Level level, String message, Throwable throwable) { if (this.loggerList != null) { for (AbstractLogger logger : this.loggerList) { logger.log(level, message, throwable); } } } public void destroy() { if (this.loggerList != null) { for (Logger logger : this.loggerList) { logger.destroy(); } } } }
apache-2.0
mpmunasinghe/product-ei
integration/mediation-tests/tests-sample/src/test/java/org/wso2/carbon/esb/samples/test/proxy/Sample286TestCase.java
2965
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.esb.samples.test.proxy; import org.apache.axiom.om.OMElement; import org.apache.axis2.AxisFault; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; import org.wso2.carbon.automation.engine.annotations.SetEnvironment; import org.wso2.esb.integration.common.utils.common.ServerConfigurationManager; import org.wso2.esb.integration.common.utils.ESBIntegrationTest; import javax.xml.namespace.QName; import java.io.File; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; /** * Create a proxy which invokes another proxy service and the communication should happen thorough * local transport */ public class Sample286TestCase extends ESBIntegrationTest { /*private ServerConfigurationManager serverManager; @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { super.init(); serverManager = new ServerConfigurationManager(context); serverManager.applyConfiguration(new File(getClass().getResource("/artifacts/ESB/proxyconfig" + "/proxy/enablelocaltransport/axis2.xml").getPath())); super.init(); loadSampleESBConfiguration(268); } @SetEnvironment(executionEnvironments = {ExecutionEnvironment.ALL}) @Test(groups = "wso2.esb", description = "proxy service with local transport") public void proxyServiceWithLocalTransportTest() throws AxisFault { OMElement response = axis2Client.sendSimpleStockQuoteRequest (getProxyServiceURLHttp("LocalTransportProxy"), null, "WSO2"); assertNotNull(response, "Response is null"); assertEquals(response.getFirstElement().getFirstChildWithName (new QName("http://services.samples/xsd", "symbol")).getText(), "WSO2", "Tag does not match"); } @AfterClass(alwaysRun = true) public void stop() throws Exception { try { cleanup(); } finally { Thread.sleep(3000); serverManager.restoreToLastConfiguration(); serverManager = null; } }*/ }
apache-2.0
JimSeker/saveData
eclipse/fileSystemDemo/src/edu/cs4730/filesystemdemo/frag_localpub.java
4348
package edu.cs4730.filesystemdemo; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.os.Bundle; import android.os.Environment; import android.widget.TextView; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; /* * This fragment will write (append) to a file to the local public area of the app. * then read back whatever is the file and display it to the screen. * * * uses the DataOutputStream/InputStream to read and write * * For bufferedWriter/reader example, see frag_ext.java */ public class frag_localpub extends Fragment { TextView logger; String TAG = "localp"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "OnCreateView"); View view = inflater.inflate(R.layout.frag_localpub, container, false); logger = (TextView) view.findViewById(R.id.loggerpub); view.findViewById(R.id.button2).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { logger.setText("Output:\n"); localfile(); } }); return view; } public void localfile() { //make sure the directories exist. File datafiledir = getActivity().getExternalFilesDir(null); datafiledir.mkdirs(); File datafile = new File(datafiledir, "myfiledata.txt"); //if the file exist, append, else create the file. if (datafile.exists()) { try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(datafile,true)); dos.writeUTF("Next line\n"); dos.close(); logger.append("Wrote next line to file\n"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { //file doesn't exist try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(datafile)); //no append dos.writeUTF("first line\n"); dos.close(); logger.append("Write first line to file\n"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //now read it back. try { DataInputStream in = new DataInputStream(new FileInputStream(datafile) ); while(true) try { logger.append(in.readUTF()); } catch (EOFException e) { //reach end of file in.close(); } } catch (FileNotFoundException e) { } catch (IOException e) { } //now do the same, except use the download directory. logger.append("\nDownload file:\n"); File dlfiledir = getActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); dlfiledir.mkdirs(); File dlfile = new File(dlfiledir, "myfiledl.txt"); if (dlfile.exists()) { try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(dlfile,true)); dos.writeUTF("2Next line\n"); dos.close(); logger.append("Wrote next line to file\n"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { //file doesn't exist try { DataOutputStream dos = new DataOutputStream(new FileOutputStream(dlfile)); //no append dos.writeUTF("1first line\n"); dos.close(); logger.append("Write first line to file\n"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //now read it back. logger.append("Now reading it back \n"); try { DataInputStream in = new DataInputStream(new FileInputStream(dlfile) ); while(true) try { logger.append(in.readUTF()); } catch (EOFException e) { //reach end of file in.close(); } } catch (FileNotFoundException e) { } catch (IOException e) { } } }
apache-2.0
grum/Ashley
benchmarks/src/main/java/com/badlogic/ashley/benchmark/artemis/systems/MovementSystem.java
2031
/******************************************************************************* * Copyright 2014 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.ashley.benchmark.artemis.systems; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.annotations.Mapper; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.ashley.benchmark.artemis.components.MovementComponent; import com.badlogic.ashley.benchmark.artemis.components.PositionComponent; import com.badlogic.gdx.math.Vector2; public class MovementSystem extends EntityProcessingSystem { private Vector2 tmp = new Vector2(); @Mapper ComponentMapper<PositionComponent> pm; @Mapper ComponentMapper<MovementComponent> mm; public MovementSystem() { super(Aspect.getAspectForAll(PositionComponent.class, MovementComponent.class)); } @Override protected void initialize() { pm = world.getMapper(PositionComponent.class); mm = world.getMapper(MovementComponent.class); } ; @Override protected void process(Entity entity) { PositionComponent pos = pm.get(entity); MovementComponent mov = mm.get(entity); tmp.set(mov.accel).scl(world.getDelta()); mov.velocity.add(tmp); tmp.set(mov.velocity).scl(world.getDelta()); pos.pos.add(tmp.x, tmp.y, 0.0f); } }
apache-2.0
mKaloer/PourMaster
core/src/main/java/pourmaster/fields/IntegerFieldType.java
517
package pourmaster.fields; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * Field type for Integers. */ public class IntegerFieldType implements FieldType<Integer> { public void writeToOutput(DataOutput output, Integer value) throws IOException { output.writeInt(value); } public Integer readFromInput(DataInput input) throws IOException { return input.readInt(); } public long getLength(Integer fieldValue) { return 1; } }
apache-2.0
LeonoraG/s-case-core
eu.scasefp7.eclipse.core.ui/src/org/eclipse/wb/swt/SWTResourceManager.java
8527
package org.eclipse.wb.swt; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; public class SWTResourceManager { private static Map<RGB, Color> m_colorMap = new HashMap<RGB, Color>(); public static Color getColor(int systemColorID) { Display display = Display.getCurrent(); return display.getSystemColor(systemColorID); } public static Color getColor(int r, int g, int b) { return getColor(new RGB(r, g, b)); } public static Color getColor(RGB rgb) { Color color = (Color)m_colorMap.get(rgb); if (color == null) { Display display = Display.getCurrent(); color = new Color(display, rgb); m_colorMap.put(rgb, color); } return color; } public static void disposeColors() { for (Color color : m_colorMap.values()) color.dispose(); m_colorMap.clear(); } private static Map<String, Image> m_imageMap = new HashMap<String, Image>(); public static final int TOP_LEFT = 1; public static final int TOP_RIGHT = 2; public static final int BOTTOM_LEFT = 3; public static final int BOTTOM_RIGHT = 4; protected static final int LAST_CORNER_KEY = 5; protected static Image getImage(InputStream stream) throws IOException { try { Display display = Display.getCurrent(); ImageData data = new ImageData(stream); //Image localImage; if (data.transparentPixel > 0) { return new Image(display, data, data.getTransparencyMask()); } return new Image(display, data); } finally { stream.close(); } } public static Image getImage(String path) { Image image = (Image)m_imageMap.get(path); if (image == null) { try { image = getImage(new FileInputStream(path)); m_imageMap.put(path, image); } catch (Exception localException) { image = getMissingImage(); m_imageMap.put(path, image); } } return image; } public static Image getImage(Class<?> clazz, String path) { String key = clazz.getName() + '|' + path; Image image = (Image)m_imageMap.get(key); if (image == null) { try { image = getImage(clazz.getResourceAsStream(path)); m_imageMap.put(key, image); } catch (Exception localException) { image = getMissingImage(); m_imageMap.put(key, image); } } return image; } private static Image getMissingImage() { Image image = new Image(Display.getCurrent(), 10, 10); GC gc = new GC(image); gc.setBackground(getColor(3)); gc.fillRectangle(0, 0, 10, 10); gc.dispose(); return image; } private static Map<Image, Map<Image, Image>>[] m_decoratedImageMap = new Map[5]; public static Image decorateImage(Image baseImage, Image decorator) { return decorateImage(baseImage, decorator, 4); } public static Image decorateImage(Image baseImage, Image decorator, int corner) { if ((corner <= 0) || (corner >= 5)) { throw new IllegalArgumentException("Wrong decorate corner"); } Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[corner]; if (cornerDecoratedImageMap == null) { cornerDecoratedImageMap = new HashMap<Image, Map<Image, Image>>(); m_decoratedImageMap[corner] = cornerDecoratedImageMap; } Map<Image, Image> decoratedMap = (Map<Image, Image>)cornerDecoratedImageMap.get(baseImage); if (decoratedMap == null) { decoratedMap = new HashMap<Image, Image>(); cornerDecoratedImageMap.put(baseImage, decoratedMap); } Image result = (Image)decoratedMap.get(decorator); if (result == null) { Rectangle bib = baseImage.getBounds(); int width = bib.width; int height = bib.height; result = new Image(Display.getCurrent(), width, height); GC gc = new GC(result); gc.drawImage(baseImage, 0, 0); if (corner == 1) { gc.drawImage(decorator, 0, 0); } else if (corner == 2) { gc.drawImage(decorator, width - width, 0); } else if (corner == 3) { gc.drawImage(decorator, 0, height - height); } else if (corner == 4) { gc.drawImage(decorator, width - width, height - height); } gc.dispose(); decoratedMap.put(decorator, result); } return result; } public static void disposeImages() { for (Image image : m_imageMap.values()) { image.dispose(); } m_imageMap.clear(); for (int i = 0; i < m_decoratedImageMap.length; i++) { Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i]; if (cornerDecoratedImageMap != null) { for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) { for (Image image : decoratedMap.values()) { image.dispose(); } decoratedMap.clear(); } cornerDecoratedImageMap.clear(); } } } private static Map<String, Font> m_fontMap = new HashMap<String, Font>(); private static Map<Font, Font> m_fontToBoldFontMap = new HashMap<Font, Font>(); public static Font getFont(String name, int height, int style) { return getFont(name, height, style, false, false); } public static Font getFont(String name, int size, int style, boolean strikeout, boolean underline) { String fontName = name + '|' + size + '|' + style + '|' + strikeout + '|' + underline; Font font = (Font)m_fontMap.get(fontName); if (font == null) { FontData fontData = new FontData(name, size, style); if ((strikeout) || (underline)) { try { Class<?> logFontClass = Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); Object logFont = FontData.class.getField("data").get(fontData); if ((logFont != null) && (logFontClass != null)) { if (strikeout) { logFontClass.getField("lfStrikeOut").set(logFont, Byte.valueOf((byte)1)); } if (underline) { logFontClass.getField("lfUnderline").set(logFont, Byte.valueOf((byte)1)); } } } catch (Throwable e) { System.err.println("Unable to set underline or strikeout (probably on a non-Windows platform). " + e); } } font = new Font(Display.getCurrent(), fontData); m_fontMap.put(fontName, font); } return font; } public static Font getBoldFont(Font baseFont) { Font font = (Font)m_fontToBoldFontMap.get(baseFont); if (font == null) { FontData[] fontDatas = baseFont.getFontData(); FontData data = fontDatas[0]; font = new Font(Display.getCurrent(), data.getName(), data.getHeight(), 1); m_fontToBoldFontMap.put(baseFont, font); } return font; } public static void disposeFonts() { for (Font font : m_fontMap.values()) { font.dispose(); } m_fontMap.clear(); for (Font font : m_fontToBoldFontMap.values()) { font.dispose(); } m_fontToBoldFontMap.clear(); } private static Map<Integer, Cursor> m_idToCursorMap = new HashMap<Integer, Cursor>(); public static Cursor getCursor(int id) { Integer key = Integer.valueOf(id); Cursor cursor = (Cursor)m_idToCursorMap.get(key); if (cursor == null) { cursor = new Cursor(Display.getDefault(), id); m_idToCursorMap.put(key, cursor); } return cursor; } public static void disposeCursors() { for (Cursor cursor : m_idToCursorMap.values()) { cursor.dispose(); } m_idToCursorMap.clear(); } public static void dispose() { disposeColors(); disposeImages(); disposeFonts(); disposeCursors(); } }
apache-2.0
davidcv/exercises
spike/src/main/java/org/david/exercises/solid/i/sol/IDiallable.java
185
package org.david.exercises.solid.i.sol; /** * Created by David Marques on 24/05/2017. */ public interface IDiallable { String phone(); IDiallable setPhone(String phone); }
apache-2.0
wujiazhong/SpringFrameworkLearning
SourceCode/ch8_2/src/main/java/com/wisely/dao/PersonRepository.java
663
package com.wisely.dao; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.wisely.domain.Person; import com.wisely.support.CustomRepository; public interface PersonRepository extends CustomRepository<Person, Long> { List<Person> findByAddress(String address); Person findByNameAndAddress(String name,String address); @Query("select p from Person p where p.name= :name and p.address= :address") Person withNameAndAddressQuery(@Param("name")String name,@Param("address")String address); Person withNameAndAddressNamedQuery(String name,String address); }
apache-2.0
d80harri/wr3
wr.ui/src/main/java/net/d80harri/wr/ui/core/SpringAwareBeanMapper.java
2581
package net.d80harri.wr.ui.core; import java.util.Map; import ma.glasnost.orika.Converter; import ma.glasnost.orika.Mapper; import ma.glasnost.orika.MapperFactory; import ma.glasnost.orika.impl.ConfigurableMapper; import ma.glasnost.orika.impl.DefaultMapperFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringAwareBeanMapper extends ConfigurableMapper implements ApplicationContextAware { private MapperFactory factory; /** * {@inheritDoc} */ @Override protected void configureFactoryBuilder(final DefaultMapperFactory.Builder factoryBuilder) { // customize the factoryBuilder as needed } /** * {@inheritDoc} */ @Override protected void configure(final MapperFactory factory) { this.factory = factory; // customize the factory as needed } /** * {@inheritDoc} */ @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { addAllSpringBeans(applicationContext); } /** * Adds all managed beans of type {@link Mapper} or {@link Converter} to the parent {@link MapperFactory}. * * @param applicationContext The application context to look for managed beans in. */ @SuppressWarnings("rawtypes") private void addAllSpringBeans(final ApplicationContext applicationContext) { final Map<String, Converter> converters = applicationContext.getBeansOfType(Converter.class); for (final Converter converter : converters.values()) { addConverter(converter); } final Map<String, Mapper> mappers = applicationContext.getBeansOfType(Mapper.class); for (final Mapper mapper : mappers.values()) { addMapper(mapper); } } /** * Add a {@link Converter}. * * @param converter The converter. */ public void addConverter(final Converter<?, ?> converter) { factory.getConverterFactory().registerConverter(converter); } /** * Add a {@link Mapper}. * * @param mapper The mapper. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void addMapper(final Mapper<?, ?> mapper) { factory.classMap(mapper.getAType(), mapper.getBType()) .byDefault() .customize((Mapper) mapper) .register(); } }
apache-2.0
alim1369/sos
src/sos/fire_v2/target/building/SOSTargetChooser2012_LargeMap.java
3488
package sos.fire_v2.target.building; import sos.base.entities.Building; import sos.base.message.structure.MessageConstants.Type; import sos.base.sosFireZone.SOSEstimatedFireZone; import sos.base.sosFireZone.SOSFireZoneManager; import sos.fire_v2.base.worldmodel.FireWorldModel; public class SOSTargetChooser2012_LargeMap extends SOSTargetChooser2012 { public SOSTargetChooser2012_LargeMap(SOSFireZoneManager fireSiteManager, FireWorldModel model) { super(fireSiteManager, model); } @Override protected void setConstants() { super.setConstants(); DISTANCE_PRIORITY = -300; if (model.sosAgent().messageSystem.type == Type.NoComunication) DISTANCE_PRIORITY = -100*5; // PRE_EX_LARGE_BUILDING_AREA_NEAR_SMALL_BUILDING = 100; // PRE_EX_LARGE_BUILDING_TEMPERATURE_NEAR_SMALL_BUILDING = 10; PRE_EX_LARGE_BUILDING_NEAR_SMALL_BUILDING_AREA = 150; PRE_EX_MINIMUM_AREA = 300; PRE_EX_MINIMUM_TEMPERATURE = 10; } /** * Yoosef * * @param site */ @Override protected void setPriority(SOSEstimatedFireZone site) { // if (model.getInnerOfMap().contains(site.getCenterX(), site.getCenterY())) // SPREAD_ANGLE = 90; // else // //TODO SPREAD_ANGLE = 70; ///////FILTERS//////////// filterRefugesAndCenters(); ////////SPREAD////////// // EX_E_setPriorityForSpreadForLargeFireSites(20000, site); long t1 = System.currentTimeMillis(); EX_E_setPriorityForSpread(Math.min(10000, site.getAllBuildings().size() * 80), site); log("time for spread " + (System.currentTimeMillis() - t1)); // EX_EP_setPriorityForFireBrigadeGroup(1000, site); //////////////ILAND_ROADSITE//////////////// // log(" time Road site " + (System.currentTimeMillis() - t1)); // log("time for new iland" + (System.currentTimeMillis() - t1)); //////////////////////// //select center if burning EX_E_setPriorityForCenters(1000000); for (Building b : bs) { EX_E_setPriorityForBuildingsInNewRoadSites(1000, b); EX_EP_setPriorityForDistance(b, DISTANCE_PRIORITY); EX_E_setPriorityForBuildingsInNewIslands(2000, site, b); // ? else // EX_EP_setPriorityForDistance(b, DISTANCE_PRIORITY*10); EX_E_setPriorityForEarlyIgnitedBuildings(b, 600); EX_E_setPriorityForBuildingNotInMapSideBuildings(b, 5000); EX_E_setPriorityForUnburnedNeighbours(b, 300); EX_E_setPriorityForFireNess(b, 300); EX_E_setPriorityForNeutral(b, -100000); EX_EP_setPriorityForBigBuilding(b); EX_P_setPriorityForCriticalTempratureBuildings(b, 1200); if (isLarge(site)) { } } log("\n\n time after for1 " + (System.currentTimeMillis() - t1) + " size " + bs.size()); for (Building n : ns) { EX_E_setPriorityForBuildingsInNewRoadSites(1000, n); EX_E_setPriorityForBuildingsInNewIslands(2000, site, n); EX_EP_setPriorityForDistance(n, DISTANCE_PRIORITY); //? else // EX_EP_setPriorityForDistance(n, DISTANCE_PRIORITY*20); EX_E_setPriorityForFireNess(n, 300); EX_E_setPriorityForBuildingNotInMapSideBuildings(n, 5000); EX_P_setPreExtinguishProrityForLargBuildingsNearSmallFireBuilding(n, 1000);//checked EX_P_setPriorityForCriticalTempratureBuildings(n, 1200); EX_P_setPriorityForUnBurnedIsLands(n, 1500); EX_P_setPriorityForUnBurnedRoadSites(n, 1000); EX_E_setPriorityForNeutral(n, -100000); EX_P_setPriorityForBigBuilding(n); EX_E_setPriorityForUnburnedNeighbours(n, 100); } log("time after for2 " + (System.currentTimeMillis() - t1) + " size " + ns.size()); } }
apache-2.0
nafae/developer
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201308/VpaidLinearCreative.java
22533
/** * VpaidLinearCreative.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201308; /** * A {@code Creative} that displays a DFP-hosted Flash-based ad * and is served via VAST 2.0 XML. It is displayed in a * linear fashion * with a video (before, after, interrupting). This creative * is read only. */ public class VpaidLinearCreative extends com.google.api.ads.dfp.axis.v201308.HasDestinationUrlCreative implements java.io.Serializable { /* The name of the Flash asset. This attribute is required and * has a maximum * length of 248 characters. */ private java.lang.String flashName; /* The contents of the Flash asset as a byte array. This attribute * is * required. The {@code flashByteArray} will be {@code * null} when the {@code * FlashCreative} is retrieved. To view the Flash * image, use the {@code * previewUrl}. */ private byte[] flashByteArray; /* Allows the creative size to differ from the actual Flash asset * size. This * attribute is optional. */ private java.lang.Boolean overrideSize; /* The Flash asset size. Note that this may differ from {@link * #size} if * {@link #overrideSize} is set to true. This attribute * is read-only and is * populated by Google. */ private com.google.api.ads.dfp.axis.v201308.Size flashAssetSize; /* The IDs of the companion creatives that are associated with * this creative. * This attribute is optional. */ private long[] companionCreativeIds; /* A map from {@code ConversionEvent} to a list of URLs that will * be pinged * when the event happens. This attribute is optional. */ private com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls; /* A string that is supplied to the VPAID creative's init function. * This is written into the VAST XML in the {@code AdParameters} section. * This attribute is optional. */ private java.lang.String customParameters; /* Duration in milliseconds for the vpaid ad given no user interaction. * This attribute is optional. */ private java.lang.Integer duration; /* An ad tag URL that will return a preview of the VAST XML response * specific * to this creative. This attribute is read-only. */ private java.lang.String vastPreviewUrl; public VpaidLinearCreative() { } public VpaidLinearCreative( java.lang.Long advertiserId, java.lang.Long id, java.lang.String name, com.google.api.ads.dfp.axis.v201308.Size size, java.lang.String previewUrl, com.google.api.ads.dfp.axis.v201308.AppliedLabel[] appliedLabels, com.google.api.ads.dfp.axis.v201308.DateTime lastModifiedDateTime, com.google.api.ads.dfp.axis.v201308.BaseCustomFieldValue[] customFieldValues, java.lang.String creativeType, java.lang.String destinationUrl, java.lang.String flashName, byte[] flashByteArray, java.lang.Boolean overrideSize, com.google.api.ads.dfp.axis.v201308.Size flashAssetSize, long[] companionCreativeIds, com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls, java.lang.String customParameters, java.lang.Integer duration, java.lang.String vastPreviewUrl) { super( advertiserId, id, name, size, previewUrl, appliedLabels, lastModifiedDateTime, customFieldValues, creativeType, destinationUrl); this.flashName = flashName; this.flashByteArray = flashByteArray; this.overrideSize = overrideSize; this.flashAssetSize = flashAssetSize; this.companionCreativeIds = companionCreativeIds; this.trackingUrls = trackingUrls; this.customParameters = customParameters; this.duration = duration; this.vastPreviewUrl = vastPreviewUrl; } /** * Gets the flashName value for this VpaidLinearCreative. * * @return flashName * The name of the Flash asset. This attribute is required and * has a maximum * length of 248 characters. */ public java.lang.String getFlashName() { return flashName; } /** * Sets the flashName value for this VpaidLinearCreative. * * @param flashName * The name of the Flash asset. This attribute is required and * has a maximum * length of 248 characters. */ public void setFlashName(java.lang.String flashName) { this.flashName = flashName; } /** * Gets the flashByteArray value for this VpaidLinearCreative. * * @return flashByteArray * The contents of the Flash asset as a byte array. This attribute * is * required. The {@code flashByteArray} will be {@code * null} when the {@code * FlashCreative} is retrieved. To view the Flash * image, use the {@code * previewUrl}. */ public byte[] getFlashByteArray() { return flashByteArray; } /** * Sets the flashByteArray value for this VpaidLinearCreative. * * @param flashByteArray * The contents of the Flash asset as a byte array. This attribute * is * required. The {@code flashByteArray} will be {@code * null} when the {@code * FlashCreative} is retrieved. To view the Flash * image, use the {@code * previewUrl}. */ public void setFlashByteArray(byte[] flashByteArray) { this.flashByteArray = flashByteArray; } /** * Gets the overrideSize value for this VpaidLinearCreative. * * @return overrideSize * Allows the creative size to differ from the actual Flash asset * size. This * attribute is optional. */ public java.lang.Boolean getOverrideSize() { return overrideSize; } /** * Sets the overrideSize value for this VpaidLinearCreative. * * @param overrideSize * Allows the creative size to differ from the actual Flash asset * size. This * attribute is optional. */ public void setOverrideSize(java.lang.Boolean overrideSize) { this.overrideSize = overrideSize; } /** * Gets the flashAssetSize value for this VpaidLinearCreative. * * @return flashAssetSize * The Flash asset size. Note that this may differ from {@link * #size} if * {@link #overrideSize} is set to true. This attribute * is read-only and is * populated by Google. */ public com.google.api.ads.dfp.axis.v201308.Size getFlashAssetSize() { return flashAssetSize; } /** * Sets the flashAssetSize value for this VpaidLinearCreative. * * @param flashAssetSize * The Flash asset size. Note that this may differ from {@link * #size} if * {@link #overrideSize} is set to true. This attribute * is read-only and is * populated by Google. */ public void setFlashAssetSize(com.google.api.ads.dfp.axis.v201308.Size flashAssetSize) { this.flashAssetSize = flashAssetSize; } /** * Gets the companionCreativeIds value for this VpaidLinearCreative. * * @return companionCreativeIds * The IDs of the companion creatives that are associated with * this creative. * This attribute is optional. */ public long[] getCompanionCreativeIds() { return companionCreativeIds; } /** * Sets the companionCreativeIds value for this VpaidLinearCreative. * * @param companionCreativeIds * The IDs of the companion creatives that are associated with * this creative. * This attribute is optional. */ public void setCompanionCreativeIds(long[] companionCreativeIds) { this.companionCreativeIds = companionCreativeIds; } public long getCompanionCreativeIds(int i) { return this.companionCreativeIds[i]; } public void setCompanionCreativeIds(int i, long _value) { this.companionCreativeIds[i] = _value; } /** * Gets the trackingUrls value for this VpaidLinearCreative. * * @return trackingUrls * A map from {@code ConversionEvent} to a list of URLs that will * be pinged * when the event happens. This attribute is optional. */ public com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] getTrackingUrls() { return trackingUrls; } /** * Sets the trackingUrls value for this VpaidLinearCreative. * * @param trackingUrls * A map from {@code ConversionEvent} to a list of URLs that will * be pinged * when the event happens. This attribute is optional. */ public void setTrackingUrls(com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls) { this.trackingUrls = trackingUrls; } public com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry getTrackingUrls(int i) { return this.trackingUrls[i]; } public void setTrackingUrls(int i, com.google.api.ads.dfp.axis.v201308.ConversionEvent_TrackingUrlsMapEntry _value) { this.trackingUrls[i] = _value; } /** * Gets the customParameters value for this VpaidLinearCreative. * * @return customParameters * A string that is supplied to the VPAID creative's init function. * This is written into the VAST XML in the {@code AdParameters} section. * This attribute is optional. */ public java.lang.String getCustomParameters() { return customParameters; } /** * Sets the customParameters value for this VpaidLinearCreative. * * @param customParameters * A string that is supplied to the VPAID creative's init function. * This is written into the VAST XML in the {@code AdParameters} section. * This attribute is optional. */ public void setCustomParameters(java.lang.String customParameters) { this.customParameters = customParameters; } /** * Gets the duration value for this VpaidLinearCreative. * * @return duration * Duration in milliseconds for the vpaid ad given no user interaction. * This attribute is optional. */ public java.lang.Integer getDuration() { return duration; } /** * Sets the duration value for this VpaidLinearCreative. * * @param duration * Duration in milliseconds for the vpaid ad given no user interaction. * This attribute is optional. */ public void setDuration(java.lang.Integer duration) { this.duration = duration; } /** * Gets the vastPreviewUrl value for this VpaidLinearCreative. * * @return vastPreviewUrl * An ad tag URL that will return a preview of the VAST XML response * specific * to this creative. This attribute is read-only. */ public java.lang.String getVastPreviewUrl() { return vastPreviewUrl; } /** * Sets the vastPreviewUrl value for this VpaidLinearCreative. * * @param vastPreviewUrl * An ad tag URL that will return a preview of the VAST XML response * specific * to this creative. This attribute is read-only. */ public void setVastPreviewUrl(java.lang.String vastPreviewUrl) { this.vastPreviewUrl = vastPreviewUrl; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof VpaidLinearCreative)) return false; VpaidLinearCreative other = (VpaidLinearCreative) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.flashName==null && other.getFlashName()==null) || (this.flashName!=null && this.flashName.equals(other.getFlashName()))) && ((this.flashByteArray==null && other.getFlashByteArray()==null) || (this.flashByteArray!=null && java.util.Arrays.equals(this.flashByteArray, other.getFlashByteArray()))) && ((this.overrideSize==null && other.getOverrideSize()==null) || (this.overrideSize!=null && this.overrideSize.equals(other.getOverrideSize()))) && ((this.flashAssetSize==null && other.getFlashAssetSize()==null) || (this.flashAssetSize!=null && this.flashAssetSize.equals(other.getFlashAssetSize()))) && ((this.companionCreativeIds==null && other.getCompanionCreativeIds()==null) || (this.companionCreativeIds!=null && java.util.Arrays.equals(this.companionCreativeIds, other.getCompanionCreativeIds()))) && ((this.trackingUrls==null && other.getTrackingUrls()==null) || (this.trackingUrls!=null && java.util.Arrays.equals(this.trackingUrls, other.getTrackingUrls()))) && ((this.customParameters==null && other.getCustomParameters()==null) || (this.customParameters!=null && this.customParameters.equals(other.getCustomParameters()))) && ((this.duration==null && other.getDuration()==null) || (this.duration!=null && this.duration.equals(other.getDuration()))) && ((this.vastPreviewUrl==null && other.getVastPreviewUrl()==null) || (this.vastPreviewUrl!=null && this.vastPreviewUrl.equals(other.getVastPreviewUrl()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getFlashName() != null) { _hashCode += getFlashName().hashCode(); } if (getFlashByteArray() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getFlashByteArray()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getFlashByteArray(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } if (getOverrideSize() != null) { _hashCode += getOverrideSize().hashCode(); } if (getFlashAssetSize() != null) { _hashCode += getFlashAssetSize().hashCode(); } if (getCompanionCreativeIds() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getCompanionCreativeIds()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getCompanionCreativeIds(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } if (getTrackingUrls() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getTrackingUrls()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getTrackingUrls(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } if (getCustomParameters() != null) { _hashCode += getCustomParameters().hashCode(); } if (getDuration() != null) { _hashCode += getDuration().hashCode(); } if (getVastPreviewUrl() != null) { _hashCode += getVastPreviewUrl().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(VpaidLinearCreative.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "VpaidLinearCreative")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("flashName"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "flashName")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("flashByteArray"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "flashByteArray")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "base64Binary")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("overrideSize"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "overrideSize")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("flashAssetSize"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "flashAssetSize")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "Size")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("companionCreativeIds"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "companionCreativeIds")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setMaxOccursUnbounded(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("trackingUrls"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "trackingUrls")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "ConversionEvent_TrackingUrlsMapEntry")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setMaxOccursUnbounded(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("customParameters"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "customParameters")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("duration"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "duration")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("vastPreviewUrl"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "vastPreviewUrl")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
vjanmey/EpicMudfia
com/planet_ink/coffee_mud/Abilities/Thief/Thief_ImprovedSteal.java
2668
package com.planet_ink.coffee_mud.Abilities.Thief; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Thief_ImprovedSteal extends ThiefSkill { @Override public String ID() { return "Thief_ImprovedSteal"; } private final static String localizedName = CMLib.lang()._("Improved Steal"); @Override public String name() { return localizedName; } @Override public String displayText(){ return "";} @Override protected int canAffectCode(){return CAN_MOBS;} @Override protected int canTargetCode(){return 0;} @Override public int classificationCode(){return Ability.ACODE_THIEF_SKILL|Ability.DOMAIN_STEALING;} @Override public int abstractQuality(){return Ability.QUALITY_OK_SELF;} @Override public boolean isAutoInvoked(){return true;} @Override public boolean canBeUninvoked(){return false;} @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(affected instanceof MOB)) return super.okMessage(myHost,msg); final MOB mob=(MOB)affected; if((msg.amISource(mob)) &&(msg.tool()!=null) &&(msg.tool().ID().equals("Thief_Steal"))) { helpProficiency(mob, 0); final Ability A=mob.fetchAbility("Thief_Steal"); final float f=getXLEVELLevel(mob); final int ableDiv=(int)Math.round(5.0-(f*0.2)); A.setAbilityCode(proficiency()/ableDiv); } return super.okMessage(myHost,msg); } }
apache-2.0
domeo/DomeoClient
src/org/mindinformatics/gwt/domeo/plugins/resource/nif/search/antibodies/AntibodiesSearch.java
4419
package org.mindinformatics.gwt.domeo.plugins.resource.nif.search.antibodies; import java.util.Set; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; /** * * @author Paolo Ciccarese <paolo.ciccarese@gmail.com> */ public class AntibodiesSearch extends Composite { interface Binder extends UiBinder<HorizontalPanel, AntibodiesSearch> { } private static final Binder binder = GWT.create(Binder.class); public static final String ALL_URI = "http://www.paolociccarese.info/ontology/misc/all"; public static final String ALL_LABEL = "All"; public static final String CATALOG = "catalog"; public static final String NAME = "name"; public static final String CLONE = "clone"; private AntibodiesSearchWidget _widget; @UiField ListBox searchType; @UiField TextBox searchBox; @UiField TextBox vendorBox; @UiField Image rightSide; @UiField Label numberResults; @UiField Label filterLabel; @UiField ListBox sourcesLabels; public AntibodiesSearch(AntibodiesSearchWidget widget, String exact) { _widget = widget; initWidget(binder.createAndBindUi(this)); if (exact.length() < 40) searchBox.setText(exact); searchBox.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { int charCode = event.getUnicodeCharCode(); if (charCode == 0) { // it's probably Firefox int keyCode = event.getNativeEvent().getKeyCode(); if (keyCode == KeyCodes.KEY_ENTER) { _widget.performSearch(searchType.getValue(searchType.getSelectedIndex()), searchBox.getText().trim(), vendorBox.getText().trim()); } } else if (charCode == KeyCodes.KEY_ENTER) { _widget.performSearch(searchType.getValue(searchType.getSelectedIndex()), searchBox.getText().trim(), vendorBox.getText().trim()); } } }); /* vendorBox.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { _widget.performSearch(searchType.getValue(searchType.getSelectedIndex()), searchBox.getText().trim(), vendorBox.getText().trim()); } } }); */ //vendorBox.setEnabled(false); rightSide.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { _widget.performSearch(searchType.getValue(searchType.getSelectedIndex()), searchBox.getText().trim(), vendorBox.getText().trim()); } }); // For filtering results according to the source sourcesLabels.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent event) { _widget.filterBySource(sourcesLabels.getValue(sourcesLabels.getSelectedIndex())); } }); sourcesLabels.setEnabled(false); searchType.addItem("Name", NAME); searchType.addItem("Catalog Number", CATALOG); searchType.addItem("Clone Number", CLONE); } public void updateResultsStats() { sourcesLabels.setEnabled(true); String termLabel = _widget.getSearchTermsResult().size() > 1 ? " results" : " result"; String vocabularyLabel = _widget.getSearchTermsResultSources().size() > 1 ? " vendors" : " vendor"; numberResults.setText("" + _widget.getSearchTermsResult().size() + termLabel + " in " + _widget.getSearchTermsResultSources().size() + vocabularyLabel); sourcesLabels.clear(); Set<String> keys = _widget.getSearchTermsResultSources(); sourcesLabels.addItem(ALL_LABEL, ALL_URI); for (String key : keys) { if(key != null) { sourcesLabels.addItem(((key.length()>30)?(key.substring(0, 30)+"..."):key), key); } } } public String getSourceFilterValue() { return sourcesLabels.getValue(sourcesLabels.getSelectedIndex()); } }
apache-2.0