code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.engine.backgroundtasks.config; /** * <p> * Class containing strings that describe the Kafka queues and groups * </p> * * @author Denis Lobanov, alexandraorth */ public interface KafkaTerms { String TASK_RUNNER_GROUP = "task-runners"; String SCHEDULERS_GROUP = "schedulers"; String WORK_QUEUE_TOPIC = "work-queue"; String NEW_TASKS_TOPIC = "new-tasks"; String LOG_TOPIC = "logs"; }
mikonapoli/grakn
grakn-engine/src/main/java/ai/grakn/engine/backgroundtasks/config/KafkaTerms.java
Java
gpl-3.0
1,152
import java.util.Scanner; public class FeetMeters { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Number of feet: "); float feet = keyboard.nextInt(); float foottometers = (float) .305; System.out.println(""); System.out.print("Number of meters: "); float meters = (float) .305 * feet; System.out.println(meters); } }
semiconductor7/java-101
Projects_import/Project1/src/FeetMeters.java
Java
gpl-3.0
467
package ProxyPattern; public class GumballMachineTestDrive { public static void main(String[] args) { int count = 0; if (args .length < 2) { System.out.println("GumballMachine <name> <inventory>"); System.exit(1); } count = Integer.parseInt(args[1]); GumballMachine gumballMachine = new GumballMachine(args[0], count); GumballMonitor monitor = new GumballMonitor(gumballMachine); monitor.report(); } }
ohgood/Head-First-Design-Patterns
ProxyPattern/GumballMachineTestDrive.java
Java
gpl-3.0
425
// This code is part of the CPCC-NG project. // // Copyright (c) 2009-2016 Clemens Krainer <clemens.krainer@gmail.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. package cpcc.demo.setup.builder; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.tuple.Pair; import cpcc.core.entities.SensorDefinition; import cpcc.core.entities.SensorType; import cpcc.core.entities.SensorVisibility; import cpcc.core.entities.TopicCategory; /** * Sensor Constants implementation. */ public final class SensorConstants { private static final String SENSOR_MSGS_NAV_SAT_FIX = "sensor_msgs/NavSatFix"; private static final String SENSOR_MSGS_IMAGE = "sensor_msgs/Image"; private static final String STD_MSGS_FLOAT32 = "std_msgs/Float32"; private static final Date now = new Date(); private static final SensorDefinition[] SENSOR_DEFINITIONS = { new SensorDefinitionBuilder() .setId(1) .setDescription("Altimeter") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.ALTIMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(2) .setDescription("Area of Operations") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.AREA_OF_OPERATIONS) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(3) .setDescription("Barometer") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.BAROMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(4) .setDescription("Battery") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.BATTERY) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(5) .setDescription("Belly Mounted Camera 640x480") .setLastUpdate(now) .setMessageType(SENSOR_MSGS_IMAGE) .setParameters("width=640 height=480 yaw=0 down=1.571 alignment=''north''") .setType(SensorType.CAMERA) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), // new SensorDefinitionBuilder() // .setId(6) // .setDescription("FPV Camera 640x480") // .setLastUpdate(now) // .setMessageType("sensor_msgs/Image") // .setParameters("width=640 height=480 yaw=0 down=0 alignment=''heading''") // .setType(SensorType.CAMERA) // .setVisibility(SensorVisibility.ALL_VV) // .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(7) .setDescription("CO2") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.CO2) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(9) .setDescription("GPS") .setLastUpdate(now) .setMessageType(SENSOR_MSGS_NAV_SAT_FIX) .setParameters(null) .setType(SensorType.GPS) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(10) .setDescription("Hardware") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.HARDWARE) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(11) .setDescription("NOx") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.NOX) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(12) .setDescription("Thermometer") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.THERMOMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build() }; public static final Map<TopicCategory, SensorType> TOPIC_SENSOR_MAP = Collections.unmodifiableMap(Stream .of(Pair.of(TopicCategory.ALTITUDE_OVER_GROUND, SensorType.ALTIMETER), Pair.of(TopicCategory.CAMERA, SensorType.CAMERA), Pair.of(TopicCategory.CAMERA_INFO, SensorType.CAMERA), Pair.of(TopicCategory.GPS_POSITION_PROVIDER, SensorType.GPS)) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight))); private SensorConstants() { // Intentionally empty. } /** * @param type the required sensor types. * @return all sensor definitions specified in type. */ public static List<SensorDefinition> byType(SensorType... type) { Set<SensorType> types = Stream.of(type).collect(Collectors.toSet()); return Stream.of(SENSOR_DEFINITIONS).filter(x -> types.contains(x.getType())).collect(Collectors.toList()); } /** * @return all sensor definitions. */ public static List<SensorDefinition> all() { return Arrays.asList(SENSOR_DEFINITIONS); } }
cksystemsgroup/cpcc
cpcc-demo/src/main/java/cpcc/demo/setup/builder/SensorConstants.java
Java
gpl-3.0
6,792
/* * Decompiled with CFR 0_114. * * Could not load the following classes: * com.stimulsoft.base.drawing.StiBrush * com.stimulsoft.base.drawing.StiColor * com.stimulsoft.base.drawing.StiSolidBrush * com.stimulsoft.base.drawing.enums.StiPenStyle * com.stimulsoft.base.serializing.annotations.StiDefaulValue * com.stimulsoft.base.serializing.annotations.StiSerializable */ package com.stimulsoft.report.chart.view.series.radar; import com.stimulsoft.base.drawing.StiBrush; import com.stimulsoft.base.drawing.StiColor; import com.stimulsoft.base.drawing.StiSolidBrush; import com.stimulsoft.base.drawing.enums.StiPenStyle; import com.stimulsoft.base.serializing.annotations.StiDefaulValue; import com.stimulsoft.base.serializing.annotations.StiSerializable; import com.stimulsoft.report.chart.core.series.StiSeriesCoreXF; import com.stimulsoft.report.chart.core.series.radar.StiRadarAreaSeriesCoreXF; import com.stimulsoft.report.chart.interfaces.series.IStiSeries; import com.stimulsoft.report.chart.interfaces.series.radar.IStiRadarAreaSeries; import com.stimulsoft.report.chart.view.areas.radar.StiRadarAreaArea; import com.stimulsoft.report.chart.view.series.radar.StiRadarSeries; public class StiRadarAreaSeries extends StiRadarSeries implements IStiRadarAreaSeries { private StiColor lineColor = StiColor.Black; private StiPenStyle lineStyle = StiPenStyle.Solid; private boolean lighting = true; private float lineWidth = 2.0f; private StiBrush brush = new StiSolidBrush(StiColor.Gainsboro); @StiSerializable public StiColor getLineColor() { return this.lineColor; } public void setLineColor(StiColor stiColor) { this.lineColor = stiColor; } @StiDefaulValue(value="Solid") @StiSerializable public StiPenStyle getLineStyle() { return this.lineStyle; } public void setLineStyle(StiPenStyle stiPenStyle) { this.lineStyle = stiPenStyle; } @StiDefaulValue(value="true") @StiSerializable public boolean getLighting() { return this.lighting; } public void setLighting(boolean bl) { this.lighting = bl; } @StiDefaulValue(value="2.0") @StiSerializable public float getLineWidth() { return this.lineWidth; } public void setLineWidth(float f) { if (f > 0.0f) { this.lineWidth = f; } } @StiSerializable(shortName="bh") public final StiBrush getBrush() { return this.brush; } public final void setBrush(StiBrush stiBrush) { this.brush = stiBrush; } public Class GetDefaultAreaType() { return StiRadarAreaArea.class; } public StiRadarAreaSeries() { this.setCore(new StiRadarAreaSeriesCoreXF(this)); } }
talek69/curso
stimulsoft/src/com/stimulsoft/report/chart/view/series/radar/StiRadarAreaSeries.java
Java
gpl-3.0
2,787
package com.base.engine.math; public class Vector2f { private float x, y; public Vector2f(float x, float y) { this.x = x; this.y = y; } public Vector2f normalized() { float len = length(); float x_ = x / len; float y_ = y / len; return new Vector2f(x_, y_); } public float length() { return (float)Math.sqrt(x * x + y * y); } public Vector2f add(Vector2f r) { return new Vector2f(x + r.getX(), y + r.getY()); } public Vector2f add(float r) { return new Vector2f(x + r, y + r); } public Vector2f sub(Vector2f r) { return new Vector2f(x - r.getX(), y - r.getY()); } public Vector2f sub(float r) { return new Vector2f(x - r, y - r); } public Vector2f mul(Vector2f r) { return new Vector2f(x * r.getX(), y * r.getY()); } public Vector2f mul(float r) { return new Vector2f(x * r, y * r); } public Vector2f div(Vector2f r) { return new Vector2f(x / r.getX(), y / r.getY()); } public Vector2f div(float r) { return new Vector2f(x / r, y / r); } public Vector2f abs() { return new Vector2f(Math.abs(x), Math.abs(y)); } @Override public String toString() { return "(" + x + ", " + y + ")"; } public float getX() { return this.x; } public void setX(float x) { this.x = x; } public float getY() { return this.y; } public void setY(float y) { this.y = y; } }
mattparizeau/2DGameEngine
ge_common/com/base/engine/math/Vector2f.java
Java
gpl-3.0
1,731
/* * Twidere - Twitter client for Android * * Copyright (C) 2012 Mariotaku Lee <mariotaku.lee@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mariotaku.twidere.util; import java.io.File; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Environment; public final class EnvironmentAccessor { public static File getExternalCacheDir(final Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) return GetExternalCacheDirAccessorFroyo.getExternalCacheDir(context); final File ext_storage_dir = Environment.getExternalStorageDirectory(); if (ext_storage_dir != null && ext_storage_dir.isDirectory()) { final String ext_cache_path = ext_storage_dir.getAbsolutePath() + "/Android/data/" + context.getPackageName() + "/cache/"; final File ext_cache_dir = new File(ext_cache_path); if (ext_cache_dir.isDirectory() || ext_cache_dir.mkdirs()) return ext_cache_dir; } return null; } @TargetApi(Build.VERSION_CODES.FROYO) private static class GetExternalCacheDirAccessorFroyo { @TargetApi(Build.VERSION_CODES.FROYO) private static File getExternalCacheDir(final Context context) { return context.getExternalCacheDir(); } } }
gen4young/twidere
src/org/mariotaku/twidere/util/EnvironmentAccessor.java
Java
gpl-3.0
1,877
public class Silver extends Piece { public Silver(int owner) { super(owner); setSymbol("S"); setType("Silver"); } public boolean canMove(Square from, Square to, Board b) { if(promoted) { //Gold movement code if((Math.abs(from.getR() - to.getR()) <= 1 && (Math.abs(from.getC() - to.getC()) <= 1))) { if(owner == 1) { //If Piece is moving backwards check for diagonal if(from.getR() - to.getR() == 1) { if(from.getC() != to.getC()) { return false; } } } else if(owner == 2) { //If Piece is moving backwards check for diagonal if(from.getR() - to.getR() == -1) { if(from.getC() != to.getC()) { return false; } } } if(to.getPiece() != null) { if(from.getPiece().getOwner() == to.getPiece().getOwner()) { return false; } } return true; } return false; } if((Math.abs(from.getR() - to.getR()) <= 1 && (Math.abs(from.getC() - to.getC()) <= 1))) { if(owner == 1) { //If Piece is moving backwards p1 if(from.getR() - to.getR() == 1) { if(from.getC() == to.getC()) { return false; } } } else if(owner == 2) { //If Piece is moving backwards p2 if(from.getR() - to.getR() == -1) { if(from.getC() == to.getC()) { return false; } } } //moving sideways if(from.getR() == to.getR()) { return false; } if(to.getPiece() != null) { if(from.getPiece().getOwner() == to.getPiece().getOwner()) { return false; } } return true; } return false; } }
dma-gh/Shogi-Game
src/Silver.java
Java
gpl-3.0
1,589
/* * This file is part of the OTHERobjects Content Management System. * * Copyright 2007-2009 OTHER works Limited. * * OTHERobjects is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OTHERobjects is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OTHERobjects. If not, see <http://www.gnu.org/licenses/>. */ package org.otherobjects.cms.tools; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import javax.annotation.Resource; import org.otherobjects.cms.model.User; import org.otherobjects.cms.model.UserDao; import org.otherobjects.cms.views.Tool; import org.springframework.stereotype.Component; /** * Generates URL to Gravatar images based on user email address. * * <p>For more info on Gravatars see <a href="http://en.gravatar.com/">http://en.gravatar.com/</a>. Details of * the algorithm are available at <a href="http://en.gravatar.com/site/implement/url">http://en.gravatar.com/site/implement/url</a>. * * @author rich */ @Component @Tool public class GravatarTool { private static final String GRAVATAR_SERVER = "http://www.gravatar.com/avatar/"; private static final String GRAVATAR_SECURE_SERVER = "https://secure.gravatar.com/avatar/"; @Resource protected UserDao userDao; /** * Generates url of Gravatar image for provided user. Username must be valid. * * @param username the username for the required user * @param size width in pixels of required image * @return the url to the image */ public String getUrl(String username, int size, boolean ssl) { return getUrl(username, size, null, ssl); } /** * Generates url of Gravatar image for provided user. Username must be valid. * If the user does not have a Gravatar image then the provided placeholder image url * is returned. * * @param username the username for the required user * @param size width in pixels of required image * @param placeholder the url of image to use when no Gravatar is available * @return the url to the image */ public String getUrl(String username, int size, String placeholder, boolean ssl) { User user = (User) userDao.loadUserByUsername(username); return getUrlForEmail(user.getEmail(), size, null, ssl); } /** * Generates url of Gravatar image for provided user. The email address does not * need to be for a user in OTHERobjects. * * If the user does not have a Gravatar image then the provided placeholder image url * is returned (provide a null placeholder to use the default Gravatar one). * * @param email the email address for the required user * @param size width in pixels of required image * @param placeholder the url of image to use when no Gravatar is available * @param ssl whether or not to get an image from a secure Gravatar url * @return the url to the image */ public String getUrlForEmail(String email, int size, String placeholder, boolean ssl) { StringBuffer url = new StringBuffer(ssl ? GRAVATAR_SECURE_SERVER : GRAVATAR_SERVER); // Add image name url.append(md5Hex(email)); url.append(".jpg"); // Add options StringBuffer options = new StringBuffer(); if (size > 0) { options.append("s=" + size); } try { if (placeholder != null) { if (options.length() > 0) { options.append("&"); } options.append("d=" + URLEncoder.encode(placeholder, "UTF-8")); } } catch (UnsupportedEncodingException e) { // Ignore -- UTF-8 must be supported } if (options.length() > 0) { url.append("?" + options.toString()); } return url.toString(); } public String getUrlForEmail(String email, int size, String placeholder) { return getUrlForEmail(email, size, placeholder, false); } private static String hex(byte[] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } private static String md5Hex(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex(md.digest(message.getBytes("CP1252"))); } catch (Exception e) { // Ignore } return null; } }
0x006EA1E5/oo6
src/main/java/org/otherobjects/cms/tools/GravatarTool.java
Java
gpl-3.0
5,206
package com.baobaotao.transaction.nestcall; public class BaseService { }
puliuyinyi/test
src/main/java/com/baobaotao/transaction/nestcall/BaseService.java
Java
gpl-3.0
75
/* Copyright (C) 2013 Jason Gowan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gowan.plugin; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.viewers.IStructuredSelection; public class SelectionToICompilationUnitList implements List<ICompilationUnit> { private List<ICompilationUnit> list; public SelectionToICompilationUnitList(IStructuredSelection selection){ List<ICompilationUnit> localList = new ArrayList<ICompilationUnit>(); List<Object> selectionList = selection.toList(); for (Object object : selectionList) { localList.addAll( delegate(object) ); } this.list = localList; } protected List<ICompilationUnit> delegate(Object selected){ List<ICompilationUnit> compilationUnits = new ArrayList<ICompilationUnit>(); if( selected instanceof ICompilationUnit ){ compilationUnits.add((ICompilationUnit)selected); }else if ( selected instanceof IPackageFragment){ compilationUnits.addAll(get((IPackageFragment)selected)); }else if( selected instanceof IPackageFragmentRoot){ compilationUnits.addAll(get((IPackageFragmentRoot)selected)); }else if( selected instanceof IJavaProject){ compilationUnits.addAll(get((IJavaProject)selected)); } return compilationUnits; } protected List<ICompilationUnit> get(IJavaProject selected) { List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); IPackageFragmentRoot[] packageRoots; try { packageRoots = selected.getAllPackageFragmentRoots(); for(int i=0; i<packageRoots.length; i++){ result.addAll(get(packageRoots[i])); } } catch (JavaModelException e) { e.printStackTrace(); } return result; } protected List<ICompilationUnit> get(IPackageFragment frag){ List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); try { result = Arrays.asList(frag.getCompilationUnits()); } catch (JavaModelException e) { e.printStackTrace(); } return result; } protected List<ICompilationUnit> get(IPackageFragmentRoot root){ List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); try { for (IJavaElement frag : Arrays.asList(root.getChildren())) { if( frag instanceof IPackageFragment ){ result.addAll(get((IPackageFragment) frag)); } } } catch (JavaModelException e) { e.printStackTrace(); } return result; } @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(Object o) { return list.contains(o); } @Override public Iterator<ICompilationUnit> iterator() { return list.iterator(); } @Override public Object[] toArray() { return list.toArray(); } @Override public <T> T[] toArray(T[] a) { return list.toArray(a); } @Override public boolean add(ICompilationUnit e) { return list.add(e); } @Override public boolean remove(Object o) { return list.remove(o); } @Override public boolean containsAll(Collection<?> c) { return list.contains(c); } @Override public boolean addAll(Collection<? extends ICompilationUnit> c) { return list.addAll(c); } @Override public boolean addAll(int index, Collection<? extends ICompilationUnit> c) { return list.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return list.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return list.retainAll(c); } @Override public void clear() { list.clear(); } @Override public ICompilationUnit get(int index) { return list.get(index); } @Override public ICompilationUnit set(int index, ICompilationUnit element) { return list.set(index, element); } @Override public void add(int index, ICompilationUnit element) { list.add(index, element); } @Override public ICompilationUnit remove(int index) { return list.remove(index); } @Override public int indexOf(Object o) { return list.indexOf(o); } @Override public int lastIndexOf(Object o) { return list.lastIndexOf(o); } @Override public ListIterator<ICompilationUnit> listIterator() { return list.listIterator(); } @Override public ListIterator<ICompilationUnit> listIterator(int index) { return list.listIterator(index); } @Override public List<ICompilationUnit> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } }
jesg/junit3Tojunit4
src/com/gowan/plugin/SelectionToICompilationUnitList.java
Java
gpl-3.0
5,321
/** * copyright * Inubit AG * Schoeneberger Ufer 89 * 10785 Berlin * Germany */ package com.inubit.research.textToProcess.textModel; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Rectangle2D; import net.frapu.code.visualization.ProcessNode; import net.frapu.code.visualization.ProcessUtils; import net.frapu.code.visualization.ProcessUtils.Orientation; /** * @author ff * */ public class WordNode extends ProcessNode { /** * */ public static final Color HIGHLIGHT_COLOR = new Color(255,255,224); private static final int PADDING = 3; //pixels /** * */ public WordNode(String word) { setText(word.replaceAll("\\/", "/")); setBackground(Color.WHITE); } /** * */ public WordNode() { // TODO Auto-generated constructor stub } @Override protected Shape getOutlineShape() { Rectangle2D outline = new Rectangle2D.Float(getPos().x - (getSize().width / 2), getPos().y - (getSize().height / 2), getSize().width, getSize().height); return outline; } @Override protected void paintInternal(Graphics g) { Graphics2D _g = (Graphics2D) g; Shape _s = getOutlineShape(); if(isSelected()) { _g.setColor(WordNode.HIGHLIGHT_COLOR); }else { _g.setColor(getBackground()); _g.setStroke(ProcessUtils.defaultStroke); } _g.fill(_s); _g.setColor(Color.LIGHT_GRAY); _g.draw(_s); _g.setColor(Color.BLACK); if(getText() == null) { ProcessUtils.drawText(_g, getPos().x, getPos().y, getSize().width, "Word", Orientation.CENTER); }else { ProcessUtils.drawText(_g, getPos().x, getPos().y, getSize().width, getText(), Orientation.CENTER); } } @Override public void setSize(int w, int h) { return; } @Override public void setPos(int x, int y) { return; } /** * @return */ public String getWord() { return getText(); } /** * @param stringBounds */ public void setBounds(Rectangle2D b) { super.setSize((int)b.getWidth() + 2* PADDING, (int)b.getHeight() + 2* PADDING); } /** * @param _wx * @param y */ public void setLocation(int x, int y) { super.setPos(x,y); } @Override public String toString() { return "WordNode ("+getText()+")"; } }
FabianFriedrich/Text2Process
src/com/inubit/research/textToProcess/textModel/WordNode.java
Java
gpl-3.0
2,249
/* * Neon, a roguelike engine. * Copyright (C) 2017-2018 - Maarten Driesen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package neon.editor.ui; import java.io.IOException; import java.util.logging.Logger; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.Window; import neon.common.files.NeonFileSystem; import neon.common.resources.ResourceManager; import neon.editor.LoadEvent; import neon.editor.controllers.CreatureHandler; import neon.editor.controllers.ItemHandler; import neon.editor.controllers.MapHandler; import neon.editor.controllers.MenuHandler; import neon.editor.controllers.TerrainHandler; import neon.editor.resource.CEditor; /** * The {@code UserInterface} takes care of most ui-related editor functionality. * * @author mdriesen * */ public final class UserInterface { private static final Logger logger = Logger.getGlobal(); private final CreatureHandler creatureHandler; private final MapHandler mapHandler; private final MenuHandler menuHandler; private final ItemHandler itemHandler; private final TerrainHandler terrainHandler; private Stage stage; private Scene scene; /** * Initializes the {@code UserInterface}. * * @param files * @param resources * @param bus * @param config */ public UserInterface(NeonFileSystem files, ResourceManager resources, EventBus bus, CEditor config) { // separate handlers for all the different ui elements menuHandler = new MenuHandler(resources, bus, this); bus.register(menuHandler); mapHandler = new MapHandler(resources, bus, config); bus.register(mapHandler); creatureHandler = new CreatureHandler(resources, bus); bus.register(creatureHandler); itemHandler = new ItemHandler(resources, bus); bus.register(itemHandler); terrainHandler = new TerrainHandler(resources, bus); bus.register(terrainHandler); // load the user interface FXMLLoader loader = new FXMLLoader(getClass().getResource("Editor.fxml")); loader.setControllerFactory(this::getController); try { scene = new Scene(loader.load()); scene.getStylesheets().add(getClass().getResource("editor.css").toExternalForm()); } catch (IOException e) { logger.severe("failed to load editor ui: " + e.getMessage()); } } /** * Returns the correct controller for a JavaFX node. * * @param type * @return */ private Object getController(Class<?> type) { if(type.equals(MenuHandler.class)) { return menuHandler; } else if (type.equals(MapHandler.class)) { return mapHandler; } else if (type.equals(CreatureHandler.class)) { return creatureHandler; } else if (type.equals(ItemHandler.class)) { return itemHandler; } else if (type.equals(TerrainHandler.class)) { return terrainHandler; } else { throw new IllegalArgumentException("No controller found for class " + type + "!"); } } /** * * @return the main window of the editor */ public Window getWindow() { return stage; } /** * Shows the main window on screen. * * @param stage */ public void start(Stage stage) { this.stage = stage; stage.setTitle("The Neon Roguelike Editor"); stage.setScene(scene); stage.setWidth(1440); stage.setMinWidth(800); stage.setHeight(720); stage.setMinHeight(600); stage.show(); stage.centerOnScreen(); stage.setOnCloseRequest(event -> System.exit(0)); } /** * Sets the title of the main window. * * @param event */ @Subscribe private void onModuleLoad(LoadEvent event) { stage.setTitle("The Neon Roguelike Editor - " + event.id); } /** * Checks if any resources are still opened and should be saved. This * method should be called when saving a module or exiting the editor. */ public void saveResources() { // check if any maps are still opened mapHandler.saveMaps(); } }
kosmonet/neon
src/neon/editor/ui/UserInterface.java
Java
gpl-3.0
4,700
package net.minecraft.server; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; // CraftBukkit start import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.SpawnerSpawnEvent; // CraftBukkit end public abstract class MobSpawnerAbstract { public int spawnDelay = 20; private String mobName = "Pig"; private List mobs; private TileEntityMobSpawnerData spawnData; public double c; public double d; private int minSpawnDelay = 200; private int maxSpawnDelay = 800; private int spawnCount = 4; private Entity j; private int maxNearbyEntities = 6; private int requiredPlayerRange = 16; private int spawnRange = 4; public MobSpawnerAbstract() {} public String getMobName() { if (this.i() == null) { if (this.mobName.equals("Minecart")) { this.mobName = "MinecartRideable"; } return this.mobName; } else { return this.i().c; } } public void setMobName(String s) { this.mobName = s; } public boolean f() { return this.a().findNearbyPlayer((double) this.b() + 0.5D, (double) this.c() + 0.5D, (double) this.d() + 0.5D, (double) this.requiredPlayerRange) != null; } public void g() { if (this.f()) { double d0; if (this.a().isStatic) { double d1 = (double) ((float) this.b() + this.a().random.nextFloat()); double d2 = (double) ((float) this.c() + this.a().random.nextFloat()); d0 = (double) ((float) this.d() + this.a().random.nextFloat()); this.a().addParticle("smoke", d1, d2, d0, 0.0D, 0.0D, 0.0D); this.a().addParticle("flame", d1, d2, d0, 0.0D, 0.0D, 0.0D); if (this.spawnDelay > 0) { --this.spawnDelay; } this.d = this.c; this.c = (this.c + (double) (1000.0F / ((float) this.spawnDelay + 200.0F))) % 360.0D; } else { if (this.spawnDelay == -1) { this.j(); } if (this.spawnDelay > 0) { --this.spawnDelay; return; } boolean flag = false; for (int i = 0; i < this.spawnCount; ++i) { Entity entity = EntityTypes.createEntityByName(this.getMobName(), this.a()); if (entity == null) { return; } int j = this.a().a(entity.getClass(), AxisAlignedBB.a((double) this.b(), (double) this.c(), (double) this.d(), (double) (this.b() + 1), (double) (this.c() + 1), (double) (this.d() + 1)).grow((double) (this.spawnRange * 2), 4.0D, (double) (this.spawnRange * 2))).size(); if (j >= this.maxNearbyEntities) { this.j(); return; } d0 = (double) this.b() + (this.a().random.nextDouble() - this.a().random.nextDouble()) * (double) this.spawnRange; double d3 = (double) (this.c() + this.a().random.nextInt(3) - 1); double d4 = (double) this.d() + (this.a().random.nextDouble() - this.a().random.nextDouble()) * (double) this.spawnRange; EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; entity.setPositionRotation(d0, d3, d4, this.a().random.nextFloat() * 360.0F, 0.0F); if (entityinsentient == null || entityinsentient.canSpawn()) { this.a(entity); this.a().triggerEffect(2004, this.b(), this.c(), this.d(), 0); if (entityinsentient != null) { entityinsentient.s(); } flag = true; } } if (flag) { this.j(); } } } } public Entity a(Entity entity) { if (this.i() != null) { NBTTagCompound nbttagcompound = new NBTTagCompound(); entity.d(nbttagcompound); Iterator iterator = this.i().b.c().iterator(); while (iterator.hasNext()) { String s = (String) iterator.next(); NBTBase nbtbase = this.i().b.get(s); nbttagcompound.set(s, nbtbase.clone()); } entity.f(nbttagcompound); if (entity.world != null) { // CraftBukkit start - call SpawnerSpawnEvent, abort if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity, this.b(), this.c(), this.d()); if (!event.isCancelled()) { entity.world.addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit // Spigot Start if ( entity.world.spigotConfig.nerfSpawnerMobs ) { entity.fromMobSpawner = true; } // Spigot End } // CraftBukkit end } NBTTagCompound nbttagcompound1; for (Entity entity1 = entity; nbttagcompound.hasKeyOfType("Riding", 10); nbttagcompound = nbttagcompound1) { nbttagcompound1 = nbttagcompound.getCompound("Riding"); Entity entity2 = EntityTypes.createEntityByName(nbttagcompound1.getString("id"), entity.world); if (entity2 != null) { NBTTagCompound nbttagcompound2 = new NBTTagCompound(); entity2.d(nbttagcompound2); Iterator iterator1 = nbttagcompound1.c().iterator(); while (iterator1.hasNext()) { String s1 = (String) iterator1.next(); NBTBase nbtbase1 = nbttagcompound1.get(s1); nbttagcompound2.set(s1, nbtbase1.clone()); } entity2.f(nbttagcompound2); entity2.setPositionRotation(entity1.locX, entity1.locY, entity1.locZ, entity1.yaw, entity1.pitch); // CraftBukkit start - call SpawnerSpawnEvent, skip if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity2, this.b(), this.c(), this.d()); if (event.isCancelled()) { continue; } if (entity.world != null) { entity.world.addEntity(entity2, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit } entity1.mount(entity2); } entity1 = entity2; } } else if (entity instanceof EntityLiving && entity.world != null) { ((EntityInsentient) entity).prepare((GroupDataEntity) null); // Spigot start - call SpawnerSpawnEvent, abort if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity, this.b(), this.c(), this.d()); if (!event.isCancelled()) { this.a().addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit // Spigot Start if ( entity.world.spigotConfig.nerfSpawnerMobs ) { entity.fromMobSpawner = true; } // Spigot End } // Spigot end } return entity; } private void j() { if (this.maxSpawnDelay <= this.minSpawnDelay) { this.spawnDelay = this.minSpawnDelay; } else { int i = this.maxSpawnDelay - this.minSpawnDelay; this.spawnDelay = this.minSpawnDelay + this.a().random.nextInt(i); } if (this.mobs != null && this.mobs.size() > 0) { this.a((TileEntityMobSpawnerData) WeightedRandom.a(this.a().random, (Collection) this.mobs)); } this.a(1); } public void a(NBTTagCompound nbttagcompound) { this.mobName = nbttagcompound.getString("EntityId"); this.spawnDelay = nbttagcompound.getShort("Delay"); if (nbttagcompound.hasKeyOfType("SpawnPotentials", 9)) { this.mobs = new ArrayList(); NBTTagList nbttaglist = nbttagcompound.getList("SpawnPotentials", 10); for (int i = 0; i < nbttaglist.size(); ++i) { this.mobs.add(new TileEntityMobSpawnerData(this, nbttaglist.get(i))); } } else { this.mobs = null; } if (nbttagcompound.hasKeyOfType("SpawnData", 10)) { this.a(new TileEntityMobSpawnerData(this, nbttagcompound.getCompound("SpawnData"), this.mobName)); } else { this.a((TileEntityMobSpawnerData) null); } if (nbttagcompound.hasKeyOfType("MinSpawnDelay", 99)) { this.minSpawnDelay = nbttagcompound.getShort("MinSpawnDelay"); this.maxSpawnDelay = nbttagcompound.getShort("MaxSpawnDelay"); this.spawnCount = nbttagcompound.getShort("SpawnCount"); } if (nbttagcompound.hasKeyOfType("MaxNearbyEntities", 99)) { this.maxNearbyEntities = nbttagcompound.getShort("MaxNearbyEntities"); this.requiredPlayerRange = nbttagcompound.getShort("RequiredPlayerRange"); } if (nbttagcompound.hasKeyOfType("SpawnRange", 99)) { this.spawnRange = nbttagcompound.getShort("SpawnRange"); } if (this.a() != null && this.a().isStatic) { this.j = null; } } public void b(NBTTagCompound nbttagcompound) { nbttagcompound.setString("EntityId", this.getMobName()); nbttagcompound.setShort("Delay", (short) this.spawnDelay); nbttagcompound.setShort("MinSpawnDelay", (short) this.minSpawnDelay); nbttagcompound.setShort("MaxSpawnDelay", (short) this.maxSpawnDelay); nbttagcompound.setShort("SpawnCount", (short) this.spawnCount); nbttagcompound.setShort("MaxNearbyEntities", (short) this.maxNearbyEntities); nbttagcompound.setShort("RequiredPlayerRange", (short) this.requiredPlayerRange); nbttagcompound.setShort("SpawnRange", (short) this.spawnRange); if (this.i() != null) { nbttagcompound.set("SpawnData", this.i().b.clone()); } if (this.i() != null || this.mobs != null && this.mobs.size() > 0) { NBTTagList nbttaglist = new NBTTagList(); if (this.mobs != null && this.mobs.size() > 0) { Iterator iterator = this.mobs.iterator(); while (iterator.hasNext()) { TileEntityMobSpawnerData tileentitymobspawnerdata = (TileEntityMobSpawnerData) iterator.next(); nbttaglist.add(tileentitymobspawnerdata.a()); } } else { nbttaglist.add(this.i().a()); } nbttagcompound.set("SpawnPotentials", nbttaglist); } } public boolean b(int i) { if (i == 1 && this.a().isStatic) { this.spawnDelay = this.minSpawnDelay; return true; } else { return false; } } public TileEntityMobSpawnerData i() { return this.spawnData; } public void a(TileEntityMobSpawnerData tileentitymobspawnerdata) { this.spawnData = tileentitymobspawnerdata; } public abstract void a(int i); public abstract World a(); public abstract int b(); public abstract int c(); public abstract int d(); }
pvginkel/Tweakkit-Server
src/main/java/net/minecraft/server/MobSpawnerAbstract.java
Java
gpl-3.0
11,945
package nest.util; import android.text.TextUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; import timber.log.Timber; public class TraceTree extends Timber.HollowTree { private final DebugTree debugTree; public TraceTree(boolean useTraces) { debugTree = new DebugTree(useTraces); } @Override public void v(String message, Object... args) { debugTree.v(message, args); } @Override public void v(Throwable t, String message, Object... args) { debugTree.v(t, message, args); } @Override public void d(String message, Object... args) { debugTree.d(message, args); } @Override public void d(Throwable t, String message, Object... args) { debugTree.d(t, message, args); } @Override public void i(String message, Object... args) { debugTree.i(message, args); } @Override public void i(Throwable t, String message, Object... args) { debugTree.i(t, message, args); } @Override public void w(String message, Object... args) { debugTree.w(message, args); } @Override public void w(Throwable t, String message, Object... args) { debugTree.w(t, message, args); } @Override public void e(String message, Object... args) { debugTree.e(message, args); } @Override public void e(Throwable t, String message, Object... args) { debugTree.e(t, message, args); } private static class DebugTree extends Timber.DebugTree { private static final Pattern ANONYMOUS_CLASS = Pattern.compile("\\$\\d+$"); private static final int STACK_POSITION = 6; private final boolean useTraces; private StackTraceElement lastTrace; private DebugTree(boolean useTraces) { this.useTraces = useTraces; } @Override protected String createTag() { String tag; if (!useTraces) { tag = nextTag(); if (tag != null) { return tag; } } StackTraceElement[] stackTrace = new Throwable().getStackTrace(); if (stackTrace.length < STACK_POSITION) { return "---"; } if (useTraces) { lastTrace = stackTrace[STACK_POSITION]; } tag = stackTrace[STACK_POSITION].getClassName(); Matcher m = ANONYMOUS_CLASS.matcher(tag); if (m.find()) { tag = m.replaceAll(""); } return tag.substring(tag.lastIndexOf('.') + 1); } @Override protected void logMessage(int priority, String tag, String message) { if (lastTrace != null) { message = (TextUtils.isEmpty(message) ? "" : message +" ") + "at "+ lastTrace; lastTrace = null; } super.logMessage(priority, tag, message); } } }
withoutuniverse/nest_tt
appko_tt/app/src/main/java/nest/util/TraceTree.java
Java
gpl-3.0
3,022
/* * Copyright (C) 2012 Carl Green * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package info.carlwithak.mpxg2.sysex.effects.algorithms; import info.carlwithak.mpxg2.model.effects.algorithms.DetuneStereo; /** * Class to parse parameter data for Detune (S) effect. * * @author Carl Green */ public class DetuneStereoParser { public static DetuneStereo parse(byte[] effectParameters) { DetuneStereo detuneStereo = new DetuneStereo(); int mix = effectParameters[0] + effectParameters[1] * 16; detuneStereo.mix.setValue(mix); int level = effectParameters[2] + effectParameters[3] * 16; detuneStereo.level.setValue(level); int tune = effectParameters[4] + effectParameters[5] * 16; detuneStereo.tune.setValue(tune); int optimize = effectParameters[6] + effectParameters[7] * 16; detuneStereo.optimize.setValue(optimize); int preDelay = effectParameters[8] + effectParameters[9] * 16; detuneStereo.preDelay.setValue(preDelay); return detuneStereo; } }
carlgreen/Lexicon-MPX-G2-Editor
mpxg2-sysex/src/main/java/info/carlwithak/mpxg2/sysex/effects/algorithms/DetuneStereoParser.java
Java
gpl-3.0
1,687
/* * Copyright 2014 Erik Wilson <erikwilson@magnorum.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.tritania.stables; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.Bukkit; import org.tritania.stables.Stables; import org.tritania.stables.util.Message; import org.tritania.stables.util.Log; public class RaceSystem { public Stables ht; public RaceSystem(Stables ht) { this.ht = ht; } }
tritania/Stables
src/main/java/org/tritania/stables/RaceSystem.java
Java
gpl-3.0
1,118
// This is a generated file. Not intended for manual editing. package org.modula.parsing.definition.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static org.modula.parsing.definition.psi.ModulaTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import org.modula.parsing.definition.psi.*; public class DefinitionFormalParametersImpl extends ASTWrapperPsiElement implements DefinitionFormalParameters { public DefinitionFormalParametersImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof DefinitionVisitor) ((DefinitionVisitor)visitor).visitFormalParameters(this); else super.accept(visitor); } @Override @NotNull public List<DefinitionFPSection> getFPSectionList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, DefinitionFPSection.class); } @Override @Nullable public DefinitionQualident getQualident() { return findChildByClass(DefinitionQualident.class); } }
miracelwhipp/idea-modula-support
ims-plugin/gen/org/modula/parsing/definition/psi/impl/DefinitionFormalParametersImpl.java
Java
gpl-3.0
1,213
package de.maxgb.vertretungsplan.manager; import android.content.Context; import android.os.AsyncTask; import de.maxgb.android.util.Logger; import de.maxgb.vertretungsplan.util.Constants; import de.maxgb.vertretungsplan.util.Stunde; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class StundenplanManager { public static final int BEGINN_NACHMITTAG = 8; public static final int ANZAHL_SAMSTAG = 4; public static final int ANZAHL_NACHMITTAG = 2; private static StundenplanManager instance; public static synchronized StundenplanManager getInstance(Context context) { if (instance == null) { instance = new StundenplanManager(context); } return instance; } private final String TAG = "StundenplanManager"; private int lastResult = 0; private ArrayList<Stunde[]> woche; private Context context; // Listener------------- private ArrayList<OnUpdateListener> listener = new ArrayList<OnUpdateListener>(); private StundenplanManager(Context context) { this.context = context; auswerten(); } public void asyncAuswerten() { AuswertenTask task = new AuswertenTask(); task.execute(); } public void auswerten() { lastResult = dateiAuswerten(); if (lastResult == -1) { } else { woche = null; } } public void auswertenWithNotify() { auswerten(); notifyListener(); } public ArrayList<Stunde[]> getClonedStundenplan() { if (woche == null) return null; ArrayList<Stunde[]> clone; try { clone = new ArrayList<Stunde[]>(woche.size()); for (Stunde[] item : woche) { Stunde[] clone2 = new Stunde[item.length]; for (int i = 0; i < item.length; i++) { clone2[i] = item[i].clone(); } clone.add(clone2); } return clone; } catch (NullPointerException e) { Logger.e(TAG, "Failed to clone stundenplan", e); return null; } } public String getLastResult() { switch (lastResult) { case -1: return "Erfolgreich ausgewertet"; case 1: return "Datei existiert nicht"; case 2: return "Kann Datei nicht lesen"; case 3: return "Zugriffsfehler"; case 4: return "Parsingfehler"; default: return "Noch nicht ausgewertet"; } } public ArrayList<Stunde[]> getStundenplan() { return woche; } public void notifyListener() { for (int i = 0; i < listener.size(); i++) { if (listener.get(i) != null) { listener.get(i).onStundenplanUpdate(); } } } public void registerOnUpdateListener(OnUpdateListener listener) { this.listener.add(listener); } public void unregisterOnUpdateListener(OnUpdateListener listener) { this.listener.remove(listener); } private Stunde[] convertJSONArrayToStundenArray(JSONArray tag) throws JSONException { Stunde[] result = new Stunde[BEGINN_NACHMITTAG - 1 + ANZAHL_NACHMITTAG]; for (int i = 0; i < BEGINN_NACHMITTAG - 1 + ANZAHL_NACHMITTAG; i++) { JSONArray stunde = tag.getJSONArray(i); if (i >= BEGINN_NACHMITTAG - 1) { result[i] = new Stunde(stunde.getString(0), stunde.getString(1), i + 1, stunde.getString(2)); } else { result[i] = new Stunde(stunde.getString(0), stunde.getString(1), i + 1); } } return result; } /** * Wertet die Stundenplandatei aus * * @return Fehlercode -1 bei Erfolg,1 Datei existiert nicht, 2 Datei kann nicht gelesen werden,3 Fehler beim Lesen,4 Fehler * beim Parsen * */ private int dateiAuswerten() { File loadoutFile = new File(context.getFilesDir(), Constants.SP_FILE_NAME); ArrayList<Stunde[]> w = new ArrayList<Stunde[]>(); if (!loadoutFile.exists()) { Logger.w(TAG, "Stundenplan file doesn´t exist"); return 1; } if (!loadoutFile.canRead()) { Logger.w(TAG, "Can´t read Stundenplan file"); return 2; } try { BufferedReader br = new BufferedReader(new FileReader(loadoutFile)); String line = br.readLine(); br.close(); JSONObject stundenplan = new JSONObject(line); JSONArray mo = stundenplan.getJSONArray("mo"); JSONArray di = stundenplan.getJSONArray("di"); JSONArray mi = stundenplan.getJSONArray("mi"); JSONArray d = stundenplan.getJSONArray("do"); JSONArray fr = stundenplan.getJSONArray("fr"); JSONObject sa = stundenplan.getJSONObject("sa"); // Samstag Stunde[] samstag = new Stunde[9]; JSONArray eins = sa.getJSONArray("0"); JSONArray zwei = sa.getJSONArray("1"); JSONArray drei = sa.getJSONArray("2"); JSONArray vier = sa.getJSONArray("3"); JSONArray acht = sa.getJSONArray("7"); JSONArray neun = sa.getJSONArray("8"); samstag[0] = new Stunde(eins.getString(0), eins.getString(1), 1); samstag[1] = new Stunde(zwei.getString(0), zwei.getString(1), 2); samstag[2] = new Stunde(drei.getString(0), drei.getString(1), 3); samstag[3] = new Stunde(vier.getString(0), vier.getString(1), 4); samstag[4] = new Stunde("", "", 5); samstag[5] = new Stunde("", "", 6); samstag[6] = new Stunde("", "", 7); samstag[7] = new Stunde(acht.getString(0), acht.getString(1), 8, acht.getString(2)); samstag[8] = new Stunde(neun.getString(0), neun.getString(1), 9, neun.getString(2)); w.add(convertJSONArrayToStundenArray(mo)); w.add(convertJSONArrayToStundenArray(di)); w.add(convertJSONArrayToStundenArray(mi)); w.add(convertJSONArrayToStundenArray(d)); w.add(convertJSONArrayToStundenArray(fr)); w.add(samstag); /* * for(int i=0;i<w.size();i++){ for(int j=0;j<w.get(i).length;j++){ System.out.println(w.get(i)[j].toString()); } } */ } catch (IOException e) { Logger.e(TAG, "Fehler beim Lesen der Datei", e); return 3; } catch (JSONException e) { Logger.e(TAG, "Fehler beim Parsen der Datei", e); return 4; } woche = w; return -1; } public interface OnUpdateListener { void onStundenplanUpdate(); } // ------------------------ private class AuswertenTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { auswerten(); return null; } @Override protected void onPostExecute(Void v) { notifyListener(); } } }
maxanier/Vertretungsplan
app/src/main/java/de/maxgb/vertretungsplan/manager/StundenplanManager.java
Java
mpl-2.0
6,174
package minejava.reg.util.concurrent; public interface RunnableFuture<V> extends Runnable, Future<V>{ @Override void run(); }
cFerg/MineJava
src/main/java/minejava/reg/util/concurrent/RunnableFuture.java
Java
mpl-2.0
135
package testtravis; import static org.junit.Assert.*; import org.junit.Test; public class Operar_unit { @Test public void testSumar() { System.out.println("Sumar dos numeros"); int numero1 = 6; int numero2 = 6; Operaciones instance = new Operaciones(); int expResult = 12; int result = instance.sumar(numero1, numero2); assertEquals(expResult, result); } @Test public void testRestar() { System.out.println("Restar dos numeros"); int numero1 = 4; int numero2 = 2; Operaciones instance = new Operaciones(); int expResult = 2; int result = instance.restar(numero1, numero2); assertEquals(expResult, result); } @Test public void testMultiplicar() { System.out.println("Multiplicar dos numeros"); int numero1 = 3; int numero2 =3; Operaciones instance = new Operaciones(); int expResult = 9; int result = instance.multiplicar(numero1, numero2); assertEquals(expResult, result); } @Test public void testDividir() { System.out.println("Dividir Dos numeros"); int numero1 = 6; int numero2 = 3; Operaciones instance = new Operaciones(); int expResult = 2; int result = instance.dividir(numero1, numero2); assertEquals(expResult, result); } }
nricaurte/prueba_degit
src/testtravis/Operar_unit.java
Java
mpl-2.0
1,428
/* * Copyright (c) 2014. The Trustees of Indiana University. * * This version of the code is licensed under the MPL 2.0 Open Source license with additional * healthcare disclaimer. If the user is an entity intending to commercialize any application * that uses this code in a for-profit venture, please contact the copyright holder. */ package com.muzima.api.model.algorithm; import com.muzima.api.model.PersonAttributeType; import com.muzima.search.api.model.object.Searchable; import com.muzima.util.JsonUtils; import net.minidev.json.JSONObject; import java.io.IOException; public class PersonAttributeTypeAlgorithm extends BaseOpenmrsAlgorithm { public static final String PERSON_ATTRIBUTE_TYPE_REPRESENTATION = "(uuid,name)"; private String uuid; /** * Implementation of this method will define how the object will be serialized from the String representation. * * @param serialized the string representation * @return the concrete object */ @Override public Searchable deserialize(final String serialized, final boolean isFullSerialization) throws IOException { PersonAttributeType attributeType = new PersonAttributeType(); attributeType.setUuid(JsonUtils.readAsString(serialized, "$['uuid']")); attributeType.setName(JsonUtils.readAsString(serialized, "$['name']")); return attributeType; } /** * Implementation of this method will define how the object will be de-serialized into the String representation. * * @param object the object * @return the string representation */ @Override public String serialize(final Searchable object, final boolean isFullSerialization) throws IOException { PersonAttributeType attributeType = (PersonAttributeType) object; JSONObject jsonObject = new JSONObject(); JsonUtils.writeAsString(jsonObject, "uuid", attributeType.getUuid()); JsonUtils.writeAsString(jsonObject, "name", attributeType.getName()); return jsonObject.toJSONString(); } }
sthaiya/muzima-api
src/main/java/com/muzima/api/model/algorithm/PersonAttributeTypeAlgorithm.java
Java
mpl-2.0
2,059
/** * Copyright 2017, Digi International Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.digi.xbee.api.packet.thread; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.*; import java.net.Inet6Address; import java.net.UnknownHostException; import java.util.Arrays; import java.util.LinkedHashMap; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.digi.xbee.api.models.CoAPURI; import com.digi.xbee.api.models.HTTPMethodEnum; import com.digi.xbee.api.models.RemoteATCommandOptions; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.thread.CoAPTxRequestPacket; import com.digi.xbee.api.utils.HexUtils; @PrepareForTest({Inet6Address.class, CoAPTxRequestPacket.class}) @RunWith(PowerMockRunner.class) public class CoAPTxRequestPacketTest { // Constants. private static final String IPV6_ADDRESS = "FDB3:0001:0002:0000:0004:0005:0006:0007"; // Variables. private int frameType = APIFrameType.COAP_TX_REQUEST.getValue(); private int frameID = 0x01; private int options = RemoteATCommandOptions.OPTION_NONE; private Inet6Address destAddress; private HTTPMethodEnum method = HTTPMethodEnum.GET; private String uriData = CoAPURI.URI_DATA_TRANSMISSION; private byte[] data = "Test".getBytes(); @Rule public ExpectedException exception = ExpectedException.none(); public CoAPTxRequestPacketTest() throws Exception { destAddress = (Inet6Address) Inet6Address.getByName(IPV6_ADDRESS); } /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { } /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#createPacket(byte[])}. * * <p>A {@code NullPointerException} exception must be thrown when parsing * a {@code null} byte array.</p> */ @Test public final void testCreatePacketNullPayload() { // Set up the resources for the test. byte[] payload = null; exception.expect(NullPointerException.class); exception.expectMessage(is(equalTo("CoAP Tx Request packet payload cannot be null."))); // Call the method under test that should throw a NullPointerException. CoAPTxRequestPacket.createPacket(payload); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#createPacket(byte[])}. * * <p>An {@code IllegalArgumentException} exception must be thrown when * parsing an empty byte array.</p> */ @Test public final void testCreatePacketEmptyPayload() { // Set up the resources for the test. byte[] payload = new byte[0]; exception.expect(IllegalArgumentException.class); exception.expectMessage(is(equalTo("Incomplete CoAP Tx Request packet."))); // Call the method under test that should throw an IllegalArgumentException. CoAPTxRequestPacket.createPacket(payload); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#createPacket(byte[])}. * * <p>An {@code IllegalArgumentException} exception must be thrown when * parsing a byte array shorter than the needed one is provided.</p> */ @Test public final void testCreatePacketPayloadShorterThanNeeded() { // Set up the resources for the test. byte[] payload = new byte[25]; payload[0] = (byte)frameType; payload[1] = (byte)frameID; payload[2] = (byte)options; payload[3] = (byte)method.getValue(); System.arraycopy(destAddress.getAddress(), 0, payload, 4, destAddress.getAddress().length); payload[20] = (byte)(uriData.length()); System.arraycopy(uriData.getBytes(), 0, payload, 21, uriData.getBytes().length - 1); exception.expect(IllegalArgumentException.class); exception.expectMessage(is(equalTo("Incomplete CoAP Tx Request packet."))); // Call the method under test that should throw an IllegalArgumentException. CoAPTxRequestPacket.createPacket(payload); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#createPacket(byte[])}. * * <p>An {@code IllegalArgumentException} exception must be thrown when * parsing a byte array not including the Frame type.</p> */ @Test public final void testCreatePacketPayloadNotIncludingFrameType() { // Set up the resources for the test. byte[] payload = new byte[25 + data.length]; payload[0] = (byte)frameID; payload[1] = (byte)options; payload[2] = (byte)method.getValue(); System.arraycopy(destAddress.getAddress(), 0, payload, 3, destAddress.getAddress().length); payload[20] = (byte)(uriData.length()); System.arraycopy(uriData.getBytes(), 0, payload, 20, uriData.getBytes().length); System.arraycopy(data, 0, payload, 20 + uriData.getBytes().length, data.length); exception.expect(IllegalArgumentException.class); exception.expectMessage(is(equalTo("Payload is not a CoAP Tx Request packet."))); // Call the method under test that should throw an IllegalArgumentException. CoAPTxRequestPacket.createPacket(payload); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#createPacket(byte[])}. * * <p>An {@code IllegalArgumentException} exception must be thrown when * parsing a byte array with an invalid IPv6 address.</p> */ @Test public final void testCreatePacketPayloadInvalidIP() throws Exception { // Set up the resources for the test. byte[] payload = new byte[26]; payload[0] = (byte)frameType; payload[1] = (byte)frameID; payload[2] = (byte)options; payload[3] = (byte)method.getValue(); System.arraycopy(destAddress.getAddress(), 0, payload, 4, destAddress.getAddress().length); payload[20] = (byte)(uriData.length()); System.arraycopy(uriData.getBytes(), 0, payload, 21, uriData.getBytes().length); PowerMockito.mockStatic(Inet6Address.class); PowerMockito.when(Inet6Address.getByAddress(Mockito.any(byte[].class))).thenThrow(new UnknownHostException()); exception.expect(IllegalArgumentException.class); // Call the method under test that should throw an IllegalArgumentException. CoAPTxRequestPacket.createPacket(payload); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#createPacket(byte[])}. * * <p>A valid CoAP TX Request packet with the provided options and without * data is created.</p> */ @Test public final void testCreatePacketValidPayloadWithoutData() { // Set up the resources for the test. byte[] payload = new byte[26]; payload[0] = (byte)frameType; payload[1] = (byte)frameID; payload[2] = (byte)options; payload[3] = (byte)method.getValue(); System.arraycopy(destAddress.getAddress(), 0, payload, 4, destAddress.getAddress().length); payload[20] = (byte)(uriData.length()); System.arraycopy(uriData.getBytes(), 0, payload, 21, uriData.getBytes().length); // Call the method under test. CoAPTxRequestPacket packet = CoAPTxRequestPacket.createPacket(payload); // Verify the result. assertThat("Returned length is not the expected one", packet.getPacketLength(), is(equalTo(payload.length))); assertThat("Returned frame ID is not the expected one", packet.getFrameID(), is(equalTo(frameID))); assertThat("Returned options are not the expected ones", packet.getTransmitOptions(), is(equalTo(options))); assertThat("Returned RESTul method is not the expected one", packet.getMethod(), is(equalTo(method))); assertThat("Returned dest address is not the expected one", packet.getDestAddress(), is(equalTo(destAddress))); assertThat("Returned URI is not the expected one", packet.getURI(), is(equalTo(uriData))); assertThat("Returned data is not the expected one", packet.getPayload(), is(nullValue())); assertThat("Returned payload array is not the expected one", packet.getPacketData(), is(equalTo(payload))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#createPacket(byte[])}. * * <p>A valid CoAP TX Request packet with the provided options and data is * created.</p> */ @Test public final void testCreatePacketValidPayloadWithData() { // Set up the resources for the test. byte[] payload = new byte[26 + data.length]; payload[0] = (byte)frameType; payload[1] = (byte)frameID; payload[2] = (byte)options; payload[3] = (byte)method.getValue(); System.arraycopy(destAddress.getAddress(), 0, payload, 4, destAddress.getAddress().length); payload[20] = (byte)(uriData.length()); System.arraycopy(uriData.getBytes(), 0, payload, 21, uriData.getBytes().length); System.arraycopy(data, 0, payload, 21 + uriData.getBytes().length, data.length); // Call the method under test. CoAPTxRequestPacket packet = CoAPTxRequestPacket.createPacket(payload); // Verify the result. assertThat("Returned length is not the expected one", packet.getPacketLength(), is(equalTo(payload.length))); assertThat("Returned frame ID is not the expected one", packet.getFrameID(), is(equalTo(frameID))); assertThat("Returned options are not the expected ones", packet.getTransmitOptions(), is(equalTo(options))); assertThat("Returned RESTul method is not the expected one", packet.getMethod(), is(equalTo(method))); assertThat("Returned dest address is not the expected one", packet.getDestAddress(), is(equalTo(destAddress))); assertThat("Returned URI is not the expected one", packet.getURI(), is(equalTo(uriData))); assertThat("Returned data is not the expected one", packet.getPayload(), is(equalTo(data))); assertThat("Returned payload array is not the expected one", packet.getPacketData(), is(equalTo(payload))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#CoAPTxRequestPacket(int, int, HTTPMethodEnum, Inet6Address, String, byte[])}. * * <p>Construct a new CoAP TX Request packet with a frame ID bigger than * 255. This must throw an {@code IllegalArgumentException}.</p> */ @Test public final void testCreateCoAPTxRequestPacketFrameIDBiggerThan255() { // Set up the resources for the test. int frameID = 524; exception.expect(IllegalArgumentException.class); exception.expectMessage(is(equalTo("Frame ID must be between 0 and 255."))); // Call the method under test that should throw an IllegalArgumentException. new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#CoAPTxRequestPacket(int, int, HTTPMethodEnum, Inet6Address, String, byte[])}. * * <p>Construct a new CoAP TX Request packet with a negative frame ID. This * must throw an {@code IllegalArgumentException}.</p> */ @Test public final void testCreateCoAPTxRequestPacketFrameIDNegative() { // Set up the resources for the test. int frameID = -6; exception.expect(IllegalArgumentException.class); exception.expectMessage(is(equalTo("Frame ID must be between 0 and 255."))); // Call the method under test that should throw an IllegalArgumentException. new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#CoAPTxRequestPacket(int, int, HTTPMethodEnum, Inet6Address, String, byte[])}. * * <p>Construct a new CoAP TX Request packet with invalid transmit options. * This must throw a {@code IllegalArgumentException}.</p> */ @Test public final void testCreateCoAPTxRequestPacketTransmitOptionsInvalid() { // Set up the resources for the test. int options = -1; exception.expect(IllegalArgumentException.class); exception.expectMessage(is(equalTo("Transmit options can only be " + RemoteATCommandOptions.OPTION_NONE + " or " + RemoteATCommandOptions.OPTION_APPLY_CHANGES + "."))); // Call the method under test that should throw a NullPointerException. new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#CoAPTxRequestPacket(int, int, HTTPMethodEnum, Inet6Address, String, byte[])}. * * <p>Construct a new CoAP TX Request packet with a null RESTful method. * This must throw a {@code NullPointerException}.</p> */ @Test public final void testCreateCoAPTxRequestPacketMethodNull() { // Set up the resources for the test. HTTPMethodEnum method = null; exception.expect(NullPointerException.class); exception.expectMessage(is(equalTo("HTTP Method cannot be null."))); // Call the method under test that should throw a NullPointerException. new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#CoAPTxRequestPacket(int, int, HTTPMethodEnum, Inet6Address, String, byte[])}. * * <p>Construct a new CoAP TX Request packet with a null destination * address. This must throw a {@code NullPointerException}.</p> */ @Test public final void testCreateCoAPTxRequestPacketDestAddressNull() { // Set up the resources for the test. Inet6Address destAddress = null; exception.expect(NullPointerException.class); exception.expectMessage(is(equalTo("Destination address cannot be null."))); // Call the method under test that should throw a NullPointerException. new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#CoAPTxRequestPacket(int, int, HTTPMethodEnum, Inet6Address, String, byte[])}. * * <p>Construct a new CoAP TX Request packet with a null URI. This must * throw a {@code NullPointerException}.</p> */ @Test public final void testCreateCoAPTxRequestPacketURINull() { // Set up the resources for the test. String uriData = null; exception.expect(NullPointerException.class); exception.expectMessage(is(equalTo("URI cannot be null."))); // Call the method under test that should throw a NullPointerException. new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#CoAPTxRequestPacket(int, int, HTTPMethodEnum, Inet6Address, String, byte[])}. * * <p>Construct a new CoAP TX Request packet without data ({@code null}).</p> */ @Test public final void testCreateCoAPTxRequestPacketValidDataNull() { // Set up the resources for the test. data = null; int expectedLength = 26; // Call the method under test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Verify the result. assertThat("Returned length is not the expected one", packet.getPacketLength(), is(equalTo(expectedLength))); assertThat("Returned frame ID is not the expected one", packet.getFrameID(), is(equalTo(frameID))); assertThat("Returned options are not the expected ones", packet.getTransmitOptions(), is(equalTo(options))); assertThat("Returned RESTul method is not the expected one", packet.getMethod(), is(equalTo(method))); assertThat("Returned dest address is not the expected one", packet.getDestAddress(), is(equalTo(destAddress))); assertThat("Returned URI is not the expected one", packet.getURI(), is(equalTo(uriData))); assertThat("Returned data is not the expected one", packet.getPayload(), is(nullValue())); assertThat("CoAP TX Request packet needs API Frame ID", packet.needsAPIFrameID(), is(equalTo(true))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#CoAPTxRequestPacket(int, int, HTTPMethodEnum, Inet6Address, String, byte[])}. * * <p>Construct a new CoAP TX Request packet with data.</p> */ @Test public final void testCreateCoAPTxRequestPacketValidDataNotNull() { // Set up the resources for the test. int expectedLength = 26 + data.length; // Call the method under test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Verify the result. assertThat("Returned length is not the expected one", packet.getPacketLength(), is(equalTo(expectedLength))); assertThat("Returned frame ID is not the expected one", packet.getFrameID(), is(equalTo(frameID))); assertThat("Returned options are not the expected ones", packet.getTransmitOptions(), is(equalTo(options))); assertThat("Returned RESTul method is not the expected one", packet.getMethod(), is(equalTo(method))); assertThat("Returned dest address is not the expected one", packet.getDestAddress(), is(equalTo(destAddress))); assertThat("Returned URI is not the expected one", packet.getURI(), is(equalTo(uriData))); assertThat("Returned data is not the expected one", packet.getPayload(), is(data)); assertThat("CoAP TX Request packet needs API Frame ID", packet.needsAPIFrameID(), is(equalTo(true))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#getAPIData()}. * * <p>Test the get API parameters with a {@code null} received data.</p> */ @Test public final void testGetAPIDataReceivedDataNull() { // Set up the resources for the test. byte[] data = null; CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); int expectedLength = 25; byte[] expectedData = new byte[expectedLength]; expectedData[0] = (byte)frameID; expectedData[1] = (byte)options; expectedData[2] = (byte)method.getValue(); System.arraycopy(destAddress.getAddress(), 0, expectedData, 3, destAddress.getAddress().length); expectedData[19] = (byte)(uriData.length()); System.arraycopy(uriData.getBytes(), 0, expectedData, 20, uriData.getBytes().length); // Call the method under test. byte[] apiData = packet.getAPIData(); // Verify the result. assertThat("API data is not the expected", apiData, is(equalTo(expectedData))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#getAPIData()}. * * <p>Test the get API parameters with a not-{@code null} received data.</p> */ @Test public final void testGetAPIDataReceivedDataNotNull() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); int expectedLength = 25 + data.length; byte[] expectedData = new byte[expectedLength]; expectedData[0] = (byte)frameID; expectedData[1] = (byte)options; expectedData[2] = (byte)method.getValue(); System.arraycopy(destAddress.getAddress(), 0, expectedData, 3, destAddress.getAddress().length); expectedData[19] = (byte)(uriData.length()); System.arraycopy(uriData.getBytes(), 0, expectedData, 20, uriData.getBytes().length); System.arraycopy(data, 0, expectedData, 20 + uriData.getBytes().length, data.length); // Call the method under test. byte[] apiData = packet.getAPIData(); // Verify the result. assertThat("API data is not the expected", apiData, is(equalTo(expectedData))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#getAPIPacketParameters()}. * * <p>Test the get API parameters with a {@code null} received data.</p> */ @Test public final void testGetAPIPacketParametersReceivedDataNull() { // Set up the resources for the test. byte[] data = null; CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Call the method under test. LinkedHashMap<String, String> packetParams = packet.getAPIPacketParameters(); // Verify the result. assertThat("Packet parameters map size is not the expected one", packetParams.size(), is(equalTo(6))); assertThat("Returned transmit options are not the expected ones", packetParams.get("Options"), is(equalTo(HexUtils.prettyHexString(HexUtils.integerToHexString(options, 1))))); assertThat("Returned HTTP method is not the expected one", packetParams.get("Method"), is(equalTo(HexUtils.prettyHexString(HexUtils.integerToHexString(method.getValue(), 1)) + " (" + method.getName() + ")"))); assertThat("Returned dest address is not the expected one", packetParams.get("Destination address"), is(equalTo(HexUtils.prettyHexString(destAddress.getAddress()) + " (" + destAddress.getHostAddress() + ")"))); assertThat("Returned URI length is not the expected one", packetParams.get("URI length"), is(equalTo(HexUtils.prettyHexString(HexUtils.integerToHexString(uriData.length(), 1)) + " (" + uriData.length() + ")"))); assertThat("Returned URI is not the expected one", packetParams.get("URI"), is(equalTo(HexUtils.prettyHexString(HexUtils.byteArrayToHexString(uriData.getBytes())) + " (" + uriData + ")"))); assertThat("RF data is not the expected", packetParams.get("RF data"), is(nullValue(String.class))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#getAPIPacketParameters()}. * * <p>Test the get API parameters with a not-{@code null} received data.</p> */ @Test public final void testGetAPIPacketParametersReceivedDataNotNull() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Call the method under test. LinkedHashMap<String, String> packetParams = packet.getAPIPacketParameters(); // Verify the result. assertThat("Packet parameters map size is not the expected one", packetParams.size(), is(equalTo(7))); assertThat("Returned transmit options are not the expected ones", packetParams.get("Options"), is(equalTo(HexUtils.prettyHexString(HexUtils.integerToHexString(options, 1))))); assertThat("Returned HTTP method is not the expected one", packetParams.get("Method"), is(equalTo(HexUtils.prettyHexString(HexUtils.integerToHexString(method.getValue(), 1)) + " (" + method.getName() + ")"))); assertThat("Returned dest address is not the expected one", packetParams.get("Destination address"), is(equalTo(HexUtils.prettyHexString(destAddress.getAddress()) + " (" + destAddress.getHostAddress() + ")"))); assertThat("Returned URI length is not the expected one", packetParams.get("URI length"), is(equalTo(HexUtils.prettyHexString(HexUtils.integerToHexString(uriData.length(), 1)) + " (" + uriData.length() + ")"))); assertThat("Returned URI is not the expected one", packetParams.get("URI"), is(equalTo(HexUtils.prettyHexString(HexUtils.byteArrayToHexString(uriData.getBytes())) + " (" + uriData + ")"))); assertThat("RF data is not the expected", packetParams.get("Payload"), is(equalTo(HexUtils.prettyHexString(HexUtils.byteArrayToHexString(data))))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setDestAddress(Inet6Address)}. */ @Test public final void testSetDestAddressNull() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); exception.expect(NullPointerException.class); exception.expectMessage(is(equalTo("Destination address cannot be null."))); // Call the method under test that should throw a NullPointerException. packet.setDestAddress(null); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setDestAddress(Inet6Address)}. * * @throws Exception */ @Test public final void testSetDestAddressNotNull() throws Exception { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); Inet6Address newAddress = (Inet6Address) Inet6Address.getByName("fd8a:cb11:ad71:0000:7662:c401:5efe:dc41"); // Call the method under test. packet.setDestAddress(newAddress); // Verify the result. assertThat("Dest address is not the expected one", packet.getDestAddress(), is(equalTo(newAddress))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setTransmitOptions(int)}. */ @Test public final void testSetTransmitOptionsATURIOptionsIllegal() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, CoAPURI.URI_AT_COMMAND, data); exception.expect(IllegalArgumentException.class); exception.expectMessage(is(equalTo("Transmit options can only be " + RemoteATCommandOptions.OPTION_NONE + " or " + RemoteATCommandOptions.OPTION_APPLY_CHANGES + "."))); // Call the method under test that should throw an IllegalArgumentException. packet.setTransmitOptions(0x03); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setTransmitOptions(int)}. */ @Test public final void testSetTransmitOptionsTXURIOptionsIllegal() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, CoAPURI.URI_DATA_TRANSMISSION, data); exception.expect(IllegalArgumentException.class); exception.expectMessage(is(equalTo("Transmit options can only be " + RemoteATCommandOptions.OPTION_NONE + " or " + RemoteATCommandOptions.OPTION_APPLY_CHANGES + "."))); // Call the method under test that should throw an IllegalArgumentException. packet.setTransmitOptions(0x02); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setTransmitOptions(int)}. */ @Test public final void testTransmitOptionsValid() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); int newOptions = 0x00; // Call the method under test. packet.setTransmitOptions(newOptions); // Verify the result. assertThat("Transmit options are not the expected ones", packet.getTransmitOptions(), is(equalTo(newOptions))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setMethod(HTTPMethodEnum)}. */ @Test public final void testSetMEthodNull() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); exception.expect(NullPointerException.class); exception.expectMessage(is(equalTo("HTTP Method cannot be null."))); // Call the method under test that should throw a NullPointerException. packet.setMethod(null); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setMethod(HTTPMethodEnum)}. */ @Test public final void testSetMethodNotNull() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); HTTPMethodEnum newMethod = HTTPMethodEnum.PUT; // Call the method under test. packet.setMethod(newMethod); // Verify the result. assertThat("HTTP method is not the expected one", packet.getMethod(), is(equalTo(newMethod))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#getPayload()}. */ @Test public final void testGetDataNullData() { // Set up the resources for the test. byte[] data = null; CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Call the method under test. byte[] result = packet.getPayload(); // Verify the result. assertThat("RF data must be the same", result, is(equalTo(data))); assertThat("RF data must be null", result, is(nullValue(byte[].class))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#getPayload()}. */ @Test public final void testGetDataValidData() { // Set up the resources for the test. CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Call the method under test. byte[] result = packet.getPayload(); // Verify the result. assertThat("Data must be the same", result, is(equalTo(data))); assertThat("Data must not be the same object", result.hashCode(), is(not(equalTo(data.hashCode())))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setPayload(byte[])}. */ @Test public final void testSetDataNullData() { // Set up the resources for the test. byte[] newData = null; CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Call the method under test. packet.setPayload(newData); byte[] result = packet.getPayload(); // Verify the result. assertThat("Data must be the same", result, is(equalTo(newData))); assertThat("Data must be null", result, is(nullValue(byte[].class))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setPayload(byte[])}. */ @Test public final void testSetDataValidData() { // Set up the resources for the test. byte[] newData = "New data".getBytes(); CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Call the method under test. packet.setPayload(newData); byte[] result = packet.getPayload(); // Verify the result. assertThat("Data must be the same", result, is(equalTo(newData))); } /** * Test method for {@link com.digi.xbee.api.packet.thread.CoAPTxRequestPacket#setPayload(byte[])}. */ @Test public final void testSetDataAndModifyOriginal() { // Set up the resources for the test. byte[] newData = "New data".getBytes(); CoAPTxRequestPacket packet = new CoAPTxRequestPacket(frameID, options, method, destAddress, uriData, data); // Call the method under test. packet.setPayload(newData); byte[] backup = Arrays.copyOf(newData, newData.length); newData[0] = 0x00; byte[] result = packet.getPayload(); // Verify the result. assertThat("Data must be the same as the setted data", result, is(equalTo(backup))); assertThat("Data must not be the current value of received data", result, is(not(equalTo(data)))); assertThat("Data must not be the same object", result.hashCode(), is(not(equalTo(backup.hashCode())))); assertThat("Data must not be the same object", result.hashCode(), is(not(equalTo(data.hashCode())))); } }
digidotcom/XBeeJavaLibrary
library/src/test/java/com/digi/xbee/api/packet/thread/CoAPTxRequestPacketTest.java
Java
mpl-2.0
31,725
/* * Copyright © 2013-2019, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.core.internal.configuration.tool; import com.google.common.base.Strings; import java.io.PrintStream; import org.fusesource.jansi.Ansi; import org.seedstack.shed.text.TextWrapper; class DetailPrinter { private static final TextWrapper textWrapper = new TextWrapper(120); private final PropertyInfo propertyInfo; DetailPrinter(PropertyInfo propertyInfo) { this.propertyInfo = propertyInfo; } void printDetail(PrintStream stream) { Ansi ansi = Ansi.ansi(); String title = "Details of " + propertyInfo.getName(); ansi .a(title) .newline() .a(Strings.repeat("-", title.length())) .newline().newline(); printSummary(propertyInfo, ansi); printDeclaration(propertyInfo, ansi); printLongDescription(propertyInfo, ansi); printAdditionalInfo(propertyInfo, ansi); ansi.newline(); stream.print(ansi.toString()); } private Ansi printSummary(PropertyInfo propertyInfo, Ansi ansi) { return ansi.a(propertyInfo.getShortDescription()).newline(); } private void printDeclaration(PropertyInfo propertyInfo, Ansi ansi) { ansi .newline() .a(" ") .fgBright(Ansi.Color.MAGENTA) .a(propertyInfo.getType()) .reset() .a(" ") .fgBright(Ansi.Color.BLUE) .a(propertyInfo.getName()) .reset(); Object defaultValue = propertyInfo.getDefaultValue(); if (defaultValue != null) { ansi .a(" = ") .fgBright(Ansi.Color.GREEN) .a(String.valueOf(defaultValue)) .reset(); } ansi .a(";") .newline(); } private void printLongDescription(PropertyInfo propertyInfo, Ansi ansi) { String longDescription = propertyInfo.getLongDescription(); if (longDescription != null) { ansi.newline().a(textWrapper.wrap(longDescription)).newline(); } } private void printAdditionalInfo(PropertyInfo propertyInfo, Ansi ansi) { if (propertyInfo.isMandatory() || propertyInfo.isSingleValue()) { ansi.newline(); } if (propertyInfo.isMandatory()) { ansi.a("* This property is mandatory.").newline(); } if (propertyInfo.isSingleValue()) { ansi.a("* This property is the default property of its declaring object").newline(); } } }
Sherpard/seed
core/src/main/java/org/seedstack/seed/core/internal/configuration/tool/DetailPrinter.java
Java
mpl-2.0
2,925
package com.storage.mywarehouse.Dao; import com.storage.mywarehouse.View.WarehouseProduct; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import java.util.List; public class WarehouseProductDAO { @SuppressWarnings("unchecked") public static List<WarehouseProduct> findById(int id) { Session session = NewHibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List products = session.createCriteria(WarehouseProduct.class) .add(Restrictions.eq("productId", id)) .list(); tx.commit(); session.close(); return products; } @SuppressWarnings("unchecked") public static List<WarehouseProduct> findByQuantity(int quantity) { Session session = NewHibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List emptyWarehouseProduct = session.createCriteria(WarehouseProduct.class) .add(Restrictions.eq("quantity", quantity)) .list(); tx.commit(); session.close(); return emptyWarehouseProduct; } @SuppressWarnings("unchecked") public static List<WarehouseProduct> findByParam(String param, String value) { Session session = NewHibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List products = session.createCriteria(WarehouseProduct.class) .add(Restrictions.eq(param.toLowerCase(), value)) .list(); tx.commit(); session.close(); return products; } @SuppressWarnings("unchecked") public static List<WarehouseProduct> findByParamContainingValue(String param, String value) { Session session = NewHibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); List products = session.createCriteria(WarehouseProduct.class) .add(Restrictions.like(param.toLowerCase(), "%" + value + "%")) .list(); tx.commit(); session.close(); return products; } }
patroklossam/WareHouse
src/main/java/com/storage/mywarehouse/Dao/WarehouseProductDAO.java
Java
mpl-2.0
2,222
package app.intelehealth.client.models.pushRequestApiCall; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Person { @SerializedName("uuid") @Expose private String uuid; @SerializedName("gender") @Expose private String gender; @SerializedName("names") @Expose private List<Name> names = null; @SerializedName("birthdate") @Expose private String birthdate; @SerializedName("attributes") @Expose private List<Attribute> attributes = null; @SerializedName("addresses") @Expose private List<Address> addresses = null; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public List<Name> getNames() { return names; } public void setNames(List<Name> names) { this.names = names; } public String getBirthdate() { return birthdate; } public void setBirthdate(String birthdate) { this.birthdate = birthdate; } public List<Attribute> getAttributes() { return attributes; } public void setAttributes(List<Attribute> attributes) { this.attributes = attributes; } public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } }
Intelehealth/Android-Mobile-Client
app/src/main/java/app/intelehealth/client/models/pushRequestApiCall/Person.java
Java
mpl-2.0
1,609
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.tests; import org.mozilla.javascript.Context; import org.mozilla.javascript.drivers.LanguageVersion; import org.mozilla.javascript.drivers.RhinoTest; import org.mozilla.javascript.drivers.ScriptTestsBase; @RhinoTest("testsrc/jstests/math-max-min-every-element-to-number.js") @LanguageVersion(Context.VERSION_DEFAULT) public class MathMaxMinEveryElementToNumber extends ScriptTestsBase { }
tuchida/rhino
testsrc/org/mozilla/javascript/tests/MathMaxMinEveryElementToNumber.java
Java
mpl-2.0
628
package com.opentrain.app; import android.test.InstrumentationTestCase; import com.opentrain.app.network.NetowrkManager; import java.util.concurrent.CountDownLatch; /** * Created by noam on 27/07/15. */ public class ServerRequestsTest extends InstrumentationTestCase { CountDownLatch countDownLatch = new CountDownLatch(1); public void test1GetMapFromServer() throws Throwable { NetowrkManager.getInstance().getMapFromServer(new NetowrkManager.RequestListener() { @Override public void onResponse(Object response) { assertNotNull(response); countDownLatch.countDown(); } @Override public void onError() { fail(); countDownLatch.countDown(); } }); countDownLatch.await(); } // public void test2AddMappingToServer() throws Throwable { // // Set<String> bssids = new HashSet<>(); // bssids.add("b4:c7:99:0b:aa:c1"); // bssids.add("b4:c7:99:0b:d4:90"); // String stationName = "StationNameTest"; // // Station station = new Station(bssids, System.currentTimeMillis()); // // NetowrkManager.getInstance().addMappingToServer(station.getPostParam(stationName), new NetowrkManager.RequestListener() { // @Override // public void onResponse(Object response) { // // assertNotNull(response); // countDownLatch.countDown(); // } // // @Override // public void onError() { // fail(); // countDownLatch.countDown(); // } // }); // // countDownLatch.await(); // } }
hasadna/OpenTrainApp
app/src/androidTest/java/com/opentrain/app/ServerRequestsTest.java
Java
mpl-2.0
1,726
package models.message; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import models.SecureTable; import org.codehaus.jackson.annotate.JsonProperty; import com.alvazan.orm.api.z8spi.meta.DboTableMeta; /** */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class StreamModule { @JsonProperty("module") @XmlElement(name="module") public String module; @JsonProperty("params") @XmlElement(name="params") public Map<String, String> params = new HashMap<String, String>(); //I want to do the composite pattern and push this field down into the "Container" while StreamModule is the "Component" of that pattern //but that would not work as unmarshalling the json would break since parser does not know to parse to StreamModule or the Container type which //I had previously called StreamAggregation so this field is only used for the Container type @JsonProperty("childStreams") @XmlElement(name="childStreams") public List<StreamModule> streams = new ArrayList<StreamModule>(); public String getModule() { return module; } public void setModule(String module) { this.module = module; } public Map<String, String> getParams() { return params; } public void setParams(Map<String, String> params) { this.params = params; } public List<StreamModule> getStreams() { return streams; } public void setStreams(List<StreamModule> streams) { this.streams = streams; } @Override public String toString() { return "module=" + module; } } // Register
deanhiller/databus
webapp/app/models/message/StreamModule.java
Java
mpl-2.0
1,764
package org.openlca.app.collaboration.navigation.actions; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.IDialogConstants; import org.openlca.app.M; import org.openlca.app.collaboration.dialogs.SelectCommitDialog; import org.openlca.app.collaboration.views.CompareView; import org.openlca.app.db.Repository; import org.openlca.app.navigation.actions.INavigationAction; import org.openlca.app.navigation.elements.INavigationElement; import org.openlca.app.rcp.images.Icon; import org.openlca.git.model.Commit; public class OpenCompareViewAction extends Action implements INavigationAction { private final boolean compareWithHead; private List<INavigationElement<?>> selection; public OpenCompareViewAction(boolean compareWithHead) { if (compareWithHead) { setText(M.HEADRevision); } else { setText(M.Commit + "..."); setImageDescriptor(Icon.COMPARE_COMMIT.descriptor()); } this.compareWithHead = compareWithHead; } @Override public void run() { Commit commit = null; if (compareWithHead) { commit = Repository.get().commits.head(); } else { SelectCommitDialog dialog = new SelectCommitDialog(); if (dialog.open() != IDialogConstants.OK_ID) return; commit = dialog.getSelection(); } CompareView.update(commit, selection); } @Override public boolean accept(List<INavigationElement<?>> selection) { if (!Repository.isConnected()) return false; this.selection = selection; return true; } }
GreenDelta/olca-app
olca-app/src/org/openlca/app/collaboration/navigation/actions/OpenCompareViewAction.java
Java
mpl-2.0
1,504
package main.origo.core.actions; import main.origo.core.event.NodeContext; import play.mvc.Action; import play.mvc.Http; import play.mvc.Result; import play.mvc.With; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @With(ContextAware.ContextAction.class) @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ContextAware { public static class ContextAction extends Action.Simple { @Override public Result call(Http.Context context) throws Throwable { try { NodeContext.set(); return delegate.call(context); } finally { NodeContext.clear(); } } } }
origocms/origo
modules/core/app/main/origo/core/actions/ContextAware.java
Java
mpl-2.0
811
package zyx.game.components.world.characters; import java.util.ArrayList; import org.lwjgl.util.vector.Matrix4f; import zyx.game.behavior.characters.CharacterAnimationBehavior; import zyx.game.behavior.player.OnlinePositionInterpolator; import zyx.game.components.AnimatedMesh; import zyx.game.components.GameObject; import zyx.game.components.IAnimatedMesh; import zyx.game.components.world.IItemHolder; import zyx.game.components.world.interactable.InteractionAction; import zyx.game.components.world.items.GameItem; import zyx.game.vo.CharacterType; import zyx.opengl.models.implementations.physics.PhysBox; public class GameCharacter extends GameObject implements IItemHolder { private static final ArrayList<InteractionAction> EMPTY_LIST = new ArrayList<>(); private static final ArrayList<InteractionAction> GUEST_LIST = new ArrayList<>(); static { GUEST_LIST.add(InteractionAction.TAKE_ORDER); } private AnimatedMesh mesh; public final CharacterInfo info; public GameCharacter() { info = new CharacterInfo(); mesh = new AnimatedMesh(); addChild(mesh); } public IAnimatedMesh getAnimatedMesh() { return mesh; } @Override public int getUniqueId() { return info.uniqueId; } public void load(CharacterSetupVo vo) { mesh.load("mesh.character"); setPosition(false, vo.pos); lookAt(vo.look); addBehavior(new OnlinePositionInterpolator(info)); addBehavior(new CharacterAnimationBehavior()); info.uniqueId = vo.id; info.name = vo.name; info.gender = vo.gender; info.type = vo.type; } @Override public void hold(GameItem item) { info.heldItem = item; mesh.addChildAsAttachment(item, "bone_carry"); } @Override public void removeItem(GameItem item) { if (info.heldItem != null) { mesh.removeChildAsAttachment(item); info.heldItem = null; } } @Override public boolean isInteractable() { if (info.type == CharacterType.GUEST) { return true; } return false; } @Override public PhysBox getPhysbox() { return mesh.getPhysbox(); } @Override public Matrix4f getMatrix() { return mesh.getMatrix(); } @Override public Matrix4f getBoneMatrix(int boneId) { return mesh.getBoneMatrix(boneId); } @Override public GameObject getWorldObject() { return this; } @Override public ArrayList<InteractionAction> getInteractions() { if (info.type == CharacterType.GUEST) { return GUEST_LIST; } else { return EMPTY_LIST; } } }
zyxakarene/LearningOpenGl
MainGame/src/zyx/game/components/world/characters/GameCharacter.java
Java
mpl-2.0
2,465
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (C) 2010, 2011, 2012, 2013 Pyravlos Team * * http://www.strabon.di.uoa.gr/ */ package org.openrdf.sail.postgis.evaluation; import java.sql.Types; import org.openrdf.sail.generaldb.evaluation.GeneralDBQueryBuilderFactory; import org.openrdf.sail.generaldb.evaluation.GeneralDBSqlCastBuilder; import org.openrdf.sail.generaldb.evaluation.GeneralDBSqlExprBuilder; public class PostGISSqlCastBuilder extends PostGISSqlExprBuilder implements GeneralDBSqlCastBuilder { protected GeneralDBSqlExprBuilder where; protected int jdbcType; public PostGISSqlCastBuilder(GeneralDBSqlExprBuilder where, GeneralDBQueryBuilderFactory factory, int jdbcType) { super(factory); this.where = where; this.jdbcType = jdbcType; append(" CAST("); } public GeneralDBSqlExprBuilder close() { append(" AS "); append(getSqlType(jdbcType)); append(")"); where.append(toSql()); where.addParameters(getParameters()); return where; } protected CharSequence getSqlType(int type) { switch (type) { case Types.VARCHAR: return "VARCHAR"; default: throw new AssertionError(type); } } }
wx1988/strabon
postgis/src/main/java/org/openrdf/sail/postgis/evaluation/PostGISSqlCastBuilder.java
Java
mpl-2.0
1,330
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.rules.rgaa42019; import org.tanaguru.entity.audit.TestSolution; import static org.tanaguru.rules.keystore.AttributeStore.ABSENT_ATTRIBUTE_VALUE; import static org.tanaguru.rules.keystore.AttributeStore.SRC_ATTR; import static org.tanaguru.rules.keystore.MarkerStore.DECORATIVE_IMAGE_MARKER; import static org.tanaguru.rules.keystore.MarkerStore.INFORMATIVE_IMAGE_MARKER; import org.apache.commons.lang3.tuple.ImmutablePair; import org.tanaguru.entity.audit.ProcessResult; import org.tanaguru.rules.keystore.HtmlElementStore; import org.tanaguru.rules.keystore.RemarkMessageStore; import org.tanaguru.rules.rgaa42019.test.Rgaa42019RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 1-8-2 of the referential Rgaa 4-2019. * * @author edaconceicao */ public class Rgaa42019Rule010802Test extends Rgaa42019RuleImplementationTestCase { /** * Default constructor */ public Rgaa42019Rule010802Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.tanaguru.rules.rgaa42019.Rgaa42019Rule010802"); } @Override protected void setUpWebResourceMap() { addWebResource("Rgaa42019.Test.01.08.02-3NMI-01", createParameter("Rules", INFORMATIVE_IMAGE_MARKER, "informative-image")); addWebResource("Rgaa42019.Test.01.08.02-4NA-01"); addWebResource("Rgaa42019.Test.01.08.02-4NA-02"); addWebResource("Rgaa42019.Test.01.08.02-4NA-03", createParameter("Rules", DECORATIVE_IMAGE_MARKER, "decorative-image")); } @Override protected void setProcess() { //---------------------------------------------------------------------- //------------------------------3NMI-01------------------------------ //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("Rgaa42019.Test.01.08.02-3NMI-01"); checkResultIsPreQualified(processResult, 2, 2); checkRemarkIsPresent( processResult, TestSolution.NEED_MORE_INFO, RemarkMessageStore.CHECK_TEXT_STYLED_PRESENCE_OF_INFORMATIVE_IMG_MSG, HtmlElementStore.INPUT_ELEMENT, 1, new ImmutablePair(SRC_ATTR, ABSENT_ATTRIBUTE_VALUE)); checkRemarkIsPresent( processResult, TestSolution.NEED_MORE_INFO, RemarkMessageStore.CHECK_NATURE_OF_IMAGE_AND_TEXT_STYLED_PRESENCE_MSG, HtmlElementStore.INPUT_ELEMENT, 2, new ImmutablePair(SRC_ATTR, ABSENT_ATTRIBUTE_VALUE)); //---------------------------------------------------------------------- //------------------------------4NA-01------------------------------ //---------------------------------------------------------------------- checkResultIsNotApplicable(processPageTest("Rgaa42019.Test.01.08.02-4NA-01")); //---------------------------------------------------------------------- //------------------------------4NA-02------------------------------ //---------------------------------------------------------------------- checkResultIsNotApplicable(processPageTest("Rgaa42019.Test.01.08.02-4NA-02")); //---------------------------------------------------------------------- //------------------------------4NA-03---------------------------------- //---------------------------------------------------------------------- checkResultIsNotApplicable(processPageTest("Rgaa42019.Test.01.08.02-4NA-03")); } // @Override // protected void setConsolidate() { // // // The consolidate method can be removed when real implementation is done. // // The assertions are automatically tested regarding the file names by // // the abstract parent class // assertEquals(TestSolution.NOT_TESTED, // consolidate("Rgaa4-2019.Test.1.8.2-3NMI-01").getValue()); //} }
Tanaguru/Tanaguru
rules/rgaa4-2019/src/test/java/org/tanaguru/rules/rgaa42019/Rgaa42019Rule010802Test.java
Java
agpl-3.0
4,980
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.mylinks.dao; import org.silverpeas.core.persistence.jdbc.sql.JdbcSqlQuery; import java.sql.SQLException; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; /** * @author silveryocha */ public class MyLinksDAOITUtil { private MyLinksDAOITUtil() { } static void assertLinkIds(final List<Integer> actualIds, final Integer... expectedIds) { if (expectedIds.length == 0) { assertThat(actualIds, empty()); } else { assertThat(actualIds, contains(expectedIds)); } } static List<Integer> getAllLinkIds() throws SQLException { return JdbcSqlQuery.createSelect("linkid") .from("SB_MyLinks_Link") .orderBy("linkid") .execute(r -> r.getInt(1)); } static void assertCategoryIds(final List<Integer> actualIds, final Integer... expectedIds) { if (expectedIds.length == 0) { assertThat(actualIds, empty()); } else { assertThat(actualIds, contains(expectedIds)); } } static List<Integer> getAllCategoryIds() throws SQLException { return JdbcSqlQuery.createSelect("catid") .from("SB_MyLinks_Cat") .orderBy("catid") .execute(r -> r.getInt(1)); } static void assertOfCouples(final List<String> actualCouples, final String... expectedCouples) { if (expectedCouples.length == 0) { assertThat(actualCouples, empty()); } else { assertThat(actualCouples, contains(expectedCouples)); } } static List<String> getAllOfCouples() throws SQLException { return JdbcSqlQuery.createSelect("*") .from("SB_MyLinks_LinkCat") .orderBy("catid, linkid") .execute(r -> r.getInt("catid") + "/" + r.getInt("linkid")); } }
SilverDav/Silverpeas-Core
core-services/mylinks/src/integration-test/java/org/silverpeas/core/mylinks/dao/MyLinksDAOITUtil.java
Java
agpl-3.0
2,953
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2008 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.syncml.client; import java.util.Enumeration; import java.util.Vector; import java.util.Date; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.funambol.sync.SyncItem; import com.funambol.sync.SourceConfig; import com.funambol.sync.SyncException; import com.funambol.sync.SyncAnchor; import com.funambol.sync.client.RawFileSyncSource; import com.funambol.sync.client.ChangesTracker; import com.funambol.syncml.protocol.SyncMLStatus; import com.funambol.platform.FileAdapter; import com.funambol.util.Log; import com.funambol.util.Base64; /** * An implementation of TrackableSyncSource, providing * the ability to sync briefcases (files). The source can handle both raw files * and OMA files (file objects). By default the source formats items according * to the OMA file object spec, but it is capable of receiving also raw files, * if their MIME type is not OMA file objects. */ public class FileSyncSource extends RawFileSyncSource { private static final String TAG_LOG = "FileSyncSource"; protected class FileSyncItem extends RawFileSyncItem { protected String prologue; protected String epilogue; public FileSyncItem(String fileName, String key) throws IOException { super(fileName, key, null, SyncItem.STATE_NEW, null); } public FileSyncItem(String fileName, String key, String type, char state, String parent) throws IOException { super(fileName, key, type, state, parent); FileAdapter file = new FileAdapter(fileName); if (SourceConfig.FILE_OBJECT_TYPE.equals(getType())) { // Initialize the prologue FileObject fo = new FileObject(); fo.setName(file.getName()); fo.setModified(new Date(file.lastModified())); prologue = fo.formatPrologue(); // Initialize the epilogue epilogue = fo.formatEpilogue(); // Compute the size of the FileObject int bodySize = Base64.computeEncodedSize((int)file.getSize()); // Set the size setObjectSize(prologue.length() + bodySize + epilogue.length()); } else { // The size is the raw file size setObjectSize(file.getSize()); } // Release the file object file.close(); } /** * Creates a new output stream to write to. If the item type is * FileDataObject, then the output stream takes care of parsing the XML * part of the object and it fills a FileObject that can be retrieved * later. @see FileObjectOutputStream for more details * Note that the output stream is unique, so that is can be reused * across different syncml messages. */ public OutputStream getOutputStream() throws IOException { if (os == null) { os = super.getOutputStream(); // If this item is a file object, we shall use the // FileObjectOutputStream if (SourceConfig.FILE_OBJECT_TYPE.equals(getType())) { FileObject fo = new FileObject(); os = new FileObjectOutputStream(fo, os); } } return os; } /** * Creates a new input stream to read from. If the source is configured * to handle File Data Object, then the stream returns the XML * description of the file. @see FileObjectInputStream for more details. */ public InputStream getInputStream() throws IOException { FileAdapter file = new FileAdapter(fileName); InputStream is = super.getInputStream(); // If this item is a file object, we shall use the // FileObjectOutputStream if (SourceConfig.FILE_OBJECT_TYPE.equals(getType())) { is = new FileObjectInputStream(prologue, is, epilogue, (int)file.getSize()); } return is; } // If we do not reimplement the getContent, it will return a null // content, but this is not used in the ss, so there's no need to // redefine it } protected String directory; protected String extensions[] = {}; //------------------------------------------------------------- Constructors /** * FileSyncSource constructor: initialize source config */ public FileSyncSource(SourceConfig config, ChangesTracker tracker, String directory) { super(config, tracker, directory); } protected void applyFileProperties(FileSyncItem fsi) throws IOException { OutputStream os = fsi.getOutputStream(); if (os instanceof FileObjectOutputStream) { FileObjectOutputStream foos = (FileObjectOutputStream)os; applyFileObjectProperties(fsi, foos); // The key for this item must be updated with the real // file name FileObject fo = foos.getFileObject(); String newName = fo.getName(); // The name is mandatory, but we try to be more robust here // and deal with items with no name if (newName != null) { fsi.setKey(directory + newName); } } } protected void applyFileObjectProperties(FileSyncItem fsi, FileObjectOutputStream foos) throws IOException { FileObject fo = foos.getFileObject(); String newName = fo.getName(); FileAdapter file = new FileAdapter(fsi.getFileName()); if (newName != null) { // Rename the file file.rename(directory + newName); } else { Log.error(TAG_LOG, "The received item does not have a valid name."); } file.close(); // Apply the modified date if present FileAdapter newFile = new FileAdapter(directory + newName); if (newFile != null) { Date lastModified = fo.getModified(); if (newFile.isSetLastModifiedSupported() && lastModified != null) { newFile.setLastModified(lastModified.getTime()); } newFile.close(); } } }
zjujunge/funambol
externals/java-sdk/syncml/src/main/java/com/funambol/syncml/client/FileSyncSource.java
Java
agpl-3.0
8,195
package io.fidelcoria.ayfmap.controller; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Component; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; @Component public class MainController { @FXML Label actionHeaderBar; @FXML TabPane actionTabPane; @FXML private GenerateTabController generateTabController; @FXML private ImportTabController importTabController; @FXML private DataTabController dataTabController; private static final Map<String, String> tabTitles; static { tabTitles = new HashMap<>(); tabTitles.put("generate-tab", "Generate Documents"); tabTitles.put("import-tab", "Import Documents"); tabTitles.put("edit-tab", "Edit Data"); } /** * Update the actionHeaderBar to reflect the selected tab */ public void tabClicked() { for (Tab tab : actionTabPane.getTabs()) { if (tab.isSelected()) { String title = tabTitles.get(tab.getId()); actionHeaderBar.setText(title); break; } } } }
fidelcoria/AYFM-Scheduling
AssignmentPlanner/src/main/java/io/fidelcoria/ayfmap/controller/MainController.java
Java
agpl-3.0
1,099
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2009. (c) 2009. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 4 $ * ************************************************************************ */ package ca.nrc.cadc.vos.server; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import ca.nrc.cadc.io.ByteCountInputStream; import ca.nrc.cadc.uws.JobInfo; import ca.nrc.cadc.uws.Parameter; import ca.nrc.cadc.uws.web.InlineContentException; import ca.nrc.cadc.uws.web.InlineContentHandler; import ca.nrc.cadc.uws.web.UWSInlineContentHandler; import ca.nrc.cadc.vos.Transfer; import ca.nrc.cadc.vos.TransferParsingException; import ca.nrc.cadc.vos.TransferReader; import ca.nrc.cadc.vos.TransferWriter; import ca.nrc.cadc.vos.VOSURI; public class TransferInlineContentHandler implements UWSInlineContentHandler { private static Logger log = Logger.getLogger(TransferInlineContentHandler.class); // 6Kb XML Doc size limit private static final long DOCUMENT_SIZE_MAX = 6144L; private static final String TEXT_XML = "text/xml"; public TransferInlineContentHandler() { } public Content accept(String name, String contentType, InputStream inputStream) throws InlineContentException, IOException { if (!contentType.equals(TEXT_XML)) throw new IllegalArgumentException("Transfer document expected Content-Type is " + TEXT_XML + " not " + contentType); if (inputStream == null) throw new IOException("The InputStream is closed"); // wrap the input stream in a byte counter to limit bytes read ByteCountInputStream sizeLimitInputStream = new ByteCountInputStream(inputStream, DOCUMENT_SIZE_MAX); try { TransferReader reader = new TransferReader(true); Transfer transfer = reader.read(sizeLimitInputStream, VOSURI.SCHEME); log.debug("Transfer: read " + sizeLimitInputStream.getByteCount() + " bytes."); TransferWriter tw = new TransferWriter(); StringWriter sw = new StringWriter(); tw.write(transfer, sw); Content content = new Content(); content.name = CONTENT_JOBINFO; content.value = new JobInfo(sw.toString(), contentType, true);; return content; } catch (TransferParsingException e) { throw new InlineContentException("Unable to create JobInfo from Transfer Document", e); } } }
opencadc/vos
cadc-vos-server/src/main/java/ca/nrc/cadc/vos/server/TransferInlineContentHandler.java
Java
agpl-3.0
6,452
/******************************************************************************* * This file is part of Termitaria, a project management tool * Copyright (C) 2008-2013 CodeSphere S.R.L., www.codesphere.ro * * Termitaria is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Termitaria. If not, see <http://www.gnu.org/licenses/> . ******************************************************************************/ package ro.cs.logaudit.entity; /** * @author matti_joona * */ public class Role { private int roleId; private String name; private String description; private String observation; private Module module; /** * @return the module */ public Module getModule() { return module; } /** * @param module the module to set */ public void setModule(Module module) { this.module = module; } /** * @return the roleId */ public int getRoleId() { return roleId; } /** * @param roleId the roleId to set */ public void setRoleId(int roleId) { this.roleId = roleId; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the observation */ public String getObservation() { return observation; } /** * @param observation the observation to set */ public void setObservation(String observation) { this.observation = observation; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuffer sb = new StringBuffer("["); sb.append(this.getClass().getSimpleName()); sb.append(": "); sb.append("roleId = ") .append(roleId) .append(", "); sb.append("name = ") .append(name) .append(", "); sb.append("description = ") .append(description).append(", "); sb.append("observation = ") .append(observation).append(", "); sb.append("module = ") .append(module) .append("]"); return sb.toString(); } }
CodeSphere/termitaria
TermitariaAudit/JavaSource/ro/cs/logaudit/entity/Role.java
Java
agpl-3.0
2,881
package de.dvdb.domain.model.social; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "dvdb2_fbsession") public class FacebookSession implements Serializable { private static final long serialVersionUID = -8753714944734959457L; private Long id; private String sessionKey; private Long user; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "user_id") public Long getUser() { return user; } public void setUser(Long user) { this.user = user; } @Column(name = "sessionkey") public String getSessionKey() { return sessionKey; } public void setSessionKey(String sessionKey) { this.sessionKey = sessionKey; } }
chris-dvdb/dvdb.de
dvdb-ejb/src/main/java/de/dvdb/domain/model/social/FacebookSession.java
Java
agpl-3.0
961
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2015 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import org.w3c.dom.Element; import com.kaltura.client.KalturaParams; import com.kaltura.client.KalturaApiException; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaUiConfAdminFilter extends KalturaUiConfAdminBaseFilter { public KalturaUiConfAdminFilter() { } public KalturaUiConfAdminFilter(Element node) throws KalturaApiException { super(node); } public KalturaParams toParams() throws KalturaApiException { KalturaParams kparams = super.toParams(); kparams.add("objectType", "KalturaUiConfAdminFilter"); return kparams; } }
moskiteau/KalturaGeneratedAPIClientsJava
src/main/java/com/kaltura/client/types/KalturaUiConfAdminFilter.java
Java
agpl-3.0
2,117
package cn.dlb.bim.ifc.engine.jvm; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.dlb.bim.component.PlatformServer; import cn.dlb.bim.component.PlatformServerConfig; import cn.dlb.bim.ifc.emf.PackageMetaData; import cn.dlb.bim.ifc.engine.IRenderEngine; import cn.dlb.bim.ifc.engine.IRenderEngineFactory; import cn.dlb.bim.ifc.engine.RenderEngineException; import cn.dlb.bim.utils.PathUtils; public class JvmRenderEngineFactory implements IRenderEngineFactory { private static final Logger LOGGER = LoggerFactory.getLogger(JvmRenderEngineFactory.class); private Path nativeFolder; private Path schemaFile; private PlatformServer server; public JvmRenderEngineFactory(PlatformServer server) { this.server = server; initialize(); } public void initialize() { try { String os = System.getProperty("os.name").toLowerCase(); String libraryName = ""; if (os.contains("windows")) { libraryName = "ifcengine.dll"; } else if (os.contains("osx") || os.contains("os x") || os.contains("darwin")) { libraryName = "libIFCEngine.dylib"; } else if (os.contains("linux")) { libraryName = "libifcengine.so"; } InputStream inputStream = Files.newInputStream(server.getPlatformServerConfig().getCompileClassRoute().resolve("lib/" + System.getProperty("sun.arch.data.model") + "/" + libraryName)); if (inputStream != null) { try { Path tmpFolder = server.getPlatformServerConfig().getTempDir(); nativeFolder = tmpFolder.resolve("ifcenginedll"); Path file = nativeFolder.resolve(libraryName); if (Files.exists(nativeFolder)) { try { PathUtils.removeDirectoryWithContent(nativeFolder); } catch (IOException e) { // Ignore } } Files.createDirectories(nativeFolder); OutputStream outputStream = Files.newOutputStream(file); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); } } finally { inputStream.close(); } } } catch (Exception e) { e.printStackTrace(); } } @Override public IRenderEngine createRenderEngine(String schema) throws RenderEngineException { try { PackageMetaData packageMetaData = server.getMetaDataManager().getPackageMetaData(schema); schemaFile = packageMetaData.getSchemaPath(); if (schemaFile == null) { throw new RenderEngineException("No schema file"); } List<String> classPathEntries = new ArrayList<>(); // for (Dependency dependency : pluginContext.getDependencies()) { // Path path = dependency.getPath(); // classPathEntries.add(path.toAbsolutePath().toString()); // } return new JvmIfcEngine(schemaFile, nativeFolder, server.getPlatformServerConfig().getTempDir(), server.getPlatformServerConfig().getClassPath() , classPathEntries); } catch (RenderEngineException e) { throw e; } } }
shenan4321/BIMplatform
src/cn/dlb/bim/ifc/engine/jvm/JvmRenderEngineFactory.java
Java
agpl-3.0
3,114
/* * Copyright 2015 Erwin Müller <erwin.mueller@deventm.org> * * This file is part of sscontrol-httpd-yourls. * * sscontrol-httpd-yourls is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * sscontrol-httpd-yourls is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with sscontrol-httpd-yourls. If not, see <http://www.gnu.org/licenses/>. */ package com.anrisoftware.sscontrol.httpd.yourls; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.ACCESS_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.API_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.BACKUP_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.CONVERT_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.DATABASE_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.DEBUG_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.DRIVER_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.GMT_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.HOST_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.LANGUAGE_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.MODE_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.OFFSET_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.OVERRIDE_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.PASSWORD_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.PORT_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.PREFIX_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.RESERVED_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.SITE_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.STATS_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.TARGET_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.UNIQUE_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.URLS_KEY; import static com.anrisoftware.sscontrol.httpd.yourls.YourlsServiceStatement.USER_KEY; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import com.anrisoftware.sscontrol.core.api.ServiceException; import com.anrisoftware.sscontrol.core.groovy.statementsmap.StatementsException; import com.anrisoftware.sscontrol.core.groovy.statementsmap.StatementsMap; import com.anrisoftware.sscontrol.core.groovy.statementstable.StatementsTable; import com.anrisoftware.sscontrol.core.groovy.statementstable.StatementsTableFactory; import com.anrisoftware.sscontrol.core.overridemode.OverrideMode; import com.anrisoftware.sscontrol.core.yesno.YesNoFlag; import com.anrisoftware.sscontrol.httpd.domain.Domain; import com.anrisoftware.sscontrol.httpd.webserviceargs.DefaultWebService; import com.anrisoftware.sscontrol.httpd.webserviceargs.DefaultWebServiceFactory; import com.google.inject.assistedinject.Assisted; /** * <i>Yourls</i> service. * * @see <a href="http://yourls.org/>http://yourls.org/</a> * * @author Erwin Mueller, erwin.mueller@deventm.org * @since 1.0 */ class YourlsServiceImpl implements YourlsService { /** * The <i>Yourls</i> service name. */ public static final String SERVICE_NAME = "yourls"; private final DefaultWebService service; private final StatementsMap statementsMap; private StatementsTable statementsTable; /** * @see YourlsServiceFactory#create(Map, Domain) */ @Inject YourlsServiceImpl(DefaultWebServiceFactory webServiceFactory, @Assisted Map<String, Object> args, @Assisted Domain domain) { this.service = webServiceFactory.create(SERVICE_NAME, args, domain); this.statementsMap = service.getStatementsMap(); setupStatements(statementsMap, args); } private void setupStatements(StatementsMap map, Map<String, Object> args) { map.addAllowed(DATABASE_KEY, OVERRIDE_KEY, BACKUP_KEY, ACCESS_KEY, USER_KEY, GMT_KEY, UNIQUE_KEY, CONVERT_KEY, RESERVED_KEY, SITE_KEY, LANGUAGE_KEY); map.setAllowValue(true, DATABASE_KEY, ACCESS_KEY, RESERVED_KEY, SITE_KEY, LANGUAGE_KEY); map.addAllowedKeys(DATABASE_KEY, USER_KEY, PASSWORD_KEY, HOST_KEY, PORT_KEY, PREFIX_KEY, DRIVER_KEY); map.addAllowedKeys(OVERRIDE_KEY, MODE_KEY); map.addAllowedKeys(BACKUP_KEY, TARGET_KEY); map.addAllowedKeys(ACCESS_KEY, STATS_KEY, API_KEY); map.addAllowedKeys(GMT_KEY, OFFSET_KEY); map.addAllowedKeys(UNIQUE_KEY, URLS_KEY); map.addAllowedKeys(CONVERT_KEY, MODE_KEY); } @Inject public final void setStatementsTable(StatementsTableFactory factory) { StatementsTable table = factory.create(this, SERVICE_NAME); table.addAllowed(DEBUG_KEY, USER_KEY); table.setAllowArbitraryKeys(true, DEBUG_KEY); table.addAllowedKeys(USER_KEY, PASSWORD_KEY); this.statementsTable = table; } @Override public Domain getDomain() { return service.getDomain(); } @Override public String getName() { return SERVICE_NAME; } public void setAlias(String alias) throws ServiceException { service.setAlias(alias); } @Override public String getAlias() { return service.getAlias(); } public void setId(String id) throws ServiceException { service.setId(id); } @Override public String getId() { return service.getId(); } public void setRef(String ref) throws ServiceException { service.setRef(ref); } @Override public String getRef() { return service.getRef(); } public void setRefDomain(String ref) throws ServiceException { service.setRefDomain(ref); } @Override public String getRefDomain() { return service.getRefDomain(); } public void setPrefix(String prefix) throws ServiceException { service.setPrefix(prefix); } @Override public String getPrefix() { return service.getPrefix(); } @Override public Map<String, Object> debugLogging(String key) { return statementsTable.tableKeys(DEBUG_KEY, key); } @Override public Map<String, Object> getDatabase() { @SuppressWarnings("serial") Map<String, Object> map = new HashMap<String, Object>() { @Override public Object put(String key, Object value) { if (value != null) { return super.put(key, value); } else { return null; } } }; StatementsMap m = statementsMap; map.put(DATABASE_KEY.toString(), m.value(DATABASE_KEY)); map.put(USER_KEY.toString(), m.mapValue(DATABASE_KEY, USER_KEY)); map.put(PASSWORD_KEY.toString(), m.mapValue(DATABASE_KEY, PASSWORD_KEY)); map.put(HOST_KEY.toString(), m.mapValue(DATABASE_KEY, HOST_KEY)); map.put(PORT_KEY.toString(), m.mapValue(DATABASE_KEY, PORT_KEY)); map.put(PREFIX_KEY.toString(), m.mapValue(DATABASE_KEY, PREFIX_KEY)); map.put(DRIVER_KEY.toString(), m.mapValue(DATABASE_KEY, DRIVER_KEY)); return map.size() == 0 ? null : map; } @Override public OverrideMode getOverrideMode() { return statementsMap.mapValue(OVERRIDE_KEY, MODE_KEY); } @Override public URI getBackupTarget() { return statementsMap.mapValueAsURI(BACKUP_KEY, TARGET_KEY); } @Override public Access getSiteAccess() { return statementsMap.value(ACCESS_KEY); } @Override public Access getStatsAccess() { return statementsMap.mapValue(ACCESS_KEY, STATS_KEY); } @Override public Access getApiAccess() { return statementsMap.mapValue(ACCESS_KEY, API_KEY); } @Override public Integer getGmtOffset() { return statementsMap.mapValue(GMT_KEY, OFFSET_KEY); } @Override public Boolean getUniqueUrls() { Object value = statementsMap.mapValue(UNIQUE_KEY, URLS_KEY); if (value instanceof YesNoFlag) { return ((YesNoFlag) value).asBoolean(); } else { return (Boolean) value; } } @Override public Convert getUrlConvertMode() { return statementsMap.mapValue(CONVERT_KEY, MODE_KEY); } @Override public List<String> getReserved() { return statementsMap.valueAsStringList(RESERVED_KEY); } @Override public String getLanguage() { return statementsMap.value(LANGUAGE_KEY); } @Override public Map<String, String> getUsers() { return statementsTable.tableKeys(USER_KEY, PASSWORD_KEY); } @Override public String getSite() { return statementsMap.value(SITE_KEY); } public Object methodMissing(String name, Object args) { try { return service.methodMissing(name, args); } catch (StatementsException e) { return statementsTable.methodMissing(name, args); } } @Override public String toString() { return service.toString(); } }
devent/sscontrol
sscontrol-httpd-yourls/src/main/java/com/anrisoftware/sscontrol/httpd/yourls/YourlsServiceImpl.java
Java
agpl-3.0
10,069
/* * This file is part of ELKI: * Environment for Developing KDD-Applications Supported by Index-Structures * * Copyright (C) 2019 * ELKI Development Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package elki.utilities.datastructures; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Random; import org.junit.Test; /** * Test the Kuhn-Munkres implementation. * * @author Erich Schubert */ public class KuhnMunkresWongTest { @Test public void test1() { int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.TEST1); double sum = 0.; for(int i = 0; i < assignment.length; i++) { assertTrue("Unassigned row " + i, assignment[i] >= 0); sum += KuhnMunkresTest.TEST1[i][assignment[i]]; } assertEquals("Assignment not optimal", 55, sum, 0); } @Test public void test2() { int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.TEST2); double sum = 0.; for(int i = 0; i < assignment.length; i++) { assertTrue("Unassigned row " + i, assignment[i] >= 0); sum += KuhnMunkresTest.TEST2[i][assignment[i]]; } assertEquals("Assignment not optimal", 4, sum, 0); } @Test public void testNonSq() { int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.NONSQUARE); double sum = 0.; for(int i = 0; i < assignment.length; i++) { assertTrue("Unassigned row " + i, assignment[i] >= 0); sum += KuhnMunkresTest.NONSQUARE[i][assignment[i]]; } assertEquals("Assignment not optimal", 637518, sum, 0); } @Test public void testDifficult() { int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.DIFFICULT); double sum = 0.; for(int i = 0; i < assignment.length; i++) { assertTrue("Unassigned row " + i, assignment[i] >= 0); sum += KuhnMunkresTest.DIFFICULT[i][assignment[i]]; } assertEquals("Assignment not optimal", 2.24, sum, 1e-4); } @Test public void testDifficult2() { int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.DIFFICULT2); double sum = 0.; for(int i = 0; i < assignment.length; i++) { assertTrue("Unassigned row " + i, assignment[i] >= 0); sum += KuhnMunkresTest.DIFFICULT2[i][assignment[i]]; } assertEquals("Assignment not optimal", 0.8802, sum, 1e-4); } @Test public void testLarge() { long seed = 0L; Random rnd = new Random(seed); double[][] mat = new double[100][100]; for(int i = 0; i < mat.length; i++) { double[] row = mat[i]; for(int j = 0; j < row.length; j++) { row[j] = Math.abs(rnd.nextDouble()); } } int[] assignment = new KuhnMunkresWong().run(mat); double sum = 0.; for(int i = 0; i < assignment.length; i++) { assertTrue("Unassigned row " + i, assignment[i] >= 0); sum += mat[i][assignment[i]]; } if(seed == 0) { if(mat.length == 10 && mat[0].length == 10) { assertEquals("sum", 1.467733381753002, sum, 1e-8); // Duration: 0.007970609 } if(mat.length == 100 && mat[0].length == 100) { assertEquals("sum", 1.5583906418867581, sum, 1e-8); // Duration: 0.015696813 } if(mat.length == 1000 && mat[0].length == 1000) { assertEquals("sum", 1.6527526146559663, sum, 1e-8); // Duration: 0.8892345580000001 } if(mat.length == 10000 && mat[0].length == 10000) { assertEquals("sum", 1.669458072091596, sum, 1e-8); // Duration: 3035.95495334 } } } }
elki-project/elki
elki-core-util/src/test/java/elki/utilities/datastructures/KuhnMunkresWongTest.java
Java
agpl-3.0
4,174
/** * @(#)MediaExportParameters.java * * This file is part of the Non-Linear Book project. * Copyright (c) 2012-2016 Anton P. Kolosov * Authors: Anton P. Kolosov, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ANTON P. KOLOSOV. ANTON P. KOLOSOV DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the Non-Linear Book software without * disclosing the source code of your own applications. * * For more information, please contact Anton P. Kolosov at this * address: antokolos@gmail.com * * Copyright (c) 2012 Anton P. Kolosov All rights reserved. */ package com.nlbhub.nlb.domain; import com.nlbhub.nlb.api.PropertyManager; /** * The MediaExportParameters class represents parameters used when saving media files during export of the scheme * to some end format (such as INSTEAD game). * * @author Anton P. Kolosov * @version 1.0 8/9/12 */ public class MediaExportParameters { public enum Preset {CUSTOM, DEFAULT, NOCHANGE, COMPRESSED}; private static final MediaExportParameters NOCHANGE = new MediaExportParameters(Preset.NOCHANGE, false, 0); private static final MediaExportParameters COMPRESSED = new MediaExportParameters(Preset.COMPRESSED, true, 80); private static final MediaExportParameters DEFAULT = ( new MediaExportParameters( Preset.DEFAULT, PropertyManager.getSettings().getDefaultConfig().getExport().isConvertpng2jpg(), PropertyManager.getSettings().getDefaultConfig().getExport().getQuality() ) ); private Preset m_preset = Preset.CUSTOM; private boolean m_convertPNG2JPG; private int m_quality; public static MediaExportParameters fromPreset(Preset preset) { switch (preset) { case NOCHANGE: return MediaExportParameters.NOCHANGE; case COMPRESSED: return MediaExportParameters.COMPRESSED; default: return MediaExportParameters.DEFAULT; } } public static MediaExportParameters getDefault() { return DEFAULT; } /* public MediaExportParameters(boolean convertPNG2JPG, int quality) { m_preset = Preset.CUSTOM; m_convertPNG2JPG = convertPNG2JPG; m_quality = quality; } */ private MediaExportParameters(Preset preset, boolean convertPNG2JPG, int quality) { m_preset = preset; m_convertPNG2JPG = convertPNG2JPG; m_quality = quality; } public Preset getPreset() { return m_preset; } public boolean isConvertPNG2JPG() { return m_convertPNG2JPG; } public int getQuality() { return m_quality; } }
Antokolos/NLB
NLBL/src/main/java/com/nlbhub/nlb/domain/MediaExportParameters.java
Java
agpl-3.0
3,959
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2020 Asqatasun.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa30; import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation; /** * Implementation of the rule 1.10.1 of the referential Rgaa 3.0. * * For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.0/01.Images/Rule-1-10-1.html">the rule 1.10.1 design page.</a> * @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-1-10-1"> 1.10.1 rule specification</a> */ public class Rgaa30Rule011001 extends AbstractNotTestedRuleImplementation { /** * Default constructor */ public Rgaa30Rule011001 () { super(); } }
Asqatasun/Asqatasun
rules/rules-rgaa3.0/src/main/java/org/asqatasun/rules/rgaa30/Rgaa30Rule011001.java
Java
agpl-3.0
1,487
/* * Fluffy Meow - Torrent RSS generator for TV series * Copyright (C) 2015 Victor Denisov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.plukh.fluffymeow.aws; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeTagsRequest; import com.amazonaws.services.ec2.model.DescribeTagsResult; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.TagDescription; import org.apache.http.client.fluent.Request; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; public class AWSInstanceInfoProviderImpl implements InstanceInfoProvider { private static final Logger log = LogManager.getLogger(AWSInstanceInfoProviderImpl.class); private static final String NAME_TAG = "Name"; private static final String DEPLOYMENT_ID_TAG = "deploymentId"; private InstanceInfo instanceInfo; public AWSInstanceInfoProviderImpl() { } @Override public InstanceInfo getInstanceInfo() { if (instanceInfo == null) { try { AmazonEC2 ec2 = new AmazonEC2Client(); String instanceId = Request.Get("http://169.254.169.254/latest/meta-data/instance-id").execute().returnContent().asString(); if (log.isDebugEnabled()) log.debug("Instance Id: " + instanceId); DescribeTagsRequest tagsRequest = new DescribeTagsRequest().withFilters( new Filter().withName("resource-id").withValues(instanceId), new Filter().withName("key").withValues(NAME_TAG, DEPLOYMENT_ID_TAG)); DescribeTagsResult tagsResult = ec2.describeTags(tagsRequest); String name = getTag(tagsResult, NAME_TAG); if (log.isDebugEnabled()) log.debug("Instance name: " + name); String deploymentId = getTag(tagsResult, DEPLOYMENT_ID_TAG); if (log.isDebugEnabled()) log.debug("Deployment: " + deploymentId); instanceInfo = new InstanceInfo() .withInstanceId(instanceId) .withName(name) .withDeploymentId(deploymentId); } catch (IOException e) { throw new AWSInstanceInfoException("Error retrieving AWS instance info", e); } } return instanceInfo; } private String getTag(DescribeTagsResult tagsResult, String tagName) { for (TagDescription tag : tagsResult.getTags()) { if (tag.getKey().equals(tagName)) return tag.getValue(); } return null; } }
vdenisov/fluffy-meow
src/main/java/org/plukh/fluffymeow/aws/AWSInstanceInfoProviderImpl.java
Java
agpl-3.0
3,343
/** * This file is part of mycollab-services. * * mycollab-services is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * mycollab-services is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with mycollab-services. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.module.crm.service.ibatis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.esofthead.mycollab.common.interceptor.aspect.Auditable; import com.esofthead.mycollab.common.interceptor.aspect.Traceable; import com.esofthead.mycollab.core.persistence.ICrudGenericDAO; import com.esofthead.mycollab.core.persistence.ISearchableDAO; import com.esofthead.mycollab.core.persistence.service.DefaultService; import com.esofthead.mycollab.module.crm.dao.ProductMapper; import com.esofthead.mycollab.module.crm.dao.ProductMapperExt; import com.esofthead.mycollab.module.crm.domain.Product; import com.esofthead.mycollab.module.crm.domain.criteria.ProductSearchCriteria; import com.esofthead.mycollab.module.crm.service.ProductService; @Service @Transactional public class ProductServiceImpl extends DefaultService<Integer, Product, ProductSearchCriteria> implements ProductService { @Autowired private ProductMapper productMapper; @Autowired private ProductMapperExt productMapperExt; @Override public ICrudGenericDAO<Integer, Product> getCrudMapper() { return productMapper; } @Override public ISearchableDAO<ProductSearchCriteria> getSearchMapper() { return productMapperExt; } }
uniteddiversity/mycollab
mycollab-services/src/main/java/com/esofthead/mycollab/module/crm/service/ibatis/ProductServiceImpl.java
Java
agpl-3.0
2,122
/* * jHears, acoustic fingerprinting framework. * Copyright (C) 2009-2010 Juha Heljoranta. * * This file is part of jHears. * * jHears is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * jHears is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with jHears. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package org.jhears.server; import java.util.Map; public interface IUser { String getName(); Long getId(); Map<String, String> getProperties(); }
inter6/jHears
jhears-server/src/main/java/org/jhears/server/IUser.java
Java
agpl-3.0
950
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.pdc.pdc.model; import org.silverpeas.core.pdc.pdc.service.PdcManager; import org.silverpeas.core.pdc.tree.model.TreeNode; import org.silverpeas.core.persistence.datasource.model.CompositeEntityIdentifier; import org.silverpeas.core.persistence.datasource.model.jpa.BasicJpaEntity; import javax.persistence.Entity; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Transient; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; /** * A value of one of the PdC's axis. A value belongs to an axis. An axis represents a given concept * for which it defines an hierarchic tree of semantic terms belonging to the concept. A value of * an axis is then the path from the axis origin down to a given node of the tree, where each node * is a term refining or specifying the parent term a little more. For example, for an axis * representing the concept of geography, one possible value can be * "France / Rhônes-Alpes / Isère / Grenoble" where France, Rhônes-Alpes, Isère and Grenoble are * each a term (thus a node) in the axis. * "France" is another value, parent of the above one, and that is also a base value of the axis as * it has no parent (one of the root values of the axis). */ @Entity @Table(name = "pdcaxisvalue") @NamedQuery(name = "findByAxisId", query = "from PdcAxisValue where axisId = :axisId") public class PdcAxisValue extends BasicJpaEntity<PdcAxisValue, PdcAxisValuePk> { private static final long serialVersionUID = 2345886411781136417L; @Transient private transient TreeNode treeNode; @Transient private transient TreeNodeList treeNodeParents = new TreeNodeList(); protected PdcAxisValue() { } /** * Creates a value of a PdC's axis from the specified tree node. Currently, an axis of the PdC is * persisted as an hierarchical tree in which each node is a value of the axis. * @param treeNode the current persistence representation of the axis value. * @return a PdC axis value. */ public static PdcAxisValue aPdcAxisValueFromTreeNode(final TreeNode treeNode) { try { List<? extends TreeNode> parents = null; if (treeNode.hasFather()) { PdcManager pdcManager = getPdcManager(); parents = pdcManager.getFullPath(treeNode.getFatherId(), treeNode.getTreeId()); } return new PdcAxisValue().fromTreeNode(treeNode).withAsTreeNodeParents(parents). inAxisId(treeNode.getTreeId()); } catch (PdcException ex) { throw new PdcRuntimeException(ex); } } /** * Creates a value of a PdC's axis from the specified value information. Currently, an axis of the * PdC is persisted as an hierarchical tree in which each node is a value of the axis. The * parameters refers the unique identifier of the node and in the tree related to the axis * identifier. * @param valueId the unique identifier of the existing value. * @param axisId the unique identifier of the axis the value belongs to. * @return a PdC axis value. */ public static PdcAxisValue aPdcAxisValue(String valueId, String axisId) { return new PdcAxisValue().setId( valueId + CompositeEntityIdentifier.COMPOSITE_SEPARATOR + axisId); } /** * Gets the unique identifier of the axis to which this value belongs to. * @return the unique identifier of the axis value. */ public String getAxisId() { return getNativeId().getAxisId().toString(); } /** * Gets the unique value identifier. * @return the unique value identifier. */ public String getValueId() { return getNativeId().getValueId().toString(); } /** * Gets all the values into which this one can be refined or specifying in a little more. Theses * values are the children of this one in the semantic tree represented by the axis to which this * value belongs. * @return an unmodifiable set of values that are children of this one. If this value is a leaf, * then an empty set is returned. */ public Set<PdcAxisValue> getChildValues() { try { Set<PdcAxisValue> children = new HashSet<>(); List<String> childNodeIds = getPdcManager().getDaughterValues(getAxisId(), getValueId()); for (String aNodeId : childNodeIds) { children.add(aPdcAxisValue(aNodeId, getAxisId())); } return Collections.unmodifiableSet(children); } catch (PdcException ex) { throw new PdcRuntimeException(ex); } } /** * Gets the value this one refines or specifies a little more. The returned value is the parent * of this one in the semantic tree represented by the axis to which this value belongs. * @return the axis value parent of this one or null if this value has no parent (in that case, * this value is a base one). */ public PdcAxisValue getParentValue() { final PdcAxisValue parent; TreeNode node = getTreeNode(); if (node.hasFather()) { int lastNodeIndex = treeNodeParents.size() - 1; TreeNode aTreeNode = treeNodeParents.get(lastNodeIndex); String valueId = aTreeNode.getPK().getId(); String axisId = getAxisId(); PdcAxisValue pdcAxisValue = new PdcAxisValue().setId( valueId + CompositeEntityIdentifier.COMPOSITE_SEPARATOR + axisId); parent = pdcAxisValue.fromTreeNode(aTreeNode).inAxisId(getAxisId()) .withAsTreeNodeParents(treeNodeParents.subList(0, lastNodeIndex)); } else { parent = null; } return parent; } /** * Gets the term carried by this value. * @return the term of the value. */ public String getTerm() { return getTreeNode().getName(); } /** * Gets the term carried by this value and translated in the specified language. * @param language the language in which the term should be translated. * @return the term translated in the specified language. If no such translation exists, then * return the default term as get by calling getTerm() method. */ public String getTermTranslatedIn(String language) { return getTreeNode().getName(language); } /** * Is this value is a base one? * @return true if this value is an axis base value. */ public boolean isBaseValue() { // as the root in the tree represents the axis itself, a base value is a direct children of the // root. return getTreeNodeParents().size() <= 1; } /** * Gets the meaning carried by this value. The meaning is in fact the complete path of terms that * made this value. For example, in an axis representing the geography, the meaning of the value * "France / Rhônes-Alpes / Isère" is "Geography / France / Rhônes-Alpes / Isère". * @return the meaning carried by this value, in other words the complete path of this value. */ public String getMeaning() { return getMeaningTranslatedIn(""); } /** * Gets the meaning carried by this value translated in the specified language. The meaning is in * fact the complete path of translated terms that made this value. For example, in an axis * representing the geography, the meaning of the value "France / Rhônes-Alpes / Isère" is in * french "Geographie / France / Rhônes-Alpes / Isère". * @return the meaning carried by this value, in other words the complete path of this value * translated in the specified language. If no such translations exist, then the result is * equivalent to the call of the getMeaning() method. */ public String getMeaningTranslatedIn(String language) { final String meaning; final String theLanguage = (language == null ? "" : language); PdcAxisValue theParent = getParentValue(); if (theParent != null) { meaning = theParent.getMeaningTranslatedIn(theLanguage) + " / "; } else { meaning = ""; } return meaning + getTerm(); } /** * Gets the path of this value from the root value (that is a base value of the axis). The path * is * made up of the identifiers of each parent value; for example : /0/2/3 * @return the path of its value. */ public String getValuePath() { return getTreeNode().getPath() + getValueId(); } /** * Copies this value into another one. In fact, the attributes of the copy refers to the same * object referred by the attributes of this instance. * @return a copy of this PdC axis value. */ protected PdcAxisValue copy() { PdcAxisValue copy = PdcAxisValue.aPdcAxisValue(getValueId(), getAxisId()); copy.treeNode = treeNode; copy.treeNodeParents = treeNodeParents; return copy; } /** * Gets the axis to which this value belongs to and that is used to classify contents on the PdC. * @return a PdC axis configured to be used in the classification of contents. */ protected UsedAxis getUsedAxis() { try { PdcManager pdc = getPdcManager(); UsedAxis usedAxis = pdc.getUsedAxis(getAxisId()); AxisHeader axisHeader = pdc.getAxisHeader(getAxisId()); usedAxis._setAxisHeader(axisHeader); usedAxis._setAxisName(axisHeader.getName()); return usedAxis; } catch (PdcException ex) { throw new PdcRuntimeException(ex); } } /** * Gets the persisted representation of this axis value. By the same way, the parents of this * tree node are also set. * @return a tree node representing this axis value in the persistence layer. */ protected TreeNode getTreeNode() { if (this.treeNode == null || (this.treeNodeParents == null && this.treeNode.hasFather())) { loadTreeNodes(); } return this.treeNode; } protected void setId(long id) { getNativeId().setValueId(id); } protected PdcAxisValue withId(String id) { getNativeId().setValueId(Long.valueOf(id)); return this; } protected PdcAxisValue inAxisId(String axisId) { getNativeId().setAxisId(Long.valueOf(axisId)); return this; } protected PdcAxisValue fromTreeNode(final TreeNode treeNode) { getNativeId().setValueId(Long.valueOf(treeNode.getPK().getId())); this.treeNode = treeNode; return this; } protected PdcAxisValue withAsTreeNodeParents(final List<? extends TreeNode> parents) { this.treeNodeParents.setAll(parents); return this; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PdcAxisValue other = (PdcAxisValue) obj; if (this.getNativeId().getValueId() != other.getNativeId().getValueId() && (this.getNativeId().getValueId() == null || !this.getNativeId().getValueId().equals(other.getNativeId().getValueId()))) { return false; } return this.getNativeId().getAxisId() == other.getNativeId().getAxisId() || (this.getNativeId().getAxisId() != null && !this.getNativeId().getAxisId().equals(other.getNativeId().getAxisId())); } @Override public int hashCode() { int hash = 5; hash = 89 * hash + (this.getNativeId().getValueId() != null ? this.getNativeId().getValueId().hashCode() : 0); hash = 89 * hash + (this.getNativeId().getAxisId() != null ? this.getNativeId().getAxisId().hashCode() : 0); return hash; } @Override public String toString() { return ""; } /** * Converts this PdC axis value to a ClassifyValue instance. This method is for compatibility * with the old way to manage the classification. * @return a ClassifyValue instance. * @throws PdcException if an error occurs while transforming this value into a ClassifyValue * instance. */ public ClassifyValue toClassifyValue() { ClassifyValue value = new ClassifyValue(Integer.valueOf(getAxisId()), getValuePath() + "/"); List<Value> fullPath = new ArrayList<>(); for (TreeNode aTreeNode : getTreeNodeParents()) { fullPath.add(new Value(aTreeNode.getPK().getId(), aTreeNode.getTreeId(), aTreeNode.getName(), aTreeNode.getDescription(), aTreeNode.getCreationDate(), aTreeNode.getCreatorId(), aTreeNode.getPath(), aTreeNode.getLevelNumber(), aTreeNode. getOrderNumber(), aTreeNode.getFatherId())); } TreeNode lastValue = getTreeNode(); fullPath.add(new Value(lastValue.getPK().getId(), lastValue.getTreeId(), lastValue.getName(), lastValue.getDescription(), lastValue.getCreationDate(), lastValue.getCreatorId(), lastValue.getPath(), lastValue.getLevelNumber(), lastValue.getOrderNumber(), lastValue.getFatherId())); value.setFullPath(fullPath); return value; } protected TreeNodeList getTreeNodeParents() { if (this.treeNodeParents == null) { loadTreeNodes(); } return this.treeNodeParents; } private void loadTreeNodes() { try { PdcManager pdc = getPdcManager(); String treeId = pdc.getTreeId(getAxisId()); List<? extends TreeNode> paths = pdc.getFullPath(getValueId(), treeId); int lastNodeIndex = paths.size() - 1; this.treeNode = paths.get(lastNodeIndex); this.treeNodeParents.setAll(paths.subList(0, lastNodeIndex)); } catch (PdcException ex) { throw new PdcRuntimeException(ex); } } private static PdcManager getPdcManager() { return PdcManager.get(); } private class TreeNodeList implements Iterable<TreeNode> { private final List<TreeNode> treeNodes = new ArrayList<>(); public int size() { return treeNodes.size(); } public TreeNode get(final int index) { return treeNodes.get(index); } public List<TreeNode> subList(final int fromIndex, final int toIndex) { return treeNodes.subList(fromIndex, toIndex); } public void setAll(final Collection<? extends TreeNode> nodes) { this.treeNodes.clear(); this.treeNodes.addAll(nodes); } @Override public Iterator<TreeNode> iterator() { return this.treeNodes.iterator(); } @Override public void forEach(final Consumer<? super TreeNode> action) { this.treeNodes.forEach(action); } @Override public Spliterator<TreeNode> spliterator() { return this.treeNodes.spliterator(); } } }
SilverDav/Silverpeas-Core
core-services/pdc/src/main/java/org/silverpeas/core/pdc/pdc/model/PdcAxisValue.java
Java
agpl-3.0
15,496
package io.github.jhg543.mellex.operation; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import io.github.jhg543.mellex.ASTHelper.*; import io.github.jhg543.mellex.antlrparser.DefaultSQLBaseListener; import io.github.jhg543.mellex.antlrparser.DefaultSQLLexer; import io.github.jhg543.mellex.antlrparser.DefaultSQLParser; import io.github.jhg543.mellex.antlrparser.DefaultSQLParser.Sql_stmtContext; import io.github.jhg543.mellex.inputsource.BasicTableDefinitionProvider; import io.github.jhg543.mellex.inputsource.TableDefinitionProvider; import io.github.jhg543.mellex.listeners.ColumnDataFlowListener; import io.github.jhg543.mellex.util.Misc; import io.github.jhg543.nyallas.graphmodel.*; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; public class StringEdgePrinter { private static final Logger log = LoggerFactory.getLogger(StringEdgePrinter.class); private static int ERR_NOSQL = 1; private static int ERR_PARSE = 2; private static int ERR_SEMANTIC = 3; private static int ERR_OK = 0; private static int printSingleFile(Path srcdir, Path dstdir, int scriptNumber, TableDefinitionProvider tp) { // generate a hash to mark vt table names String srcHash = Integer.toHexString(srcdir.hashCode()); // create destination dir try { Files.createDirectories(dstdir); } catch (IOException e) { throw new RuntimeException(e); } try (PrintWriter err = new PrintWriter(dstdir.resolve("log").toAbsolutePath().toString(), "utf-8")) { // trim perl code String sql = Misc.trimPerlScript(srcdir, StandardCharsets.UTF_8); if (sql == null) { err.println("Can't extract sql from file " + srcdir.toString()); return ERR_NOSQL; } // log actual sql statement ( for corrent line number ..) try (PrintWriter writer = new PrintWriter(dstdir.resolve("sql").toAbsolutePath().toString(), "utf-8")) { writer.append(sql); } // antlr parse AtomicInteger errorCount = new AtomicInteger(); ANTLRInputStream in = new ANTLRInputStream(sql); DefaultSQLLexer lexer = new DefaultSQLLexer(in); CommonTokenStream tokens = new CommonTokenStream(lexer); DefaultSQLParser parser = new DefaultSQLParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { err.println("line" + line + ":" + charPositionInLine + "at" + offendingSymbol + ":" + msg); errorCount.incrementAndGet(); } }); err.println("-------Parse start---------"); ParseTree tree = null; try { tree = parser.parse(); if (errorCount.get() > 0) { return ERR_PARSE; } } catch (Exception e) { e.printStackTrace(err); return ERR_PARSE; } err.println("-------Parse OK, Semantic Analysis start --------"); ParseTreeWalker w = new ParseTreeWalker(); try { ColumnDataFlowListener s = new ColumnDataFlowListener(tp, tokens); w.walk(s, tree); } catch (Exception e) { e.printStackTrace(err); return ERR_SEMANTIC; } err.println("-------Semantic OK, Writing result --------"); // Remove volatile tables VolatileTableRemover graph = new VolatileTableRemover(); // DAG dag = new DAG(); // ZeroBasedStringIdGenerator ids = new // ZeroBasedStringIdGenerator(); Map<String, Vertex<String, Integer>> vmap = new HashMap<>(); // Output result and initialize volatile tables removal process try (PrintWriter out = new PrintWriter(dstdir.resolve("out").toAbsolutePath().toString(), "utf-8")) { out.println("ScriptID StmtID StmtType DestCol SrcCol ConnectionType"); String template = "%d %d %s %s.%s %s.%s %d\n"; DefaultSQLBaseListener pr = new DefaultSQLBaseListener() { int stmtNumber = 0; @Override public void exitSql_stmt(Sql_stmtContext ctx) { super.exitSql_stmt(ctx); String stmtType = null; SubQuery q = null; if (ctx.insert_stmt() != null) { stmtType = "I"; q = ctx.insert_stmt().stmt; } if (ctx.create_table_stmt() != null) { if (ctx.create_table_stmt().insert != null) { stmtType = "C"; q = ctx.create_table_stmt().insert; } } if (ctx.create_view_stmt() != null) { stmtType = "V"; q = ctx.create_view_stmt().insert; } if (ctx.update_stmt() != null) { stmtType = "U"; q = ctx.update_stmt().q; } if (q != null) { // what's vt's scope? Set<String> vts = tp.getVolatileTables().keySet(); String dstTable = q.dbobj.toDotString(); boolean isDstVT = vts.contains(dstTable); if (isDstVT) { dstTable = "VT_" + srcHash + "_" + dstTable; } for (ResultColumn c : q.columns) { for (InfSource source : c.inf.getSources()) { ObjectName srcname = source.getSourceObject(); String srcTable = srcname.toDotStringExceptLast(); boolean isSrcVT = vts.contains(srcTable); if (isSrcVT) { srcTable = "VT_" + srcHash + "_" + srcTable; } out.append(String.format(template, scriptNumber, stmtNumber, stmtType, dstTable, c.name, srcTable, srcname.toDotStringLast(), source.getConnectionType().getMarker())); // collapse volatile table String dst = dstTable + "." + c.name; String src = srcTable + "." + srcname.toDotStringLast(); // Integer dstnum = ids.queryNumber(dst); // Integer srcnum = ids.queryNumber(src); Vertex<String, Integer> srcv; srcv = vmap.get(src); if (srcv == null) { srcv = graph.addVertex(BasicVertex::new); vmap.put(src, srcv); srcv.setVertexData(src); if (isSrcVT) { srcv.setMarker(0); } } Vertex<String, Integer> dstv; dstv = vmap.get(dst); if (dstv == null) { dstv = graph.addVertex(BasicVertex::new); vmap.put(dst, dstv); dstv.setVertexData(dst); if (isDstVT) { dstv.setMarker(0); } } Edge<String, Integer> edge = new BasicEdge<String, Integer>(srcv, dstv); edge.setEdgeData(source.getConnectionType().getMarker()); graph.addEdge(edge); } } } else { // log.warn("query null for sm " + stmtNumber); } stmtNumber++; } }; w.walk(pr, tree); } // Int2ObjectMap<Node> collapsed = dag.collapse(scriptNumber); graph.remove(); // write result (with volatile tables removed) try (PrintWriter out = new PrintWriter(dstdir.resolve("novt").toAbsolutePath().toString(), "utf-8")) { out.println("scriptid,dstsch,dsttbl,dstcol,srcsch,srctbl,srccol,contype"); String template = "%d,%s,%s,%s,%s,%s,%s,%d\n"; for (Vertex<String, Integer> v : graph.getVertexes()) { for (Edge<String, Integer> e : v.getOutgoingEdges()) { String dst = e.getTarget().getVertexData(); String src = e.getSource().getVertexData(); List<String> t1 = Splitter.on('.').splitToList(dst); if (t1.size() == 2) { t1 = new ArrayList<String>(t1); t1.add(0, "3X_NOSCHEMA_" + scriptNumber); } List<String> t2 = Splitter.on('.').splitToList(src); if (t2.size() == 2) { t2 = new ArrayList<String>(t1); t2.add(0, "3X_NOSCHEMA_" + scriptNumber); } out.append(String.format(template, scriptNumber, t1.get(0), t1.get(1), t1.get(2), t2.get(0), t2.get(1), t2.get(2), e.getEdgeData())); } } } tp.clearVolatileTables(); err.println("-------Success --------"); return 0; } catch (FileNotFoundException | UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static int[] printStringEdge(Path srcdir, Path dstdir, Predicate<Path> filefilter, int scriptNumberStart, boolean caseSensitive) { // ensure directories exist Preconditions.checkState(Files.isDirectory(srcdir)); try { Files.createDirectories(dstdir); } catch (IOException e1) { throw new RuntimeException(e1); } // set up variables GlobalSettings.setCaseSensitive(caseSensitive); AtomicInteger scriptNumber = new AtomicInteger(scriptNumberStart); TableDefinitionProvider tp = new BasicTableDefinitionProvider(Misc::nameSym); int[] stats = new int[10]; // open global output files try (PrintWriter out = new PrintWriter(dstdir.resolve("stats").toAbsolutePath().toString(), "utf-8"); PrintWriter cols = new PrintWriter(dstdir.resolve("cols").toAbsolutePath().toString(), "utf-8"); PrintWriter numbers = new PrintWriter(dstdir.resolve("number").toAbsolutePath().toString(), "utf-8")) { // for each file Files.walk(srcdir).filter(filefilter).sorted().forEach(path -> { int sn = scriptNumber.getAndIncrement(); numbers.println("" + sn + " " + path.toString()); String srcHash = Integer.toHexString(path.hashCode()); Path workdir = dstdir.resolve(path.getFileName()).resolve(srcHash); // deal with single files. int retcode = printSingleFile(path, workdir, sn, tp); if (retcode > 0) { out.println(String.format("%s %d %d", path.toString(), retcode, sn)); } stats[retcode]++; }); out.println("OK=" + stats[ERR_OK]); out.println("NOSQL=" + stats[ERR_NOSQL]); out.println("PARSE=" + stats[ERR_PARSE]); out.println("SEMANTIC=" + stats[ERR_SEMANTIC]); tp.getPermanentTables().forEach((name, stmt) -> { stmt.columns.forEach(colname -> cols.println(name + "." + colname.name)); }); return stats; } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { Predicate<Path> filefilter = x -> Files.isRegularFile(x) && (x.getFileName().toString().toLowerCase().endsWith(".sql") || x.getFileName().toString().toLowerCase() .endsWith(".pl")) && x.toString().toUpperCase().endsWith("BIN\\" + x.getFileName().toString().toUpperCase()); // printStringEdge(Paths.get("d:/dataflow/work1/script/mafixed"), // Paths.get("d:/dataflow/work2/mares"), filefilter, 0, false); printStringEdge(Paths.get("d:/dataflow/work1/debug"), Paths.get("d:/dataflow/work2/debugres"), filefilter, 0, false); // printStringEdge(Paths.get("d:/dataflow/work1/f1/sor"), // Paths.get("d:/dataflow/work2/result2/sor"), filefilter, 0, false); } }
jhg543/mellex
src/main/java/io/github/jhg543/mellex/operation/StringEdgePrinter.java
Java
agpl-3.0
11,043
package com.neverwinterdp.scribengin.dataflow.example.wire; import java.util.Properties; import com.neverwinterdp.message.Message; import com.neverwinterdp.scribengin.dataflow.DataSet; import com.neverwinterdp.scribengin.dataflow.Dataflow; import com.neverwinterdp.scribengin.dataflow.DataflowDescriptor; import com.neverwinterdp.scribengin.dataflow.DataflowSubmitter; import com.neverwinterdp.scribengin.dataflow.KafkaDataSet; import com.neverwinterdp.scribengin.dataflow.KafkaWireDataSetFactory; import com.neverwinterdp.scribengin.dataflow.Operator; import com.neverwinterdp.scribengin.shell.ScribenginShell; import com.neverwinterdp.storage.kafka.KafkaStorageConfig; import com.neverwinterdp.util.JSONSerializer; import com.neverwinterdp.vm.client.VMClient; public class ExampleWireDataflowSubmitter { private String dataflowID; private int defaultReplication; private int defaultParallelism; private int numOfWorker; private int numOfExecutorPerWorker; private String inputTopic; private String outputTopic; private ScribenginShell shell; private DataflowSubmitter submitter; private String localAppHome; private String dfsAppHome; public ExampleWireDataflowSubmitter(ScribenginShell shell){ this(shell, new Properties()); } /** * Constructor - sets shell to access Scribengin and configuration properties * @param shell ScribenginShell to connect to Scribengin with * @param props Properties to configure the dataflow */ public ExampleWireDataflowSubmitter(ScribenginShell shell, Properties props){ //This it the shell to communicate with Scribengin with this.shell = shell; //The dataflow's ID. All dataflows require a unique ID when running dataflowID = props.getProperty("dataflow.id", "WireDataflow"); //The default replication factor for Kafka defaultReplication = Integer.parseInt(props.getProperty("dataflow.replication", "1")); //The number of DataStreams to deploy defaultParallelism = Integer.parseInt(props.getProperty("dataflow.parallelism", "2")); //The number of workers to deploy (i.e. YARN containers) numOfWorker = Integer.parseInt(props.getProperty("dataflow.numWorker", "5")); //The number of executors per worker (i.e. threads per YARN container) numOfExecutorPerWorker = Integer.parseInt(props.getProperty("dataflow.numExecutorPerWorker", "5")); //The kafka input topic inputTopic = props.getProperty("dataflow.inputTopic", "input.topic"); //The kafka output topic outputTopic = props.getProperty("dataflow.outputTopic", "output.topic"); //The example hdfs dataflow local location localAppHome = props.getProperty("dataflow.localapphome", "N/A"); //DFS location to upload the example dataflow dfsAppHome = props.getProperty("dataflow.dfsAppHome", "/applications/dataflow/splitterexample"); } /** * The logic to submit the dataflow * @param kafkaZkConnect [host]:[port] of Kafka's Zookeeper conenction * @throws Exception */ public void submitDataflow(String kafkaZkConnect) throws Exception{ //Upload the dataflow to HDFS VMClient vmClient = shell.getScribenginClient().getVMClient(); vmClient.uploadApp(localAppHome, dfsAppHome); Dataflow dfl = buildDataflow(kafkaZkConnect); //Get the dataflow's descriptor DataflowDescriptor dflDescriptor = dfl.buildDataflowDescriptor(); //Output the descriptor in human-readable JSON System.out.println(JSONSerializer.INSTANCE.toString(dflDescriptor)); //Ensure all your sources and sinks are up and running first, then... //Submit the dataflow and wait until it starts running submitter = new DataflowSubmitter(shell.getScribenginClient(), dfl).submit().waitForDataflowRunning(60000); } /** * Wait for the dataflow to complete within the given timeout * @param timeout Timeout in ms * @throws Exception */ public void waitForDataflowCompletion(int timeout) throws Exception{ submitter.waitForDataflowStop(timeout); } /** * The logic to build the dataflow configuration * The main takeaway between this dataflow and the ExampleSimpleDataflowSubmitter * is the use of dfl.useWireDataSetFactory() * This factory allows us to tie together operators * with Kafka topics between them * @param kafkaZkConnect [host]:[port] of Kafka's Zookeeper conenction * @return */ public Dataflow buildDataflow(String kafkaZkConnect){ //Create the new Dataflow object // <Message,Message> pertains to the <input,output> object for the data Dataflow dfl = new Dataflow(dataflowID); //Example of how to set the KafkaWireDataSetFactory dfl. setDefaultParallelism(defaultParallelism). setDefaultReplication(defaultReplication). useWireDataSetFactory(new KafkaWireDataSetFactory(kafkaZkConnect)); dfl.getWorkerDescriptor().setNumOfInstances(numOfWorker); dfl.getWorkerDescriptor().setNumOfExecutor(numOfExecutorPerWorker); //Define our input source - set name, ZK host:port, and input topic name KafkaDataSet<Message> inputDs = dfl.createInput(new KafkaStorageConfig("input", kafkaZkConnect, inputTopic)); //Define our output sink - set name, ZK host:port, and output topic name DataSet<Message> outputDs = dfl.createOutput(new KafkaStorageConfig("output", kafkaZkConnect, outputTopic)); //Define which operators to use. //This will be the logic that ties the datasets and operators together Operator splitter = dfl.createOperator("splitteroperator", SplitterDataStreamOperator.class); Operator odd = dfl.createOperator("oddoperator", PersisterDataStreamOperator.class); Operator even = dfl.createOperator("evenoperator", PersisterDataStreamOperator.class); //Send all input to the splitter operator inputDs.useRawReader().connect(splitter); //The splitter operator then connects to the odd and even operators splitter.connect(odd) .connect(even); //Both the odd and even operator connect to the output dataset // This is arbitrary, we could connect them to any dataset or operator we wanted odd.connect(outputDs); even.connect(outputDs); return dfl; } public String getDataflowID() { return dataflowID; } public String getInputTopic() { return inputTopic; } public String getOutputTopic() { return outputTopic; } }
DemandCube/NeverwinterDP
scribengin/dataflow/example/src/main/java/com/neverwinterdp/scribengin/dataflow/example/wire/ExampleWireDataflowSubmitter.java
Java
agpl-3.0
6,521
package com.gmail.nossr50.commands.party; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.commands.CommandHelper; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.events.chat.McMMOPartyChatEvent; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.party.Party; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.util.Users; public class PCommand implements CommandExecutor { private final mcMMO plugin; public PCommand (mcMMO plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { PlayerProfile profile; String usage = ChatColor.RED + "Proper usage is /p <party-name> <message>"; //TODO: Needs more locale. if (CommandHelper.noCommandPermissions(sender, "mcmmo.commands.party")) { return true; } switch (args.length) { case 0: if (sender instanceof Player) { profile = Users.getProfile((Player) sender); if (profile.getAdminChatMode()) { profile.toggleAdminChat(); } profile.togglePartyChat(); if (profile.getPartyChatMode()) { sender.sendMessage(LocaleLoader.getString("Commands.Party.Chat.On")); } else { sender.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Off")); } } else { sender.sendMessage(usage); } return true; default: if (sender instanceof Player) { Player player = (Player) sender; Party party = Users.getProfile(player).getParty(); if (party == null) { player.sendMessage(LocaleLoader.getString("Commands.Party.None")); return true; } StringBuffer buffer = new StringBuffer(); buffer.append(args[0]); for (int i = 1; i < args.length; i++) { buffer.append(" "); buffer.append(args[i]); } String message = buffer.toString(); McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent(player.getName(), party.getName(), message); plugin.getServer().getPluginManager().callEvent(chatEvent); if (chatEvent.isCancelled()) { return true; } message = chatEvent.getMessage(); String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + player.getName() + ChatColor.GREEN + ") "; plugin.getLogger().info("[P](" + party.getName() + ")" + "<" + player.getName() + "> " + message); for (Player member : party.getOnlineMembers()) { member.sendMessage(prefix + message); } } else { if (args.length < 2) { sender.sendMessage(usage); return true; } if (!PartyManager.getInstance().isParty(args[0])) { sender.sendMessage(LocaleLoader.getString("Party.InvalidName")); return true; } StringBuffer buffer = new StringBuffer(); buffer.append(args[1]); for (int i = 2; i < args.length; i++) { buffer.append(" "); buffer.append(args[i]); } String message = buffer.toString(); McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent("Console", args[0], message); plugin.getServer().getPluginManager().callEvent(chatEvent); if (chatEvent.isCancelled()) { return true; } message = chatEvent.getMessage(); String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + "*Console*" + ChatColor.GREEN + ") "; plugin.getLogger().info("[P](" + args[0] + ")" + "<*Console*> " + message); for (Player member : PartyManager.getInstance().getOnlineMembers(args[0])) { member.sendMessage(prefix + message); } } return true; } } }
javalangSystemwin/mcMMOPlus
src/main/java/com/gmail/nossr50/commands/party/PCommand.java
Java
agpl-3.0
4,799
package org.demo.jdk.utilapis; public class Bird implements Flyable { private int speed = 15; @Override public void fly() { System.out.println("I'm Bird, my speed is " + speed + "."); } }
William-Hai/SimpleDemo
src/org/demo/jdk/utilapis/Bird.java
Java
agpl-3.0
220
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb.index; import java.util.Iterator; import java.util.NoSuchElementException; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; /** * An {@link Iterator} with additional {@link #size()} and {@link #close()} * methods on it, used for iterating over index query results. It is first and * foremost an {@link Iterator}, but also an {@link Iterable} JUST so that it * can be used in a for-each loop. The <code>iterator()</code> method * <i>always</i> returns <code>this</code>. * * The size is calculated before-hand so that calling it is always fast. * * When you're done with the result and haven't reached the end of the * iteration {@link #close()} must be called. Results which are looped through * entirely closes automatically. Typical use: * * <pre> * IndexHits<Node> hits = index.get( "key", "value" ); * try * { * for ( Node node : hits ) * { * // do something with the hit * } * } * finally * { * hits.close(); * } * </pre> * * @param <T> the type of items in the Iterator. */ public interface IndexHits<T> extends Iterator<T>, Iterable<T> { /** * Returns the size of this iterable, in most scenarios this value is accurate * while in some scenarios near-accurate. * * There's no cost in calling this method. It's considered near-accurate if this * {@link IndexHits} object has been returned when inside a {@link Transaction} * which has index modifications, of a certain nature. Also entities * ({@link Node}s/{@link Relationship}s) which have been deleted from the graph, * but are still in the index will also affect the accuracy of the returned size. * * @return the near-accurate size if this iterable. */ int size(); /** * Closes the underlying search result. This method should be called * whenever you've got what you wanted from the result and won't use it * anymore. It's necessary to call it so that underlying indexes can dispose * of allocated resources for this search result. * * You can however skip to call this method if you loop through the whole * result, then close() will be called automatically. Even if you loop * through the entire result and then call this method it will silently * ignore any consequtive call (for convenience). */ void close(); /** * Returns the first and only item from the result iterator, or {@code null} * if there was none. If there were more than one item in the result a * {@link NoSuchElementException} will be thrown. This method must be called * first in the iteration and will grab the first item from the iteration, * so the result is considered broken after this call. * * @return the first and only item, or {@code null} if none. */ T getSingle(); /** * Returns the score of the most recently fetched item from this iterator * (from {@link #next()}). The range of the returned values is up to the * {@link Index} implementation to dictate. * @return the score of the most recently fetched item from this iterator. */ float currentScore(); }
neo4j-attic/graphdb
kernel/src/main/java/org/neo4j/graphdb/index/IndexHits.java
Java
agpl-3.0
4,080
/* * Claudia Project * http://claudia.morfeo-project.org * * (C) Copyright 2010 Telefonica Investigacion y Desarrollo * S.A.Unipersonal (Telefonica I+D) * * See CREDITS file for info about members and contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License (AGPL) as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the Affero GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * If you want to use this software an plan to distribute a * proprietary application in any way, and you are not licensing and * distributing your source code under AGPL, you probably need to * purchase a commercial license of the product. Please contact * claudia-support@lists.morfeo-project.org for more information. */ package com.telefonica.claudia.smi.deployment; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.resource.DomRepresentation; import org.restlet.resource.Representation; import org.restlet.resource.Resource; import org.restlet.resource.ResourceException; import org.restlet.resource.Variant; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.telefonica.claudia.smi.Main; import com.telefonica.claudia.smi.URICreation; public class ServiceItemResource extends Resource { private static Logger log = Logger.getLogger("com.telefonica.claudia.smi.ServiceItemResource"); String vdcId; String vappId; String orgId; public ServiceItemResource(Context context, Request request, Response response) { super(context, request, response); this.vappId = (String) getRequest().getAttributes().get("vapp-id"); this.vdcId = (String) getRequest().getAttributes().get("vdc-id"); this.orgId = (String) getRequest().getAttributes().get("org-id"); // Get the item directly from the "persistence layer". if (this.orgId != null && this.vdcId!=null && this.vappId!=null) { // Define the supported variant. getVariants().add(new Variant(MediaType.TEXT_XML)); // By default a resource cannot be updated. setModifiable(true); } else { // This resource is not available. setAvailable(false); } } /** * Handle GETS */ @Override public Representation represent(Variant variant) throws ResourceException { // Generate the right representation according to its media type. if (MediaType.TEXT_XML.equals(variant.getMediaType())) { try { DeploymentDriver actualDriver= (DeploymentDriver) getContext().getAttributes().get(DeploymentApplication.ATTR_PLUGIN_DEPLOYMENT); String serviceInfo = actualDriver.getService(URICreation.getFQN(orgId, vdcId, vappId)); // Substitute the macros in the description serviceInfo = serviceInfo.replace("@HOSTNAME", "http://" + Main.serverHost + ":" + Main.serverPort); if (serviceInfo==null) { log.error("Null response from the SM."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(serviceInfo)); Document doc = db.parse(is); DomRepresentation representation = new DomRepresentation( MediaType.TEXT_XML, doc); log.info("Data returned for service "+ URICreation.getFQN(orgId, vdcId, vappId) + ": \n\n" + serviceInfo); // Returns the XML representation of this document. return representation; } catch (IOException e) { log.error("Time out waiting for the Lifecycle Controller."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } catch (SAXException e) { log.error("Retrieved data was not in XML format: " + e.getMessage()); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } catch (ParserConfigurationException e) { log.error("Error trying to configure parser."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } } return null; } /** * Handle DELETE requests. */ @Override public void removeRepresentations() throws ResourceException { DeploymentDriver actualDriver= (DeploymentDriver) getContext().getAttributes().get(DeploymentApplication.ATTR_PLUGIN_DEPLOYMENT); try { actualDriver.undeploy(URICreation.getFQN(orgId, vdcId, vappId)); } catch (IOException e) { log.error("Time out waiting for the Lifecycle Controller."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return; } // Tells the client that the request has been successfully fulfilled. getResponse().setStatus(Status.SUCCESS_NO_CONTENT); } }
StratusLab/claudia
tcloud-server/src/main/java/com/telefonica/claudia/smi/deployment/ServiceItemResource.java
Java
agpl-3.0
6,138
/* * Copyright (c) 2015 - 2016 Memorial Sloan-Kettering Cancer Center. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mskcc.cbio.portal.util; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import org.cbioportal.persistence.GenePanelRepository; import org.cbioportal.model.GenePanel; import org.mskcc.cbio.portal.model.GeneticAlterationType; import org.mskcc.cbio.portal.model.GeneticProfile; /** * Genetic Profile Util Class. * */ public class GeneticProfileUtil { /** * Gets the GeneticProfile with the Specified GeneticProfile ID. * @param profileId GeneticProfile ID. * @param profileList List of Genetic Profiles. * @return GeneticProfile or null. */ public static GeneticProfile getProfile(String profileId, ArrayList<GeneticProfile> profileList) { for (GeneticProfile profile : profileList) { if (profile.getStableId().equals(profileId)) { return profile; } } return null; } /** * Returns true if Any of the Profiles Selected by the User Refer to mRNA Expression * outlier profiles. * * @param geneticProfileIdSet Set of Chosen Profiles IDs. * @param profileList List of Genetic Profiles. * @return true or false. */ public static boolean outlierExpressionSelected(HashSet<String> geneticProfileIdSet, ArrayList<GeneticProfile> profileList) { Iterator<String> geneticProfileIdIterator = geneticProfileIdSet.iterator(); while (geneticProfileIdIterator.hasNext()) { String geneticProfileId = geneticProfileIdIterator.next(); GeneticProfile geneticProfile = getProfile (geneticProfileId, profileList); if (geneticProfile != null && geneticProfile.getGeneticAlterationType() == GeneticAlterationType.MRNA_EXPRESSION) { String profileName = geneticProfile.getProfileName(); if (profileName != null) { if (profileName.toLowerCase().contains("outlier")) { return true; } } } } return false; } public static int getGenePanelId(String panelId) { GenePanelRepository genePanelRepository = SpringUtil.getGenePanelRepository(); GenePanel genePanel = genePanelRepository.getGenePanelByStableId(panelId).get(0); return genePanel.getInternalId(); } }
bihealth/cbioportal
core/src/main/java/org/mskcc/cbio/portal/util/GeneticProfileUtil.java
Java
agpl-3.0
3,897
package com.alessiodp.parties.bukkit.addons.external.skript.expressions; import ch.njol.skript.classes.Changer; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; import ch.njol.skript.doc.Since; import ch.njol.skript.expressions.base.SimplePropertyExpression; import ch.njol.util.coll.CollectionUtils; import com.alessiodp.parties.api.interfaces.Party; import org.bukkit.event.Event; @Name("Party Name") @Description("Get the name of the given party.") @Examples({"send \"%name of party with name \"test\"%\"", "send \"%name of event-party%\""}) @Since("3.0.0") public class ExprPartyName extends SimplePropertyExpression<Party, String> { static { register(ExprPartyName.class, String.class, "name", "party"); } @Override public Class<? extends String> getReturnType() { return String.class; } @Override protected String getPropertyName() { return "name"; } @Override public String convert(Party party) { return party.getName(); } @Override public void change(Event e, Object[] delta, Changer.ChangeMode mode){ if (delta != null) { Party party = getExpr().getSingle(e); String newName = (String) delta[0]; switch (mode) { case SET: party.rename(newName); break; case DELETE: party.rename(null); break; default: break; } } } @Override public Class<?>[] acceptChange(final Changer.ChangeMode mode) { return (mode == Changer.ChangeMode.SET || mode == Changer.ChangeMode.DELETE) ? CollectionUtils.array(String.class) : null; } }
AlessioDP/Parties
bukkit/src/main/java/com/alessiodp/parties/bukkit/addons/external/skript/expressions/ExprPartyName.java
Java
agpl-3.0
1,576
/** * Copyright (C) 2001-2020 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.new_plotter.configuration; import com.rapidminer.gui.new_plotter.listener.events.LineFormatChangeEvent; import com.rapidminer.gui.new_plotter.utility.DataStructureUtils; import com.rapidminer.tools.I18N; import java.awt.BasicStroke; import java.awt.Color; import java.lang.ref.WeakReference; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * @author Marius Helf * @deprecated since 9.2.0 */ @Deprecated public class LineFormat implements Cloneable { private static class StrokeFactory { static public BasicStroke getSolidStroke() { return new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); } static public BasicStroke getDottedStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 1f, 1f }, 0.0f); } static public BasicStroke getShortDashedStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 4f, 2f }, 0.0f); } static public BasicStroke getLongDashedStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 7f, 3f }, 0.0f); } static public BasicStroke getDashDotStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 6f, 2f, 1f, 2f }, 0.0f); } static public BasicStroke getStripedStroke() { return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 0.2f, 0.2f }, 0.0f); } } public enum LineStyle { NONE(null, I18N.getGUILabel("plotter.linestyle.NONE.label")), SOLID(StrokeFactory.getSolidStroke(), I18N .getGUILabel("plotter.linestyle.SOLID.label")), DOTS(StrokeFactory.getDottedStroke(), I18N .getGUILabel("plotter.linestyle.DOTS.label")), SHORT_DASHES(StrokeFactory.getShortDashedStroke(), I18N .getGUILabel("plotter.linestyle.SHORT_DASHES.label")), LONG_DASHES(StrokeFactory.getLongDashedStroke(), I18N .getGUILabel("plotter.linestyle.LONG_DASHES.label")), DASH_DOT(StrokeFactory.getDashDotStroke(), I18N .getGUILabel("plotter.linestyle.DASH_DOT.label")), STRIPES(StrokeFactory.getStripedStroke(), I18N .getGUILabel("plotter.linestyle.STRIPES.label")); private final BasicStroke stroke; private final String name; public BasicStroke getStroke() { return stroke; } public String getName() { return name; } private LineStyle(BasicStroke stroke, String name) { this.stroke = stroke; this.name = name; } } private List<WeakReference<LineFormatListener>> listeners = new LinkedList<WeakReference<LineFormatListener>>(); private LineStyle style = LineStyle.NONE; // dashed, solid... private Color color = Color.GRAY; private float width = 1.0f; public LineStyle getStyle() { return style; } public void setStyle(LineStyle style) { if (style != this.style) { this.style = style; fireStyleChanged(); } } public Color getColor() { return color; } public void setColor(Color color) { if (color == null ? this.color != null : !color.equals(this.color)) { this.color = color; fireColorChanged(); } } public float getWidth() { return width; } public void setWidth(float width) { if (width != this.width) { this.width = width; fireWidthChanged(); } } private void fireWidthChanged() { fireLineFormatChanged(new LineFormatChangeEvent(this, width)); } private void fireColorChanged() { fireLineFormatChanged(new LineFormatChangeEvent(this, color)); } private void fireStyleChanged() { fireLineFormatChanged(new LineFormatChangeEvent(this, style)); } private void fireLineFormatChanged(LineFormatChangeEvent e) { Iterator<WeakReference<LineFormatListener>> it = listeners.iterator(); while (it.hasNext()) { LineFormatListener l = it.next().get(); if (l != null) { l.lineFormatChanged(e); } else { it.remove(); } } } @Override public LineFormat clone() { LineFormat clone = new LineFormat(); clone.color = new Color(color.getRGB(), true); clone.style = style; clone.width = width; return clone; } public BasicStroke getStroke() { BasicStroke stroke = style.getStroke(); if (stroke != null) { float[] scaledDashArray = getScaledDashArray(); BasicStroke scaledStroke = new BasicStroke(this.getWidth(), stroke.getEndCap(), stroke.getLineJoin(), stroke.getMiterLimit(), scaledDashArray, stroke.getDashPhase()); return scaledStroke; } else { return null; } } float[] getScaledDashArray() { BasicStroke stroke = getStyle().getStroke(); if (stroke == null) { return null; } float[] dashArray = stroke.getDashArray(); float[] scaledDashArray; if (dashArray != null) { float scalingFactor = getWidth(); if (scalingFactor <= 0) { scalingFactor = 1; } if (scalingFactor != 1) { scaledDashArray = DataStructureUtils.cloneAndMultiplyArray(dashArray, scalingFactor); } else { scaledDashArray = dashArray; } } else { scaledDashArray = dashArray; } return scaledDashArray; } public void addLineFormatListener(LineFormatListener l) { listeners.add(new WeakReference<LineFormatListener>(l)); } public void removeLineFormatListener(LineFormatListener l) { Iterator<WeakReference<LineFormatListener>> it = listeners.iterator(); while (it.hasNext()) { LineFormatListener listener = it.next().get(); if (l != null) { if (listener != null && listener.equals(l)) { it.remove(); } } else { it.remove(); } } } }
rapidminer/rapidminer-studio
src/main/java/com/rapidminer/gui/new_plotter/configuration/LineFormat.java
Java
agpl-3.0
6,597
package com.nexusplay.containers; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.sql.SQLException; import org.apache.commons.io.IOUtils; import com.nexusplay.db.SubtitlesDatabase; import com.nexusplay.security.RandomContainer; /** * Contains a proposed change (to a subtitle). * @author alex * */ public class Change { private String targetID, changedContent, id, originalContent, votes; private int nrVotes; /** * Constructor for creating new objects, prior to storing them in the database. * @param changedContent The change's original data * @param originalContent The change's new data * @param targetID The object targeted by the change * @param votes The user IDs that voted this change */ public Change(String changedContent, String originalContent, String targetID, String votes){ this.changedContent = changedContent; this.originalContent = originalContent; this.targetID = targetID; this.votes = votes; nrVotes = votes.length() - votes.replace(";", "").length(); generateId(); } /** * This constructor should only be used for recreating a stored object. * @param changedContent The change's original data * @param originalContent The change's new data * @param targetID The object targeted by the change * @param votes The user IDs that voted this change * @param id The change's unique ID */ public Change(String changedContent, String originalContent, String targetID, String votes, String id){ this.changedContent = changedContent; this.originalContent = originalContent; this.targetID = targetID; this.votes = votes; nrVotes = votes.length() - votes.replace(";", "").length(); this.id = id; } /** * Commits a change to disk. * @throws SQLException Thrown if the database is not accessible to us for whatever reason * @throws FileNotFoundException Thrown if we're denied access to the subtitle file * @throws IOException Thrown if an error appears while writing the file */ public void commitChange() throws SQLException, FileNotFoundException, IOException{ Subtitle sub = SubtitlesDatabase.getSubtitleByID(targetID); FileInputStream input = new FileInputStream(SettingsContainer.getAbsoluteSubtitlePath() + File.separator + sub.getId() + ".vtt"); String content = IOUtils.toString(input, "UTF-8"); content = content.replaceAll(originalContent, changedContent); content = content.replaceAll(originalContent.replaceAll("\n", "\r\n"), changedContent.replaceAll("\n", "\r\n")); FileOutputStream output = new FileOutputStream(SettingsContainer.getAbsoluteSubtitlePath() + File.separator + sub.getId() + ".vtt"); IOUtils.write(content, output, "UTF-8"); output.close(); input.close(); } /** * Generates a new unique ID for the item */ public void generateId() { id = (new BigInteger(130, RandomContainer.getRandom())).toString(32); } /** * @return The ID of the Media element associated to this object */ public String getTargetID() { return targetID; } /** * @param targetID The new ID of the Media element associated to this object */ public void setTargetID(String targetID) { this.targetID = targetID; } /** * @return The change itself */ public String getChangedContent() { return changedContent; } /** * @param content The new data to change */ public void setChangedContent(String content) { this.changedContent = content; } /** * @return The change's unique ID */ public String getId() { return id; } /** * @param id The change's new unique ID */ public void setId(String id) { this.id = id; } /** * @return The user IDs who voted for this change */ public String getVotes() { return votes; } /** * @param votes The new user IDs who voted for this change */ public void setVotes(String votes) { this.votes = votes; nrVotes = votes.length() - votes.replace(";", "").length(); } /** * @return The original content prior to changing */ public String getOriginalContent() { return originalContent; } /** * @param originalContent The new original content prior to changing */ public void setOriginalContent(String originalContent) { this.originalContent = originalContent; } /** * @return the nrVotes */ public int getNrVotes() { return nrVotes; } /** * @param nrVotes the nrVotes to set */ public void setNrVotes(int nrVotes) { this.nrVotes = nrVotes; } }
AlexCristian/NexusPlay
src/com/nexusplay/containers/Change.java
Java
agpl-3.0
4,573
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.purap.document.validation.impl; import org.kuali.kfs.coreservice.framework.parameter.ParameterService; import org.kuali.kfs.module.purap.PurapConstants; import org.kuali.kfs.module.purap.PurapParameterConstants; import org.kuali.kfs.module.purap.PurapRuleConstants; import org.kuali.kfs.module.purap.document.RequisitionDocument; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent; public class RequisitionNewIndividualItemValidation extends PurchasingNewIndividualItemValidation { public boolean validate(AttributedDocumentEvent event) { return super.validate(event); } @Override protected boolean commodityCodeIsRequired() { //if the ENABLE_COMMODITY_CODE_IND parameter is N then we don't //need to check for the ITEMS_REQUIRE_COMMODITY_CODE_IND parameter anymore, just return false. boolean enableCommodityCode = SpringContext.getBean(ParameterService.class).getParameterValueAsBoolean(PurapConstants.PURAP_NAMESPACE, "Document", PurapParameterConstants.ENABLE_COMMODITY_CODE_IND); if (!enableCommodityCode) { return false; } else { return super.getParameterService().getParameterValueAsBoolean(RequisitionDocument.class, PurapRuleConstants.ITEMS_REQUIRE_COMMODITY_CODE_IND); } } }
quikkian-ua-devops/will-financials
kfs-purap/src/main/java/org/kuali/kfs/module/purap/document/validation/impl/RequisitionNewIndividualItemValidation.java
Java
agpl-3.0
2,205
/** * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.stratelia.silverpeas.peasCore; import com.silverpeas.util.ArrayUtil; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.beans.admin.ComponentInstLight; import com.stratelia.webactiv.beans.admin.OrganizationController; import javax.servlet.http.HttpServletRequest; /** * @author ehugonnet */ public class SilverpeasWebUtil { private OrganizationController organizationController = new OrganizationController(); public SilverpeasWebUtil() { } public SilverpeasWebUtil(OrganizationController controller) { organizationController = controller; } public OrganizationController getOrganizationController() { return organizationController; } /** * Accessing the MainSessionController * @param request the HttpServletRequest * @return the current MainSessionController. */ public MainSessionController getMainSessionController(HttpServletRequest request) { return (MainSessionController) request.getSession().getAttribute( MainSessionController.MAIN_SESSION_CONTROLLER_ATT); } /** * Extract the space id and the component id. * @param request * @return */ public String[] getComponentId(HttpServletRequest request) { String spaceId; String componentId; String function; String pathInfo = request.getPathInfo(); SilverTrace.info("peasCore", "ComponentRequestRouter.getComponentId", "root.MSG_GEN_PARAM_VALUE", "pathInfo=" + pathInfo); if (pathInfo != null) { spaceId = null; pathInfo = pathInfo.substring(1); // remove first '/' function = pathInfo.substring(pathInfo.indexOf('/') + 1, pathInfo.length()); if (pathInfo.startsWith("jsp")) { // Pour les feuilles de styles, icones, ... + Pour les composants de // l'espace personnel (non instanciables) componentId = null; } else { // Get the space and component Ids // componentId extracted from the URL // Old url (with WA..) if (pathInfo.contains("WA")) { String sAndCId = pathInfo.substring(0, pathInfo.indexOf('/')); // spaceId looks like WA17 spaceId = sAndCId.substring(0, sAndCId.indexOf('_')); // componentId looks like kmelia123 componentId = sAndCId.substring(spaceId.length() + 1, sAndCId.length()); } else { componentId = pathInfo.substring(0, pathInfo.indexOf('/')); } if (function.startsWith("Main") || function.startsWith("searchResult") || function.equalsIgnoreCase("searchresult") || function.startsWith("portlet") || function.equals("GoToFilesTab")) { ComponentInstLight component = organizationController.getComponentInstLight(componentId); spaceId = component.getDomainFatherId(); } SilverTrace.info("peasCore", "ComponentRequestRouter.getComponentId", "root.MSG_GEN_PARAM_VALUE", "componentId=" + componentId + "spaceId=" + spaceId + " pathInfo=" + pathInfo); } } else { spaceId = "-1"; componentId = "-1"; function = "Error"; } String[] context = new String[] { spaceId, componentId, function }; SilverTrace.info("peasCore", "ComponentRequestRouter.getComponentId", "root.MSG_GEN_PARAM_VALUE", "spaceId=" + spaceId + " | componentId=" + componentId + " | function=" + function); return context; } public String[] getRoles(HttpServletRequest request) { MainSessionController controller = getMainSessionController(request); if (controller != null) { return organizationController.getUserProfiles(controller.getUserId(), getComponentId(request)[1]); } return ArrayUtil.EMPTY_STRING_ARRAY; } }
NicolasEYSSERIC/Silverpeas-Core
web-core/src/main/java/com/stratelia/silverpeas/peasCore/SilverpeasWebUtil.java
Java
agpl-3.0
5,021
/* * Copyright (c) 2012 - 2020 Splice Machine, Inc. * * This file is part of Splice Machine. * Splice Machine is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either * version 3, or (at your option) any later version. * Splice Machine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Splice Machine. * If not, see <http://www.gnu.org/licenses/>. */ package com.splicemachine.si.impl; import splice.com.google.common.base.Function; import com.splicemachine.si.api.txn.TransactionStatus; /** * Provides hooks for tests to provide callbacks. Mainly used to provide thread coordination in tests. It allows tests * to "trace" the internals of the SI execution. */ public class Tracer { private static transient Function<byte[],byte[]> fRowRollForward = null; private static transient Function<Long, Object> fTransactionRollForward = null; private static transient Function<Object[], Object> fStatus = null; private static transient Runnable fCompact = null; private static transient Function<Long, Object> fCommitting = null; private static transient Function<Long, Object> fWaiting = null; private static transient Function<Object[], Object> fRegion = null; private static transient Function<Object, String> bestAccess = null; public static Integer rollForwardDelayOverride = null; public static void registerRowRollForward(Function<byte[],byte[]> f) { Tracer.fRowRollForward = f; } public static boolean isTracingRowRollForward() { return Tracer.fRowRollForward != null; } public static void registerTransactionRollForward(Function<Long, Object> f) { Tracer.fTransactionRollForward = f; } public static boolean isTracingTransactionRollForward() { return Tracer.fTransactionRollForward != null; } public static void registerStatus(Function<Object[], Object> f) { Tracer.fStatus = f; } public static void registerCompact(Runnable f) { Tracer.fCompact = f; } public static void registerCommitting(Function<Long, Object> f) { Tracer.fCommitting = f; } public static void registerBestAccess(Function<Object, String> f) { Tracer.bestAccess = f; } public static void registerWaiting(Function<Long, Object> f) { Tracer.fWaiting = f; } public static void registerRegion(Function<Object[], Object> f) { Tracer.fRegion = f; } public static void traceRowRollForward(byte[] key) { if (fRowRollForward != null) { fRowRollForward.apply(key); } } public static void traceTransactionRollForward(long transactionId) { if (fTransactionRollForward != null) { fTransactionRollForward.apply(transactionId); } } public static void traceStatus(long transactionId, TransactionStatus newStatus, boolean beforeChange) { if (fStatus != null) { fStatus.apply(new Object[] {transactionId, newStatus, beforeChange}); } } public static void compact() { if (fCompact != null) { fCompact.run(); } } public static void traceCommitting(long transactionId) { if (fCommitting != null) { fCommitting.apply(transactionId); } } public static void traceWaiting(long transactionId) { if (fWaiting != null) { fWaiting.apply(transactionId); } } public static void traceRegion(String tableName, Object region) { if (fRegion != null) { fRegion.apply(new Object[] {tableName, region}); } } public static void traceBestAccess(Object objectParam) { if (bestAccess != null) { bestAccess.apply(objectParam); } } }
splicemachine/spliceengine
splice_si_api/src/main/java/com/splicemachine/si/impl/Tracer.java
Java
agpl-3.0
4,164
/* * JBILLING CONFIDENTIAL * _____________________ * * [2003] - [2012] Enterprise jBilling Software Ltd. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Enterprise jBilling Software. * The intellectual and technical concepts contained * herein are proprietary to Enterprise jBilling Software * and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden. */ package com.sapienter.jbilling.server.user; import com.sapienter.jbilling.server.user.contact.db.ContactDTO; import com.sapienter.jbilling.server.user.db.CompanyDAS; import com.sapienter.jbilling.server.user.db.CompanyDTO; import com.sapienter.jbilling.server.util.db.CurrencyDAS; import com.sapienter.jbilling.server.util.db.CurrencyDTO; import com.sapienter.jbilling.server.util.db.LanguageDAS; import javax.validation.Valid; import javax.validation.constraints.Size; public class CompanyWS implements java.io.Serializable { private int id; private Integer currencyId; private Integer languageId; @Size(min = 0, max = 100, message = "validation.error.size,0,100") private String description; @Valid private ContactWS contact; public CompanyWS() { } public CompanyWS(int i) { id = i; } public CompanyWS(CompanyDTO companyDto) { this.id = companyDto.getId(); this.currencyId= companyDto.getCurrencyId(); this.languageId = companyDto.getLanguageId(); this.description = companyDto.getDescription(); ContactDTO contact = new EntityBL(Integer.valueOf(this.id)).getContact(); if (contact != null) { this.contact = new ContactWS(contact.getId(), contact.getAddress1(), contact.getAddress2(), contact.getCity(), contact.getStateProvince(), contact.getPostalCode(), contact.getCountryCode(), contact.getDeleted()); } } public CompanyDTO getDTO(){ CompanyDTO dto = new CompanyDAS().find(Integer.valueOf(this.id)); dto.setCurrency(new CurrencyDAS().find(this.currencyId)); dto.setLanguage(new LanguageDAS().find(this.languageId)); dto.setDescription(this.description); return dto; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Integer getCurrencyId() { return currencyId; } public void setCurrencyId(Integer currencyId) { this.currencyId = currencyId; } public Integer getLanguageId() { return languageId; } public void setLanguageId(Integer languageId) { this.languageId = languageId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ContactWS getContact() { return contact; } public void setContact(ContactWS contact) { this.contact = contact; } public String toString() { return "CompanyWS [id=" + id + ", currencyId=" + currencyId + ", languageId=" + languageId + ", description=" + description + ", contact=" + contact + "]"; } }
rahith/ComtalkA-S
src/java/com/sapienter/jbilling/server/user/CompanyWS.java
Java
agpl-3.0
3,574
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/ */ package org.phenotips.variantStoreIntegration; import org.phenotips.data.similarity.internal.AbstractVariant; import org.phenotips.variantstore.shared.GACallInfoFields; import org.phenotips.variantstore.shared.GAVariantInfoFields; import org.phenotips.variantstore.shared.VariantUtils; import java.text.DecimalFormat; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.ga4gh.GACall; import org.ga4gh.GAVariant; /** * A variant from the variant store. Annotated by Exomiser. * * @version $Id$ */ public class VariantStoreVariant extends AbstractVariant { private static DecimalFormat df = new DecimalFormat("#.####"); /** * Create a {@link Variant} from a {@link GAVariant} returned by a {@link * org.phenotips.variantstore.VariantStoreInterface}. * * @param gaVariant a {@link GAVariant} * @param totIndividuals number of individuals stored in the variant store */ public VariantStoreVariant(GAVariant gaVariant, Integer totIndividuals) { setChrom(gaVariant.getReferenceName()); setPosition((int) (gaVariant.getStart() + 1)); GACall call = gaVariant.getCalls().get(0); List<Integer> genotype = call.getGenotype(); setGenotype(gaVariant.getReferenceBases(), StringUtils.join(gaVariant.getAlternateBases(), ','), StringUtils.join(genotype, '/')); setEffect(VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GENE_EFFECT)); String value = VariantUtils.getInfo(call, GACallInfoFields.EXOMISER_VARIANT_SCORE); if (value == null || "null".equals(value)) { setScore(null); } else { setScore(Double.valueOf(value)); } setAnnotation("geneScore", VariantUtils.getInfo(call, GACallInfoFields.EXOMISER_GENE_COMBINED_SCORE)); setAnnotation("geneSymbol", VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GENE)); setAnnotation("hgvs", VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GENE_HGVS)); value = VariantUtils.getInfo(gaVariant, GAVariantInfoFields.EXAC_AF); setAnnotation("exacAF", df.format(Double.valueOf(value))); setAnnotation("gtHet", VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GT_HET)); setAnnotation("gtHom", VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GT_HOM)); if (totIndividuals != null) { value = VariantUtils.getInfo(gaVariant, GAVariantInfoFields.AC_TOT); Double pcAF = Double.valueOf(value) / (totIndividuals * 2); setAnnotation("pcAF", df.format(pcAF)); } } }
phenotips/variant-store
integration/api/src/main/java/org/phenotips/variantStoreIntegration/VariantStoreVariant.java
Java
agpl-3.0
3,411
/* * Created on 20/giu/2010 * * Copyright 2010 by Andrea Vacondio (andrea.vacondio@gmail.com). * * This file is part of the Sejda source code * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sejda.model.exception; /** * Exception thrown when a wrong password has been set and it's not possible to open the pdf document (and execute the task) * * @author Andrea Vacondio * */ public class TaskWrongPasswordException extends TaskIOException { private static final long serialVersionUID = -5517166148313118559L; /** * @param message * @param cause */ public TaskWrongPasswordException(String message, Throwable cause) { super(message, cause); } /** * @param message */ public TaskWrongPasswordException(String message) { super(message); } /** * @param cause */ public TaskWrongPasswordException(Throwable cause) { super(cause); } }
torakiki/sejda
sejda-model/src/main/java/org/sejda/model/exception/TaskWrongPasswordException.java
Java
agpl-3.0
1,584
/* * Copyright (C) 2000 - 2016 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.personalorganizer.service; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.silverpeas.core.personalorganizer.model.JournalHeader; import org.silverpeas.core.personalorganizer.model.ParticipationStatus; import org.silverpeas.core.personalorganizer.model.SchedulableCount; import org.silverpeas.core.personalorganizer.socialnetwork.SocialInformationEvent; import org.silverpeas.core.util.StringUtil; import org.silverpeas.core.silvertrace.SilverTrace; import org.silverpeas.core.persistence.jdbc.DBUtil; import org.silverpeas.core.util.DateUtil; import org.silverpeas.core.exception.SilverpeasException; import org.silverpeas.core.exception.UtilException; public class JournalDAO { public static final String COLUMNNAMES = "id, name, delegatorId, description, priority, classification, startDay, startHour, endDay, endHour, externalId"; private static final String JOURNALCOLUMNNAMES = "CalendarJournal.id, CalendarJournal.name, CalendarJournal.delegatorId, CalendarJournal.description, CalendarJournal.priority, " + " CalendarJournal.classification, CalendarJournal.startDay, CalendarJournal.startHour, CalendarJournal.endDay, CalendarJournal.endHour, CalendarJournal.externalId"; private static final String INSERT_JOURNAL = "INSERT INTO CalendarJournal (" + COLUMNNAMES + ") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; private static final String UPDATE_JOURNAL = "UPDATE CalendarJournal SET name = ?, " + "delegatorId = ?, description = ?, priority = ?, classification = ?, " + "startDay = ?, startHour = ?, endDay = ?, endHour = ?, externalId = ? WHERE id = ?"; private static final String DELETE_JOURNAL = "DELETE FROM CalendarJournal WHERE id = ?"; public String addJournal(Connection con, JournalHeader journal) throws SQLException, UtilException, CalendarException { PreparedStatement prepStmt = null; int id = 0; try { prepStmt = con.prepareStatement(INSERT_JOURNAL); id = DBUtil.getNextId("CalendarJournal", "id"); prepStmt.setInt(1, id); prepStmt.setString(2, journal.getName()); prepStmt.setString(3, journal.getDelegatorId()); prepStmt.setString(4, journal.getDescription()); prepStmt.setInt(5, journal.getPriority().getValue()); prepStmt.setString(6, journal.getClassification().getString()); prepStmt.setString(7, journal.getStartDay()); prepStmt.setString(8, journal.getStartHour()); prepStmt.setString(9, journal.getEndDay()); prepStmt.setString(10, journal.getEndHour()); prepStmt.setString(11, journal.getExternalId()); if (prepStmt.executeUpdate() == 0) { throw new CalendarException( "JournalDAO.Connection con, addJournal(Connection con, JournalHeader journal)", SilverpeasException.ERROR, "calendar.EX_EXCUTE_INSERT_EMPTY"); } } finally { DBUtil.close(prepStmt); } return String.valueOf(id); } public void updateJournal(Connection con, JournalHeader journal) throws SQLException, CalendarException { PreparedStatement prepStmt = null; try { prepStmt = con.prepareStatement(UPDATE_JOURNAL); prepStmt.setString(1, journal.getName()); prepStmt.setString(2, journal.getDelegatorId()); prepStmt.setString(3, journal.getDescription()); prepStmt.setInt(4, journal.getPriority().getValue()); prepStmt.setString(5, journal.getClassification().getString()); prepStmt.setString(6, journal.getStartDay()); prepStmt.setString(7, journal.getStartHour()); prepStmt.setString(8, journal.getEndDay()); prepStmt.setString(9, journal.getEndHour()); prepStmt.setString(10, journal.getExternalId()); prepStmt.setInt(11, Integer.parseInt(journal.getId())); if (prepStmt.executeUpdate() == 0) { throw new CalendarException( "JournalDAO.Connection con, updateJournal(Connection con, JournalHeader journal)", SilverpeasException.ERROR, "calendar.EX_EXCUTE_UPDATE_EMPTY"); } } finally { DBUtil.close(prepStmt); } } public void removeJournal(Connection con, String id) throws SQLException, CalendarException { PreparedStatement prepStmt = null; try { prepStmt = con.prepareStatement(DELETE_JOURNAL); prepStmt.setInt(1, Integer.parseInt(id)); if (prepStmt.executeUpdate() == 0) { throw new CalendarException( "JournalDAO.Connection con, removeJournal(Connection con, JournalHeader journal)", SilverpeasException.ERROR, "calendar.EX_EXCUTE_DELETE_EMPTY"); } } finally { DBUtil.close(prepStmt); } } public boolean hasTentativeJournalsForUser(Connection con, String userId) throws SQLException, java.text.ParseException { PreparedStatement prepStmt = null; ResultSet rs = null; try { prepStmt = getTentativePreparedStatement(con, userId); rs = prepStmt.executeQuery(); return rs.next(); } finally { DBUtil.close(rs, prepStmt); } } public Collection<JournalHeader> getTentativeJournalHeadersForUser(Connection con, String userId) throws SQLException, java.text.ParseException { PreparedStatement prepStmt = null; ResultSet rs = null; List<JournalHeader> list = new ArrayList<JournalHeader>(); try { prepStmt = getTentativePreparedStatement(con, userId); rs = prepStmt.executeQuery(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(journal); } } finally { DBUtil.close(rs, prepStmt); } return list; } private PreparedStatement getTentativePreparedStatement( Connection con, String userId) throws SQLException { String selectStatement = "select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal, CalendarJournalAttendee " + " WHERE (CalendarJournal.id = CalendarJournalAttendee.journalId) " + " and (CalendarJournalAttendee.participationStatus = ?) " + " and (userId = ?) " + " order by startDay, startHour"; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, ParticipationStatus.TENTATIVE); prepStmt.setString(2, userId); return prepStmt; } private Collection<JournalHeader> getJournalHeadersForUser(Connection con, String day, String userId, String categoryId, String participation, String comparator) throws SQLException, java.text.ParseException { StringBuilder selectStatement = new StringBuilder(); selectStatement.append("select distinct ").append( JournalDAO.JOURNALCOLUMNNAMES).append( " from CalendarJournal, CalendarJournalAttendee "); if (categoryId != null) { selectStatement.append(", CalendarJournalCategory "); } selectStatement.append(" where (CalendarJournal.id = CalendarJournalAttendee.journalId) "); selectStatement.append(" and (userId = '").append(userId).append("'"); selectStatement.append(" and participationStatus = '").append(participation).append("') "); if (categoryId != null) { selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId) "); selectStatement.append(" and (CalendarJournalCategory.categoryId = '").append(categoryId). append("') "); } selectStatement.append(" and ((startDay ").append(comparator).append(" '").append(day).append( "') or (startDay <= '").append(day).append( "' and endDay >= '").append(day).append("')) "); if (participation.equals(ParticipationStatus.ACCEPTED)) { selectStatement.append("union ").append("select distinct ").append( JournalDAO.JOURNALCOLUMNNAMES).append(" from CalendarJournal "); if (categoryId != null) { selectStatement.append(", CalendarJournalCategory "); } selectStatement.append(" where (delegatorId = '").append(userId).append( "') "); if (categoryId != null) { selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId) "); selectStatement.append(" and (CalendarJournalCategory.categoryId = '").append(categoryId). append("') "); } selectStatement.append(" and ((startDay ").append(comparator).append(" '").append(day) .append( "') or (startDay <= '").append(day).append("' and endDay >= '").append(day).append( "')) "); } selectStatement.append(" order by 7 , 8 "); // Modif PHiL -> Interbase PreparedStatement prepStmt = null; ResultSet rs = null; List<JournalHeader> list = null; try { prepStmt = con.prepareStatement(selectStatement.toString()); rs = prepStmt.executeQuery(); list = new ArrayList<JournalHeader>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(journal); } } finally { DBUtil.close(rs, prepStmt); } return list; } public Collection<JournalHeader> getDayJournalHeadersForUser(Connection con, String day, String userId, String categoryId, String participation) throws SQLException, java.text.ParseException { return getJournalHeadersForUser(con, day, userId, categoryId, participation, "="); } public Collection<JournalHeader> getNextJournalHeadersForUser(Connection con, String day, String userId, String categoryId, String participation) throws SQLException, java.text.ParseException { return getJournalHeadersForUser(con, day, userId, categoryId, participation, ">="); } /** * get next JournalHeader for this user accordint to the type of data base * used(PostgreSQL,Oracle,MMS) * @param con * @param day * @param userId * @param classification * @param limit * @param offset * @return * @throws SQLException * @throws java.text.ParseException */ public List<JournalHeader> getNextEventsForUser(Connection con, String day, String userId, String classification, Date begin, Date end) throws SQLException, java.text.ParseException { String selectNextEvents = "select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal " + " where delegatorId = ? and endDay >= ? "; int classificationIndex = 2; int limitIndex = 3; if (StringUtil.isDefined(classification)) { selectNextEvents += " and classification = ? "; classificationIndex++; limitIndex++; } selectNextEvents += " and CalendarJournal.startDay >= ? and CalendarJournal.startDay <= ?"; selectNextEvents += " order by CalendarJournal.startDay, CalendarJournal.startHour "; PreparedStatement prepStmt = null; ResultSet rs = null; List<JournalHeader> list = null; try { prepStmt = con.prepareStatement(selectNextEvents); prepStmt.setString(1, userId); prepStmt.setString(2, day); if (classificationIndex == 3)// Classification param not null { prepStmt.setString(classificationIndex, classification); } prepStmt.setString(limitIndex, DateUtil.date2SQLDate(begin)); prepStmt.setString(limitIndex + 1, DateUtil.date2SQLDate(end)); rs = prepStmt.executeQuery(); list = new ArrayList<JournalHeader>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(journal); } } finally { DBUtil.close(rs, prepStmt); } return list; } public Collection<SchedulableCount> countMonthJournalsForUser(Connection con, String month, String userId, String categoryId, String participation) throws SQLException { StringBuilder selectStatement = new StringBuilder(200); String theDay = ""; selectStatement .append( "select count(distinct CalendarJournal.id), ? from CalendarJournal, CalendarJournalAttendee "); if (categoryId != null) { selectStatement.append(", CalendarJournalCategory "); } selectStatement.append("where (CalendarJournal.id = CalendarJournalAttendee.journalId) "); selectStatement.append("and (userId = ").append(userId); selectStatement.append(" and participationStatus = '").append(participation).append("')"); selectStatement.append(" and ((startDay = ?) or ((startDay <= ?) and (endDay >= ?))) "); if (categoryId != null) { selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId)"); selectStatement.append(" and (CalendarJournalCategory.categoryId = '").append(categoryId). append("') "); } selectStatement.append("group by ?"); if (participation.equals(ParticipationStatus.ACCEPTED)) { selectStatement.append( "union select count(distinct CalendarJournal.id), ? from CalendarJournal "); if (categoryId != null) { selectStatement.append(", CalendarJournalCategory "); } selectStatement.append("where (delegatorId = '").append(userId).append( "')"); selectStatement.append(" and ((startDay = ?) or ((startDay <= ?) and (endDay >= ?)))"); if (categoryId != null) { selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId)"); selectStatement.append(" and (CalendarJournalCategory.categoryId = '").append(categoryId). append("') "); } selectStatement.append("group by ?"); } List<SchedulableCount> list = new ArrayList<SchedulableCount>(); int number; String date = ""; PreparedStatement prepStmt = null; try { ResultSet rs = null; prepStmt = con.prepareStatement(selectStatement.toString()); for (int day = 1; day == 31; day++) { if (day < 10) { theDay = month + "0" + String.valueOf(day); } else { theDay = month + String.valueOf(day); } prepStmt.setString(1, theDay); prepStmt.setString(2, theDay); prepStmt.setString(3, theDay); prepStmt.setString(4, theDay); prepStmt.setString(5, theDay); prepStmt.setString(6, theDay); prepStmt.setString(7, theDay); prepStmt.setString(8, theDay); prepStmt.setString(9, theDay); prepStmt.setString(10, theDay); rs = prepStmt.executeQuery(); while (rs.next()) { number = rs.getInt(1); date = rs.getString(2); SchedulableCount count = new SchedulableCount(number, date); list.add(count); } DBUtil.close(rs); } } finally { DBUtil.close(prepStmt); } return list; } public Collection<JournalHeader> getPeriodJournalHeadersForUser(Connection con, String begin, String end, String userId, String categoryId, String participation) throws SQLException, java.text.ParseException { StringBuilder selectStatement = new StringBuilder(200); selectStatement.append("select distinct ").append(JournalDAO.COLUMNNAMES).append( " from CalendarJournal, CalendarJournalAttendee "); if (categoryId != null) { selectStatement.append(", CalendarJournalCategory "); } selectStatement.append(" where (CalendarJournal.id = CalendarJournalAttendee.journalId) "); selectStatement.append(" and (userId = '").append(userId).append("' "); selectStatement.append(" and participationStatus = '").append(participation).append("') "); if (categoryId != null) { selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId) "); selectStatement.append(" and (categoryId = '").append(categoryId).append( "') "); } selectStatement.append(" and ( (startDay >= '").append(begin).append( "' and startDay <= '").append(end).append("')"); selectStatement.append(" or (endDay >= '").append(begin).append( "' and endDay <= '").append(end).append("')"); selectStatement.append(" or ('").append(begin).append("' >= startDay and '").append(begin). append("' <= endDay) "); selectStatement.append(" or ('").append(end).append("' >= startDay and '").append(end).append( "' <= endDay) ) "); if (participation.equals(ParticipationStatus.ACCEPTED)) { selectStatement.append(" union select distinct ").append( JournalDAO.COLUMNNAMES).append(" from CalendarJournal "); if (categoryId != null) { selectStatement.append(", CalendarJournalCategory "); } selectStatement.append("where (delegatorId = '").append(userId).append( "') "); if (categoryId != null) { selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId) "); selectStatement.append(" and (categoryId = '").append(categoryId).append("') "); } selectStatement.append(" and ( (startDay >= '").append(begin).append( "' and startDay <= '").append(end).append("')"); selectStatement.append(" or (endDay >= '").append(begin).append( "' and endDay <= '").append(end).append("')"); selectStatement.append(" or ('").append(begin).append( "' >= startDay and '").append(begin).append("' <= endDay) "); selectStatement.append(" or ('").append(end).append("' >= startDay and '").append(end) .append( "' <= endDay) ) "); } selectStatement.append(" order by 7 , 8 "); PreparedStatement prepStmt = null; ResultSet rs = null; List<JournalHeader> list = null; try { prepStmt = con.prepareStatement(selectStatement.toString()); rs = prepStmt.executeQuery(); list = new ArrayList<JournalHeader>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(journal); } } finally { DBUtil.close(rs, prepStmt); } return list; } public JournalHeader getJournalHeaderFromResultSet(ResultSet rs) throws SQLException, java.text.ParseException { String id = String.valueOf(rs.getInt(1)); String name = rs.getString(2); String delegatorId = rs.getString(3); JournalHeader journal = new JournalHeader(id, name, delegatorId); journal.setDescription(rs.getString(4)); try { journal.getPriority().setValue(rs.getInt(5)); } catch (Exception e) { SilverTrace.warn("calendar", "JournalDAO.getJournalHeaderFromResultSet(ResultSet rs)", "calendar_MSG_NOT_GET_PRIORITY"); } journal.getClassification().setString(rs.getString(6)); journal.setStartDay(rs.getString(7)); journal.setStartHour(rs.getString(8)); journal.setEndDay(rs.getString(9)); journal.setEndHour(rs.getString(10)); journal.setExternalId(rs.getString(11)); return journal; } public JournalHeader getJournalHeader(Connection con, String journalId) throws SQLException, CalendarException, java.text.ParseException { String selectStatement = "select " + JournalDAO.COLUMNNAMES + " from CalendarJournal " + "where id = ?"; PreparedStatement prepStmt = null; ResultSet rs = null; JournalHeader journal; try { prepStmt = con.prepareStatement(selectStatement); prepStmt.setInt(1, Integer.parseInt(journalId)); rs = prepStmt.executeQuery(); if (rs.next()) { journal = getJournalHeaderFromResultSet(rs); } else { throw new CalendarException( "JournalDAO.Connection con, String journalId", SilverpeasException.ERROR, "calendar.EX_RS_EMPTY", "journalId=" + journalId); } return journal; } finally { DBUtil.close(rs, prepStmt); } } public Collection<JournalHeader> getOutlookJournalHeadersForUser(Connection con, String userId) throws SQLException, CalendarException, java.text.ParseException { String selectStatement = "select " + JournalDAO.COLUMNNAMES + " from CalendarJournal " + "where delegatorId = ? and externalId is not null"; PreparedStatement prepStmt = null; ResultSet rs = null; try { prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, userId); rs = prepStmt.executeQuery(); Collection<JournalHeader> list = new ArrayList<JournalHeader>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(journal); } return list; } finally { DBUtil.close(rs, prepStmt); } } public Collection<JournalHeader> getOutlookJournalHeadersForUserAfterDate( Connection con, String userId, java.util.Date startDate) throws SQLException, CalendarException, java.text.ParseException { String selectStatement = "select " + JournalDAO.COLUMNNAMES + " from CalendarJournal " + "where delegatorId = ? and startDay >= ? and externalId is not null"; PreparedStatement prepStmt = null; ResultSet rs = null; Collection<JournalHeader> list = null; try { prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, userId); prepStmt.setString(2, DateUtil.date2SQLDate(startDate)); rs = prepStmt.executeQuery(); list = new ArrayList<JournalHeader>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(journal); } return list; } finally { DBUtil.close(rs, prepStmt); } } public Collection<JournalHeader> getJournalHeadersForUserAfterDate(Connection con, String userId, java.util.Date startDate, int nbReturned) throws SQLException, CalendarException, java.text.ParseException { String selectStatement = "select " + JournalDAO.COLUMNNAMES + " from CalendarJournal " + "where delegatorId = ? " + "and ((startDay >= ?) or (startDay <= ? and endDay >= ?))" + " order by startDay, startHour"; PreparedStatement prepStmt = null; ResultSet rs = null; String startDateString = DateUtil.date2SQLDate(startDate); try { int count = 0; prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, userId); prepStmt.setString(2, startDateString); prepStmt.setString(3, startDateString); prepStmt.setString(4, startDateString); rs = prepStmt.executeQuery(); Collection<JournalHeader> list = new ArrayList<JournalHeader>(); while (rs.next() && nbReturned != count) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(journal); count++; } return list; } finally { DBUtil.close(rs, prepStmt); } } /** * get Next Social Events for a given list of my Contacts accordint to the type of data base * used(PostgreSQL,Oracle,MMS) . This includes all kinds of events * @param con * @param day * @param myId * @param myContactsIds * @param begin * @param end * @return List<SocialInformationEvent> * @throws SQLException * @throws ParseException */ public List<SocialInformationEvent> getNextEventsForMyContacts(Connection con, String day, String myId, List<String> myContactsIds, Date begin, Date end) throws SQLException, ParseException { String selectNextEvents = "select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal " + " where endDay >= ? and delegatorId in(" + toSqlString(myContactsIds) + ") " + " and startDay >= ? and startDay <= ? " + " order by startDay ASC, startHour ASC"; PreparedStatement prepStmt = null; ResultSet rs = null; try { prepStmt = con.prepareStatement(selectNextEvents); prepStmt.setString(1, day); prepStmt.setString(2, DateUtil.date2SQLDate(begin)); prepStmt.setString(3, DateUtil.date2SQLDate(end)); rs = prepStmt.executeQuery(); List<SocialInformationEvent> list = new ArrayList<SocialInformationEvent>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(new SocialInformationEvent(journal, journal.getId().equals(myId))); } return list; } finally { DBUtil.close(rs, prepStmt); } } private static String toSqlString(List<String> list) { StringBuilder result = new StringBuilder(100); if (list == null || list.isEmpty()) { return "''"; } int i = 0; for (String var : list) { if (i != 0) { result.append(","); } result.append("'").append(var).append("'"); i++; } return result.toString(); } /** * get Last Social Events for a given list of my Contacts accordint to the type of data base * used(PostgreSQL,Oracle,MMS) . This includes all kinds of events * @param con * @param day * @param myId * @param myContactsIds * @param begin * @param end * @return List<SocialInformationEvent> * @throws SQLException * @throws ParseException */ public List<SocialInformationEvent> getLastEventsForMyContacts(Connection con, String day, String myId, List<String> myContactsIds, Date begin, Date end) throws SQLException, ParseException { String selectNextEvents = "select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal " + " where endDay < ? and delegatorId in(" + toSqlString(myContactsIds) + ") " + " and startDay >= ? and startDay <= ? " + " order by startDay desc, startHour desc"; PreparedStatement prepStmt = null; ResultSet rs = null; List<SocialInformationEvent> list = null; try { prepStmt = con.prepareStatement(selectNextEvents); prepStmt.setString(1, day); prepStmt.setString(2, DateUtil.date2SQLDate(begin)); prepStmt.setString(3, DateUtil.date2SQLDate(end)); rs = prepStmt.executeQuery(); list = new ArrayList<SocialInformationEvent>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(new SocialInformationEvent(journal, journal.getId().equals(myId))); } } finally { DBUtil.close(rs, prepStmt); } return list; } /** * get my Last Social Events accordint to the type of data base used(PostgreSQL,Oracle,MMS) . This * includes all kinds of events * @param con * @param day * @param myId * @param numberOfElement * @param firstIndex * @return List<SocialInformationEvent> * @throws SQLException * @throws ParseException */ public List<SocialInformationEvent> getMyLastEvents(Connection con, String day, String myId, Date begin, Date end) throws SQLException, ParseException { String selectNextEvents = "select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal " + " where endDay < ? and delegatorId = ? " + " and startDay >= ? and startDay <= ? " + " order by startDay desc, startHour desc "; PreparedStatement prepStmt = null; ResultSet rs = null; List<SocialInformationEvent> list = null; try { prepStmt = con.prepareStatement(selectNextEvents); prepStmt.setString(1, day); prepStmt.setString(2, myId); prepStmt.setString(3, DateUtil.date2SQLDate(begin)); prepStmt.setString(4, DateUtil.date2SQLDate(end)); rs = prepStmt.executeQuery(); list = new ArrayList<SocialInformationEvent>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(new SocialInformationEvent(journal)); } } finally { DBUtil.close(rs, prepStmt); } return list; } /** * get my Last Social Events when data base is MMS. This includes all kinds of events * @param con * @param day * @param myId * @param numberOfElement * @param firstIndex * @return * @throws SQLException * @throws java.text.ParseException */ public List<SocialInformationEvent> getMyLastEvents_MSS(Connection con, String day, String myId, Date begin, Date end) throws SQLException, java.text.ParseException { String selectNextEvents = "select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal " + " where endDay < ? and delegatorId = ? " + " and startDay >= ? and startDay <= ? " + " order by CalendarJournal.startDay desc, CalendarJournal.startHour desc"; PreparedStatement prepStmt = null; ResultSet rs = null; List<SocialInformationEvent> list = null; try { prepStmt = con.prepareStatement(selectNextEvents); prepStmt.setString(1, day); prepStmt.setString(2, myId); prepStmt.setString(3, DateUtil.date2SQLDate(begin)); prepStmt.setString(4, DateUtil.date2SQLDate(end)); rs = prepStmt.executeQuery(); list = new ArrayList<SocialInformationEvent>(); while (rs.next()) { JournalHeader journal = getJournalHeaderFromResultSet(rs); list.add(new SocialInformationEvent(journal)); } } finally { DBUtil.close(rs, prepStmt); } return list; } }
auroreallibe/Silverpeas-Core
core-services/personalOrganizer/src/main/java/org/silverpeas/core/personalorganizer/service/JournalDAO.java
Java
agpl-3.0
30,469
/** * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of the GPL, you may * redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS") * applications as described in Silverpeas's FLOSS exception. You should have received a copy of the * text describing the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.beans.admin; import java.util.ArrayList; import java.util.List; import com.silverpeas.util.StringUtil; import com.stratelia.webactiv.organization.AdminPersistenceException; import com.stratelia.webactiv.organization.SpaceRow; import com.stratelia.webactiv.organization.SpaceUserRoleRow; import com.stratelia.webactiv.util.exception.SilverpeasException; public class SpaceProfileInstManager { /** * Constructor */ public SpaceProfileInstManager() { } /** * Create a new space profile instance in database * * * @param spaceProfileInst * @param domainManager * @param sFatherId * @return * @throws AdminException */ public String createSpaceProfileInst(SpaceProfileInst spaceProfileInst, DomainDriverManager domainManager, String parentSpaceId) throws AdminException { try { // Create the spaceProfile node SpaceUserRoleRow newRole = makeSpaceUserRoleRow(spaceProfileInst); newRole.spaceId = idAsInt(parentSpaceId); domainManager.getOrganization().spaceUserRole.createSpaceUserRole(newRole); String spaceProfileNodeId = idAsString(newRole.id); // Update the CSpace with the links TSpaceProfile-TGroup for (String groupId : spaceProfileInst.getAllGroups()) { domainManager.getOrganization().spaceUserRole.addGroupInSpaceUserRole(idAsInt(groupId), idAsInt(spaceProfileNodeId)); } // Update the CSpace with the links TSpaceProfile-TUser for (String userId : spaceProfileInst.getAllUsers()) { domainManager.getOrganization().spaceUserRole.addUserInSpaceUserRole(idAsInt(userId), idAsInt(spaceProfileNodeId)); } return spaceProfileNodeId; } catch (Exception e) { throw new AdminException("SpaceProfileInstManager.addSpaceProfileInst", SilverpeasException.ERROR, "admin.EX_ERR_ADD_SPACE_PROFILE", "space profile name: '" + spaceProfileInst.getName() + "'", e); } } /** * Get Space profile information with given id and creates a new SpaceProfileInst * * @param ddManager * @param spaceProfileId * @param parentSpaceId * @return * @throws AdminException */ public SpaceProfileInst getSpaceProfileInst(DomainDriverManager ddManager, String spaceProfileId, String parentSpaceId) throws AdminException { if (!StringUtil.isDefined(parentSpaceId)) { try { ddManager.getOrganizationSchema(); SpaceRow space = ddManager.getOrganization().space.getSpaceOfSpaceUserRole(idAsInt( spaceProfileId)); if (space == null) { space = new SpaceRow(); } parentSpaceId = idAsString(space.id); } catch (Exception e) { throw new AdminException("SpaceProfileInstManager.getSpaceProfileInst", SilverpeasException.ERROR, "admin.EX_ERR_GET_SPACE_PROFILE", "space profile Id: '" + spaceProfileId + "', space Id: '" + parentSpaceId + "'", e); } finally { ddManager.releaseOrganizationSchema(); } } try { ddManager.getOrganizationSchema(); // Load the profile detail SpaceUserRoleRow spaceUserRole = ddManager.getOrganization().spaceUserRole. getSpaceUserRole(idAsInt(spaceProfileId)); SpaceProfileInst spaceProfileInst = null; if (spaceUserRole != null) { // Set the attributes of the space profile Inst spaceProfileInst = spaceUserRoleRow2SpaceProfileInst(spaceUserRole); setUsersAndGroups(ddManager, spaceProfileInst); } return spaceProfileInst; } catch (Exception e) { throw new AdminException("SpaceProfileInstManager.getSpaceProfileInst", SilverpeasException.ERROR, "admin.EX_ERR_SET_SPACE_PROFILE", "space profile Id: '" + spaceProfileId + "', space Id: '" + parentSpaceId + "'", e); } finally { ddManager.releaseOrganizationSchema(); } } /** * get information for given id and store it in the given SpaceProfileInst object * * @param ddManager * @param spaceId * @param roleName * @throws AdminException */ public SpaceProfileInst getInheritedSpaceProfileInstByName(DomainDriverManager ddManager, String spaceId, String roleName) throws AdminException { return getSpaceProfileInst(ddManager, spaceId, roleName, true); } public SpaceProfileInst getSpaceProfileInstByName(DomainDriverManager ddManager, String spaceId, String roleName) throws AdminException { return getSpaceProfileInst(ddManager, spaceId, roleName, false); } private SpaceProfileInst getSpaceProfileInst(DomainDriverManager ddManager, String spaceId, String roleName, boolean isInherited) throws AdminException { try { ddManager.getOrganizationSchema(); int inherited = 0; if (isInherited) { inherited = 1; } // Load the profile detail SpaceUserRoleRow spaceUserRole = ddManager.getOrganization().spaceUserRole. getSpaceUserRole(idAsInt(spaceId), roleName, inherited); SpaceProfileInst spaceProfileInst = null; if (spaceUserRole != null) { // Set the attributes of the space profile Inst spaceProfileInst = spaceUserRoleRow2SpaceProfileInst(spaceUserRole); setUsersAndGroups(ddManager, spaceProfileInst); } return spaceProfileInst; } catch (Exception e) { throw new AdminException("SpaceProfileInstManager.getInheritedSpaceProfileInst", SilverpeasException.ERROR, "admin.EX_ERR_GET_SPACE_PROFILE", "spaceId = " + spaceId + ", role = " + roleName, e); } finally { ddManager.releaseOrganizationSchema(); } } private void setUsersAndGroups(DomainDriverManager ddManager, SpaceProfileInst spaceProfileInst) throws AdminPersistenceException { // Get the groups String[] asGroupIds = ddManager.getOrganization().group. getDirectGroupIdsInSpaceUserRole(idAsInt(spaceProfileInst.getId())); // Set the groups to the space profile if (asGroupIds != null) { for (String groupId : asGroupIds) { spaceProfileInst.addGroup(groupId); } } // Get the Users String[] asUsersIds = ddManager.getOrganization().user.getDirectUserIdsOfSpaceUserRole(idAsInt( spaceProfileInst.getId())); // Set the Users to the space profile if (asUsersIds != null) { for (String userId : asUsersIds) { spaceProfileInst.addUser(userId); } } } private SpaceProfileInst spaceUserRoleRow2SpaceProfileInst(SpaceUserRoleRow spaceUserRole) { // Set the attributes of the space profile Inst SpaceProfileInst spaceProfileInst = new SpaceProfileInst(); spaceProfileInst.setId(Integer.toString(spaceUserRole.id)); spaceProfileInst.setName(spaceUserRole.roleName); spaceProfileInst.setLabel(spaceUserRole.name); spaceProfileInst.setDescription(spaceUserRole.description); spaceProfileInst.setSpaceFatherId(Integer.toString(spaceUserRole.spaceId)); if (spaceUserRole.isInherited == 1) { spaceProfileInst.setInherited(true); } return spaceProfileInst; } /** * Deletes space profile instance from Silverpeas * * @param spaceProfileInst * @param ddManager * @throws AdminException */ public void deleteSpaceProfileInst(SpaceProfileInst spaceProfileInst, DomainDriverManager ddManager) throws AdminException { try { // delete the spaceProfile node ddManager.getOrganization().spaceUserRole.removeSpaceUserRole(idAsInt(spaceProfileInst .getId())); } catch (Exception e) { throw new AdminException("SpaceProfileInstManager.deleteSpaceProfileInst", SilverpeasException.ERROR, "admin.EX_ERR_DELETE_SPACEPROFILE", "space profile Id: '" + spaceProfileInst.getId() + "'", e); } } /** * Updates space profile instance * * @param spaceProfileInst * @param ddManager * @param spaceProfileInstNew * @return * @throws AdminException */ public String updateSpaceProfileInst(SpaceProfileInst spaceProfileInst, DomainDriverManager ddManager, SpaceProfileInst spaceProfileInstNew) throws AdminException { List<String> alOldSpaceProfileGroup = new ArrayList<String>(); List<String> alNewSpaceProfileGroup = new ArrayList<String>(); List<String> alAddGroup = new ArrayList<String>(); List<String> alRemGroup = new ArrayList<String>(); List<String> alOldSpaceProfileUser = new ArrayList<String>(); List<String> alNewSpaceProfileUser = new ArrayList<String>(); List<String> alAddUser = new ArrayList<String>(); List<String> alRemUser = new ArrayList<String>(); try { // Compute the Old spaceProfile group list List<String> alGroup = spaceProfileInst.getAllGroups(); for (String groupId : alGroup) { alOldSpaceProfileGroup.add(groupId); } // Compute the New spaceProfile group list alGroup = spaceProfileInstNew.getAllGroups(); for (String groupId : alGroup) { alNewSpaceProfileGroup.add(groupId); } // Compute the remove group list for (String groupId : alOldSpaceProfileGroup) { if (!alNewSpaceProfileGroup.contains(groupId)) { alRemGroup.add(groupId); } } // Compute the add and stay group list for (String groupId : alNewSpaceProfileGroup) { if (!alOldSpaceProfileGroup.contains(groupId)) { alAddGroup.add(groupId); } } // Add the new Groups for (String groupId : alAddGroup) { // Create the links between the spaceProfile and the group ddManager.getOrganization().spaceUserRole.addGroupInSpaceUserRole( idAsInt(groupId), idAsInt(spaceProfileInst.getId())); } // Remove the removed groups for (String groupId : alRemGroup) { // delete the node link SpaceProfile_Group ddManager.getOrganization().spaceUserRole.removeGroupFromSpaceUserRole( idAsInt(groupId), idAsInt(spaceProfileInst.getId())); } // Compute the Old spaceProfile User list ArrayList<String> alUser = spaceProfileInst.getAllUsers(); for (String userId : alUser) { alOldSpaceProfileUser.add(userId); } // Compute the New spaceProfile User list alUser = spaceProfileInstNew.getAllUsers(); for (String userId : alUser) { alNewSpaceProfileUser.add(userId); } // Compute the remove User list for (String userId : alOldSpaceProfileUser) { if (!alNewSpaceProfileUser.contains(userId)) { alRemUser.add(userId); } } // Compute the add and stay User list for (String userId : alNewSpaceProfileUser) { if (!alOldSpaceProfileUser.contains(userId)) { alAddUser.add(userId); } } // Add the new Users for (String userId : alAddUser) { // Create the links between the spaceProfile and the User ddManager.getOrganization().spaceUserRole.addUserInSpaceUserRole( idAsInt(userId), idAsInt(spaceProfileInst.getId())); } // Remove the removed Users for (String userId : alRemUser) { // delete the node link SpaceProfile_User ddManager.getOrganization().spaceUserRole.removeUserFromSpaceUserRole( idAsInt(userId), idAsInt(spaceProfileInst.getId())); } // update the spaceProfile node SpaceUserRoleRow changedSpaceUserRole = makeSpaceUserRoleRow(spaceProfileInstNew); changedSpaceUserRole.id = idAsInt(spaceProfileInstNew.getId()); ddManager.getOrganization().spaceUserRole.updateSpaceUserRole(changedSpaceUserRole); return idAsString(changedSpaceUserRole.id); } catch (Exception e) { throw new AdminException("SpaceProfileInstManager.updateSpaceProfileInst", SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_SPACEPROFILE", "space profile Id: '" + spaceProfileInst.getId() + "'", e); } } /** * Converts SpaceProfileInst to SpaceUserRoleRow */ private SpaceUserRoleRow makeSpaceUserRoleRow(SpaceProfileInst spaceProfileInst) { SpaceUserRoleRow spaceUserRole = new SpaceUserRoleRow(); spaceUserRole.id = idAsInt(spaceProfileInst.getId()); spaceUserRole.roleName = spaceProfileInst.getName(); spaceUserRole.name = spaceProfileInst.getLabel(); spaceUserRole.description = spaceProfileInst.getDescription(); if (spaceProfileInst.isInherited()) { spaceUserRole.isInherited = 1; } return spaceUserRole; } /** * Convert String Id to int Id */ private int idAsInt(String id) { if (id == null || id.length() == 0) { return -1; // the null id. } try { return Integer.parseInt(id); } catch (NumberFormatException e) { return -1; // the null id. } } /** * Convert int Id to String Id */ static private String idAsString(int id) { return Integer.toString(id); } }
CecileBONIN/Silverpeas-Core
lib-core/src/main/java/com/stratelia/webactiv/beans/admin/SpaceProfileInstManager.java
Java
agpl-3.0
14,175
package org.bimserver.database.query.literals; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import org.bimserver.database.query.conditions.LiteralCondition; public class StringLiteral extends LiteralCondition { private final String value; public StringLiteral(String value) { this.value = value; } public Object getValue() { return value; } }
opensourceBIM/BIMserver
BimServer/src/org/bimserver/database/query/literals/StringLiteral.java
Java
agpl-3.0
1,207
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc4; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Ifc Sub Contract Resource Type Enum</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcSubContractResourceTypeEnum() * @model * @generated */ public enum IfcSubContractResourceTypeEnum implements Enumerator { /** * The '<em><b>NULL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NULL_VALUE * @generated * @ordered */ NULL(0, "NULL", "NULL"), /** * The '<em><b>NOTDEFINED</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NOTDEFINED_VALUE * @generated * @ordered */ NOTDEFINED(1, "NOTDEFINED", "NOTDEFINED"), /** * The '<em><b>WORK</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #WORK_VALUE * @generated * @ordered */ WORK(2, "WORK", "WORK"), /** * The '<em><b>USERDEFINED</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #USERDEFINED_VALUE * @generated * @ordered */ USERDEFINED(3, "USERDEFINED", "USERDEFINED"), /** * The '<em><b>PURCHASE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PURCHASE_VALUE * @generated * @ordered */ PURCHASE(4, "PURCHASE", "PURCHASE"); /** * The '<em><b>NULL</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>NULL</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NULL * @model * @generated * @ordered */ public static final int NULL_VALUE = 0; /** * The '<em><b>NOTDEFINED</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>NOTDEFINED</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NOTDEFINED * @model * @generated * @ordered */ public static final int NOTDEFINED_VALUE = 1; /** * The '<em><b>WORK</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>WORK</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #WORK * @model * @generated * @ordered */ public static final int WORK_VALUE = 2; /** * The '<em><b>USERDEFINED</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>USERDEFINED</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #USERDEFINED * @model * @generated * @ordered */ public static final int USERDEFINED_VALUE = 3; /** * The '<em><b>PURCHASE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>PURCHASE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PURCHASE * @model * @generated * @ordered */ public static final int PURCHASE_VALUE = 4; /** * An array of all the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final IfcSubContractResourceTypeEnum[] VALUES_ARRAY = new IfcSubContractResourceTypeEnum[] { NULL, NOTDEFINED, WORK, USERDEFINED, PURCHASE, }; /** * A public read-only list of all the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<IfcSubContractResourceTypeEnum> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcSubContractResourceTypeEnum get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { IfcSubContractResourceTypeEnum result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcSubContractResourceTypeEnum getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { IfcSubContractResourceTypeEnum result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcSubContractResourceTypeEnum get(int value) { switch (value) { case NULL_VALUE: return NULL; case NOTDEFINED_VALUE: return NOTDEFINED; case WORK_VALUE: return WORK; case USERDEFINED_VALUE: return USERDEFINED; case PURCHASE_VALUE: return PURCHASE; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private IfcSubContractResourceTypeEnum(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //IfcSubContractResourceTypeEnum
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc4/IfcSubContractResourceTypeEnum.java
Java
agpl-3.0
7,689
///* // * Tanaguru - Automated webpage assessment // * Copyright (C) 2008-2017 Tanaguru.org // * // * This program is free software: you can redistribute it and/or modify // * it under the terms of the GNU Affero General Public License as // * published by the Free Software Foundation, either version 3 of the // * License, or (at your option) any later version. // * // * This program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU Affero General Public License for more details. // * // * You should have received a copy of the GNU Affero General Public License // * along with this program. If not, see <http://www.gnu.org/licenses/>. // * // * Contact us by mail: tanaguru AT tanaguru DOT org // */ //package org.tanaguru.rules.rgaa32017; // //import org.apache.commons.lang3.tuple.ImmutablePair; //import org.tanaguru.entity.audit.ProcessResult; //import org.tanaguru.entity.audit.TestSolution; //import org.tanaguru.rules.keystore.HtmlElementStore; //import org.tanaguru.rules.keystore.RemarkMessageStore; //import org.tanaguru.rules.rgaa32017.test.Rgaa32017RuleImplementationTestCase; // ///** // * Unit test class for the implementation of the rule 10-9-1 of the referential Rgaa 3-2017. // * // * @author // */ //public class Rgaa32017Rule100901Test extends Rgaa32017RuleImplementationTestCase { // // /** // * Default constructor // * @param testName // */ // public Rgaa32017Rule100901Test (String testName){ // super(testName); // } // // @Override // protected void setUpRuleImplementationClassName() { // setRuleImplementationClassName( // "org.tanaguru.rules.rgaa32017.Rgaa32017Rule100901"); // } // // @Override // protected void setUpWebResourceMap() { // addWebResource("Rgaa32017.Test.10.9.1-1Passed-01"); // addWebResource("Rgaa32017.Test.10.9.1-2Failed-01"); // addWebResource("Rgaa32017.Test.10.9.1-2Failed-02"); // // addWebResource("Rgaa32017.Test.10.9.1-3NMI-01"); //// addWebResource("Rgaa32017.Test.10.9.1-4NA-01"); // } // // @Override // protected void setProcess() { // //---------------------------------------------------------------------- // //------------------------------1Passed-01------------------------------ // //---------------------------------------------------------------------- // // checkResultIsPassed(processPageTest("Rgaa32017.Test.10.9.1-1Passed-01"), 0); // // //---------------------------------------------------------------------- // //------------------------------2Failed-01------------------------------ // //---------------------------------------------------------------------- // ProcessResult processResult = processPageTest("Rgaa32017.Test.10.9.1-2Failed-01"); // checkResultIsFailed(processResult, 1, 1); //// checkRemarkIsPresent( //// processResult, //// TestSolution.FAILED, //// CHECK_IF_USER_HAVE_MECHANISM_TO_DELETE_JUSTIFY_TEXT_ALIGN_MSG, //// "h1", //// 1, //// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue")); // //---------------------------------------------------------------------- // //------------------------------2Failed-02------------------------------ // //---------------------------------------------------------------------- // processResult = processPageTest("Rgaa32017.Test.10.9.1-2Failed-02"); // checkResultIsFailed(processResult, 1, 1); //// checkRemarkIsPresent( //// processResult, //// TestSolution.FAILED, //// RemarkMessageStore.CHECK_IF_USER_HAVE_MECHANISM_TO_DELETE_JUSTIFY_TEXT_ALIGN_MSG, //// HtmlElementStore.P_ELEMENT, //// 1, //// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue")); // // //---------------------------------------------------------------------- // //------------------------------3NMI-01--------------------------------- // //---------------------------------------------------------------------- //// ProcessResult processResult = processPageTest("Rgaa32017.Test.10.9.1-3NMI-01"); //// checkResultIsNotTested(processResult); // temporary result to make the result buildable before implementation //// checkResultIsPreQualified(processResult, 1, 1); //// checkRemarkIsPresent( //// processResult, //// TestSolution.NEED_MORE_INFO, //// CHECK_IF_USER_HAVE_MECHANISM_TO_DELETE_JUSTIFY_TEXT_ALIGN_MSG, //// "p", //// 1); // // // //---------------------------------------------------------------------- // //------------------------------4NA-01------------------------------ // //---------------------------------------------------------------------- //// checkResultIsNotApplicable(processPageTest("Rgaa32017.Test.10.9.1-4NA-01")); // } // // @Override // protected void setConsolidate() { // // // The consolidate method can be removed when real implementation is done. // // The assertions are automatically tested regarding the file names by // // the abstract parent class //// assertEquals(TestSolution.NOT_TESTED, //// consolidate("Rgaa32017.Test.10.9.1-3NMI-01").getValue()); // } // //}
Tanaguru/Tanaguru
rules/rgaa3-2017/src/test/java/org/tanaguru/rules/rgaa32017/Rgaa32017Rule100901Test.java
Java
agpl-3.0
5,642
/* * Copyright 2013 Anton Tananaev (anton.tananaev@gmail.com) * * 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 pl.datamatica.traccar.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.gwt.core.shared.GwtIncompatible; import com.google.gwt.user.client.rpc.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.*; import org.hibernate.annotations.Filter; import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.SQLDelete; import com.google.gwt.user.datepicker.client.CalendarUtil; import java.util.HashSet; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; @Entity @Table(name = "devices", indexes = { @Index(name = "devices_pkey", columnList = "id") }, uniqueConstraints = { @UniqueConstraint(name = "devices_ukey_uniqueid", columnNames = "uniqueid") }) @SQLDelete(sql="UPDATE devices d SET d.deleted = 1 WHERE d.id = ?") @FilterDef(name="softDelete", defaultCondition="deleted = 0") @Filter(name="softDelete") public class Device extends TimestampedEntity implements IsSerializable, GroupedDevice { private static final long serialVersionUID = 1; public static final short DEFAULT_TIMEOUT = 5 * 60; public static final short DEFAULT_MIN_IDLE_TIME = 1 * 60; public static final String DEFAULT_MOVING_ARROW_COLOR = "00017A"; public static final String DEFAULT_PAUSED_ARROW_COLOR = "B12222"; public static final String DEFAULT_STOPPED_ARROW_COLOR = "016400"; public static final String DEFAULT_OFFLINE_ARROW_COLOR = "778899"; public static final String DEFAULT_COLOR = "0000FF"; public static final double DEFAULT_ARROW_RADIUS = 5; public static final int NEAR_EXPIRATION_THRESHOLD_DAYS = 7; public Device() { iconType = DeviceIconType.DEFAULT; iconMode = DeviceIconMode.ICON; iconArrowMovingColor = DEFAULT_MOVING_ARROW_COLOR; iconArrowPausedColor = DEFAULT_PAUSED_ARROW_COLOR; iconArrowStoppedColor = DEFAULT_STOPPED_ARROW_COLOR; iconArrowOfflineColor = DEFAULT_OFFLINE_ARROW_COLOR; iconArrowRadius = DEFAULT_ARROW_RADIUS; color = DEFAULT_COLOR; deviceModelId = -1; showName = true; showProtocol = true; showOdometer = true; } public Device(Device device) { id = device.id; uniqueId = device.uniqueId; name = device.name; description = device.description; phoneNumber = device.phoneNumber; plateNumber = device.plateNumber; vehicleInfo = device.vehicleInfo; timeout = device.timeout; idleSpeedThreshold = device.idleSpeedThreshold; minIdleTime = device.minIdleTime; speedLimit = device.speedLimit; fuelCapacity = device.fuelCapacity; iconType = device.iconType; icon = device.getIcon(); photo = device.getPhoto(); odometer = device.odometer; autoUpdateOdometer = device.autoUpdateOdometer; if (device.maintenances != null) { maintenances = new ArrayList<>(device.maintenances.size()); for (Maintenance maintenance : device.maintenances) { maintenances.add(new Maintenance(maintenance)); } } if (device.registrations != null) { registrations = new ArrayList<>(device.registrations.size()); for(RegistrationMaintenance registration : device.registrations) registrations.add(new RegistrationMaintenance(registration)); } if (device.sensors != null) { sensors = new ArrayList<>(device.sensors.size()); for (Sensor sensor : device.sensors) { sensors.add(new Sensor(sensor)); } } if (device.latestPosition != null) latestPosition = new Position(device.latestPosition); group = device.group == null ? null : new Group(device.group.getId()).copyFrom(device.group); deviceModelId = device.deviceModelId; iconId = device.iconId; customIconId = device.customIconId; iconMode = device.iconMode; iconArrowMovingColor = device.iconArrowMovingColor; iconArrowPausedColor = device.iconArrowPausedColor; iconArrowStoppedColor = device.iconArrowStoppedColor; iconArrowOfflineColor = device.iconArrowOfflineColor; iconArrowRadius = device.iconArrowRadius; showName = device.showName; showProtocol = device.showProtocol; showOdometer = device.showOdometer; timezoneOffset = device.timezoneOffset; commandPassword = device.commandPassword; protocol = device.protocol; historyLength = device.historyLength; validTo = device.validTo; color = device.color; users = new HashSet<>(device.users); owner = device.owner; ignition = device.ignition; ignTime = device.ignTime; setLastUpdate(device.getLastUpdate()); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, updatable = false, unique = true) private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } @GwtTransient @OneToOne(fetch = FetchType.EAGER) @JoinColumn(foreignKey = @ForeignKey(name = "devices_fkey_position_id")) @JsonIgnore private Position latestPosition; public void setLatestPosition(Position latestPosition) { this.latestPosition = latestPosition; } public Position getLatestPosition() { return latestPosition; } private String uniqueId; public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } public String getUniqueId() { return uniqueId; } private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /** * Consider device offline after 'timeout' seconds spent from last position */ @Column(nullable = true) private int timeout = DEFAULT_TIMEOUT; public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } @Column(nullable = true) private double idleSpeedThreshold; public double getIdleSpeedThreshold() { return idleSpeedThreshold; } public void setIdleSpeedThreshold(double idleSpeedThreshold) { this.idleSpeedThreshold = idleSpeedThreshold; } @Column(nullable = true) private int minIdleTime = DEFAULT_MIN_IDLE_TIME; public int getMinIdleTime() { return minIdleTime; } public void setMinIdleTime(int minIdleTime) { this.minIdleTime = minIdleTime; } @Column(nullable = true) private Double speedLimit; public Double getSpeedLimit() { return speedLimit; } public void setSpeedLimit(Double speedLimit) { this.speedLimit = speedLimit; } @Column(nullable = true) private Double fuelCapacity; public Double getFuelCapacity() { return fuelCapacity; } public void setFuelCapacity(Double fuelCapacity) { this.fuelCapacity = fuelCapacity; } // Hibernate bug HHH-8783: (http://hibernate.atlassian.net/browse/HHH-8783) // ForeignKey(name) has no effect in JoinTable (and others). It is // reported as closed but the comments indicate it is still not fixed // for @JoinTable() and targeted to be fixed in 5.x :-(. // @GwtTransient @ManyToMany(fetch = FetchType.LAZY) @Fetch(FetchMode.SUBSELECT) @JoinTable(name = "users_devices", foreignKey = @ForeignKey(name = "users_devices_fkey_devices_id"), joinColumns = { @JoinColumn(name = "devices_id", table = "devices", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "users_id", table = "users", referencedColumnName = "id") }) @JsonIgnore private Set<User> users; public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } @GwtTransient @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(foreignKey = @ForeignKey(name = "devices_fkey_owner_id")) @JsonIgnore private User owner; public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } @Enumerated(EnumType.STRING) private DeviceIconType iconType; public DeviceIconType getIconType() { return iconType; } public void setIconType(DeviceIconType iconType) { this.iconType = iconType; } @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "devices_fkey_icon_id")) private DeviceIcon icon; public DeviceIcon getIcon() { return icon; } public void setIcon(DeviceIcon icon) { this.icon = icon; } @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "devices_fkey_photo_id")) @JsonIgnore private Picture photo; public Picture getPhoto() { return photo; } public void setPhoto(Picture photo) { this.photo = photo; } @JsonIgnore private String phoneNumber; public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @JsonIgnore private String plateNumber; public String getPlateNumber() { return plateNumber; } public void setPlateNumber(String plateNumber) { this.plateNumber = plateNumber; } @JsonIgnore private String vehicleInfo; public String getVehicleInfo() { return vehicleInfo; } public void setVehicleInfo(String vehicleInfo) { this.vehicleInfo = vehicleInfo; } // contains current odometer value in kilometers @Column(nullable = true) @JsonIgnore private double odometer; public double getOdometer() { return odometer; } public void setOdometer(double odometer) { this.odometer = odometer; } // indicates that odometer must be updated automatically by positions history @Column(nullable = true) @JsonIgnore private boolean autoUpdateOdometer; public boolean isAutoUpdateOdometer() { return autoUpdateOdometer; } public void setAutoUpdateOdometer(boolean autoUpdateOdometer) { this.autoUpdateOdometer = autoUpdateOdometer; } @Transient private List<Maintenance> maintenances; public List<Maintenance> getMaintenances() { return maintenances; } public void setMaintenances(List<Maintenance> maintenances) { this.maintenances = maintenances; } @Transient private List<RegistrationMaintenance> registrations; public List<RegistrationMaintenance> getRegistrations() { return registrations; } public void setRegistrations(List<RegistrationMaintenance> registrations) { this.registrations = registrations; } @Transient private List<Sensor> sensors; public List<Sensor> getSensors() { return sensors; } public void setSensors(List<Sensor> sensors) { this.sensors = sensors; } @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "devices_fkey_group_id")) private Group group; public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } @Column(nullable = true, length = 128) private String status; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Enumerated(EnumType.STRING) private DeviceIconMode iconMode; public DeviceIconMode getIconMode() { return iconMode; } public void setIconMode(DeviceIconMode iconMode) { this.iconMode = iconMode; } private String iconArrowMovingColor; private String iconArrowPausedColor; private String iconArrowStoppedColor; private String iconArrowOfflineColor; public String getIconArrowMovingColor() { return iconArrowMovingColor; } public void setIconArrowMovingColor(String iconArrowMovingColor) { this.iconArrowMovingColor = iconArrowMovingColor; } public String getIconArrowPausedColor() { return iconArrowPausedColor; } public void setIconArrowPausedColor(String iconArrowPausedColor) { this.iconArrowPausedColor = iconArrowPausedColor; } public String getIconArrowStoppedColor() { return iconArrowStoppedColor; } public void setIconArrowStoppedColor(String iconArrowStoppedColor) { this.iconArrowStoppedColor = iconArrowStoppedColor; } public String getIconArrowOfflineColor() { return iconArrowOfflineColor; } public void setIconArrowOfflineColor(String iconArrowOfflineColor) { this.iconArrowOfflineColor = iconArrowOfflineColor; } @Column(nullable = true) private boolean iconRotation; @Column(nullable = true) private double iconArrowRadius; public double getIconArrowRadius() { return iconArrowRadius; } public void setIconArrowRadius(double iconArrowRadius) { this.iconArrowRadius = iconArrowRadius; } @Column(nullable = true) private boolean showName; public boolean isShowName() { return showName; } public void setShowName(boolean showName) { this.showName = showName; } @Column(nullable = true) private boolean showProtocol; @Column(nullable = true) private boolean showOdometer; public boolean isShowProtocol() { return showProtocol; } public void setShowProtocol(boolean showProtocol) { this.showProtocol = showProtocol; } public boolean isShowOdometer() { return showOdometer; } public void setShowOdometer(boolean showOdometer) { this.showOdometer = showOdometer; } @Column(nullable = true) private Integer timezoneOffset; public int getTimezoneOffset() { return timezoneOffset == null ? 0 : timezoneOffset; } public void setTimezoneOffset(Integer timezoneOffset) { this.timezoneOffset = timezoneOffset; } @Transient private String protocol; public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } @Column(nullable = true) private String commandPassword; public String getCommandPassword() { return commandPassword; } public void setCommandPassword(String commandPassword) { this.commandPassword = commandPassword; } @Transient private boolean isAlarmEnabled; public boolean isAlarmEnabled() { return isAlarmEnabled; } public void setAlarmEnabled(boolean isEnabled) { isAlarmEnabled = isEnabled; } @Transient private boolean unreadAlarms; public boolean hasUnreadAlarms() { return unreadAlarms; } public void setUnreadAlarms(boolean unreadAlarms) { this.unreadAlarms = unreadAlarms; } @Transient @JsonIgnore private Date lastAlarmsCheck; public Date getLastAlarmsCheck() { return lastAlarmsCheck; } public void setLastAlarmsCheck(Date date) { lastAlarmsCheck = date; } @Column(nullable=false, columnDefinition = "boolean default false") private boolean deleted; public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } @Column(nullable=false, columnDefinition = "CHAR(6) default '0000FF'") private String color; public String getColor() { return color; } public void setColor(String color) { this.color = color; } @Column(nullable=false, columnDefinition = "BIGINT default -1") private long deviceModelId; public long getDeviceModelId() { return deviceModelId; } public void setDeviceModelId(long id) { this.deviceModelId = id; } @GwtTransient @JsonIgnore @OneToMany(fetch = FetchType.LAZY, mappedBy="device") private List<Position> positions = new ArrayList<>(); public List<Position> getPositions() { return positions; } private Long iconId; public Long getIconId() { return iconId; } public void setIconId(Long iconId) { this.iconId = iconId; } private Long customIconId; public Long getCustomIconId() { return customIconId; } public void setCustomIconId(Long value) { this.customIconId = value; } @Temporal(TemporalType.DATE) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ", timezone="GMT") private Date validTo; public Date getValidTo() { return validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } @GwtIncompatible public boolean isValid(Date today) { if(getValidTo() == null) return false; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); today = sdf.parse(sdf.format(today)); return today.compareTo(getValidTo()) <= 0; } catch (ParseException ex) { Logger.getLogger(Device.class.getName()).log(Level.SEVERE, null, ex); return false; } } @GwtIncompatible public Date getLastAvailablePositionDate(Date today, int freeHistoryDays) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { today = sdf.parse(sdf.format(today)); } catch (ParseException e) { Logger.getLogger(Device.class.getName()).log(Level.SEVERE, null, e); } int availableHistoryLength = freeHistoryDays; if (isValid(today)) { availableHistoryLength = getHistoryLength(); } Calendar cal = Calendar.getInstance(); cal.setTime(today); cal.add(Calendar.DATE, -availableHistoryLength); return cal.getTime(); } public int getSubscriptionDaysLeft(Date from) { if (validTo == null) { return 0; } int daysDiff = CalendarUtil.getDaysBetween(from, validTo); int daysLeft = daysDiff + 1; if (daysLeft < 0) { daysLeft = 0; } return daysLeft; } public boolean isCloseToExpire(Date from) { int daysLeft = getSubscriptionDaysLeft(from); return (daysLeft <= NEAR_EXPIRATION_THRESHOLD_DAYS && daysLeft > 0); } @Column(nullable = false, columnDefinition = "integer") private int historyLength; public int getHistoryLength() { return historyLength; } public void setHistoryLength(int historyLength) { this.historyLength = historyLength; } @GwtIncompatible public int getAlertsHistoryLength(ApplicationSettings settings) { int historyLength = settings.getFreeHistory(); if(isValid(new Date())) historyLength = getHistoryLength(); return Math.min(historyLength, 7); } @Column(nullable = false, columnDefinition="bit default false") private boolean isBlocked; public boolean isBlocked() { return isBlocked; } public void setBlocked(boolean isBlocked) { this.isBlocked = isBlocked; } @JsonIgnore private Integer battery; @JsonIgnore public Integer getBatteryLevel() { return battery; } @JsonIgnore public void setBatteryLevel(Integer level) { this.battery = level; } @Temporal(javax.persistence.TemporalType.TIMESTAMP) @JsonIgnore private Date battTime; @JsonIgnore public Date getBatteryTime() { return battTime; } @JsonIgnore public void setBatteryTime(Date time) { this.battTime = time; } @JsonIgnore public int getBatteryTimeout() { return 3600; } private Boolean ignition; public Boolean getIgnition() { return ignition; } public void setIgnition(Boolean ignition) { this.ignition = ignition; } @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date ignTime; public Date getIgnitionTime() { return ignTime; } public void setIgnitionTime(Date ignitionTime) { ignTime = ignitionTime; } @JsonIgnore private Integer positionFreq; public Integer getPositionFreq() { return positionFreq; } private Boolean autoArm; public Boolean isAutoArmed() { return autoArm; } private Double fuelLevel; public Double getFuelLevel() { return fuelLevel; } public void setFuelLevel(Double lvl) { this.fuelLevel = lvl; } private Double fuelUsed; public Double getFuelUsed() { return fuelUsed; } public void setFuelUsed(Double used) { this.fuelUsed = used; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Device)) return false; Device device = (Device) o; if (getUniqueId() != null ? !getUniqueId().equals(device.getUniqueId()) : device.getUniqueId() != null) return false; return true; } @Override public int hashCode() { return getUniqueId() != null ? getUniqueId().hashCode() : 0; } }
datamatica-pl/traccar-orm
src/main/java/pl/datamatica/traccar/model/Device.java
Java
agpl-3.0
23,210
/** * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of the GPL, you may * redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS") * applications as described in Silverpeas's FLOSS exception. You should have received a copy of the * text describing the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.util.node.model; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.Serializable; import java.text.ParseException; import org.silverpeas.search.indexEngine.model.IndexEntry; import com.silverpeas.util.clipboard.ClipboardSelection; import com.silverpeas.util.clipboard.SilverpeasKeyData; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.util.DateUtil; public class NodeSelection extends ClipboardSelection implements Serializable { private static final long serialVersionUID = -6462797069972573255L; public static DataFlavor NodeDetailFlavor; static { NodeDetailFlavor = new DataFlavor(NodeDetail.class, "Node"); } private NodeDetail nodeDetail; public NodeSelection(NodeDetail node) { super(); nodeDetail = node; super.addFlavor(NodeDetailFlavor); } @Override public synchronized Object getTransferData(DataFlavor parFlavor) throws UnsupportedFlavorException { Object transferedData; try { transferedData = super.getTransferData(parFlavor); } catch (UnsupportedFlavorException e) { if (parFlavor.equals(NodeDetailFlavor)) { transferedData = nodeDetail; } else { throw e; } } return transferedData; } @Override public IndexEntry getIndexEntry() { NodePK pk = nodeDetail.getNodePK(); IndexEntry indexEntry = new IndexEntry(pk.getInstanceId(), "Node", pk.getId()); indexEntry.setTitle(nodeDetail.getName()); return indexEntry; } @Override public SilverpeasKeyData getKeyData() { SilverpeasKeyData keyData = new SilverpeasKeyData(); keyData.setTitle(nodeDetail.getName()); keyData.setAuthor(nodeDetail.getCreatorId()); try { keyData.setCreationDate(DateUtil.parse(nodeDetail.getCreationDate())); } catch (ParseException e) { SilverTrace.error("node", "NodeSelection.getKeyData()", "root.EX_NO_MESSAGE", e); } keyData.setDesc(nodeDetail.getDescription()); return keyData; } }
CecileBONIN/Silverpeas-Core
ejb-core/node/src/main/java/com/stratelia/webactiv/util/node/model/NodeSelection.java
Java
agpl-3.0
3,220
package output; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import javax.swing.JOptionPane; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; public class XmlParserJhove { public static void main(String args[]) throws Exception { JOptionPane.showMessageDialog(null, "Please choose the XML File to analyse", "XmlParsing", JOptionPane.QUESTION_MESSAGE); String xmlfile = utilities.BrowserDialogs.chooseFile(); parseXmlFile(xmlfile); } public static void parseXmlFile(String xmlfile) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlfile); PrintWriter xmlsummary = new PrintWriter(new FileWriter((jhoveValidations.JhoveGuiStarterDialog.jhoveExaminationFolder + "//" + "JhoveExaminationSummary" + ".xml"))); String xmlVersion = "xml version='1.0'"; String xmlEncoding = "encoding='ISO-8859-1'"; String xmlxslStyleSheet = "<?xml-stylesheet type=\"text/xsl\" href=\"JhoveCustomized.xsl\"?>"; xmlsummary.println("<?" + xmlVersion + " " + xmlEncoding + "?>"); xmlsummary.println(xmlxslStyleSheet); xmlsummary.println("<JhoveFindingsSummary>"); output.XslStyleSheetsJhove.JhoveCustomizedXsl(); ArrayList<String> errormessages = new ArrayList<String>(); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("item"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; xmlsummary.println("<File>"); String testutf8 = eElement.getElementsByTagName("filename").item(0).getTextContent(); if (testutf8.contains("&")) { String sub = utilities.GenericUtilities.normaliseToUtf8(testutf8); xmlsummary.println("<FileName>" + sub + "</FileName>"); } else { xmlsummary.println("<FileName>" + eElement.getElementsByTagName("filename").item(0).getTextContent() + "</FileName>"); } if (eElement.getElementsByTagName("creationyear").item(0)!= null) { xmlsummary.println("<CreationYear>" + eElement.getElementsByTagName("creationyear").item(0).getTextContent() + "</CreationYear>"); } if (eElement.getElementsByTagName("creationsoftware").item(0)!= null) { xmlsummary.println("<CreationSoftware>" + eElement.getElementsByTagName("creationsoftware").item(0).getTextContent() + "</CreationSoftware>"); } if (eElement.getElementsByTagName("encryption").item(0)!= null) { xmlsummary.println("<Encryption>" + eElement.getElementsByTagName("encryption").item(0).getTextContent() + "</Encryption>"); } if (eElement.getElementsByTagName("PdfType").item(0)!= null) { xmlsummary.println("<PdfType>" + eElement.getElementsByTagName("PdfType").item(0).getTextContent() + "</PdfType>"); } xmlsummary.println("<Module>" + eElement.getElementsByTagName("reportingModule").item(0).getTextContent() + "</Module>"); xmlsummary.println("<Status>" + eElement.getElementsByTagName("status").item(0).getTextContent() + "</Status>"); String status = eElement.getElementsByTagName("status").item(0).getTextContent(); if ((status.contains("Not")) || (status.contains("not"))) { System.out.println(eElement.getElementsByTagName("filename").item(0).getTextContent()); int lenmessages = eElement.getElementsByTagName("message").getLength(); xmlsummary.println("<JhoveMessages>" + lenmessages + "</JhoveMessages>"); for (int temp3 = 0; temp3 < lenmessages; temp3++) { String error = eElement.getElementsByTagName("message").item(temp3).getTextContent(); int writtenmessage = temp3 + 1; //TODO: get rid of xml escaping characters error = error.replace("\"", "&quot;"); error = error.replace("\'", "&apos;"); error = error.replace("<", "&lt;"); error = error.replace(">", "&gt;"); error = error.replace("&", " &amp;"); xmlsummary.println("<Message" + writtenmessage + ">" + error + "</Message" + writtenmessage + ">"); errormessages.add(error); } } xmlsummary.println("</File>"); //TODO: should be changed to File, but as well in XSLT } } Collections.sort(errormessages); int i; // copy ErrorList because later the no. of entries of each // element will be counted ArrayList<String> originerrors = new ArrayList<String>(); for (i = 0; i < errormessages.size(); i++) { // There might be a // pre-defined // function for this originerrors.add(errormessages.get(i)); } // get rid of redundant entries i = 0; while (i < errormessages.size() - 1) { if (errormessages.get(i).equals(errormessages.get(i + 1))) { errormessages.remove(i); } else { i++; } } xmlsummary.println("<SampleSummary>"); xmlsummary.println("<ExaminedPdfFiles>" + nList.getLength() + "</ExaminedPdfFiles>"); xmlsummary.println("<DifferentJhoveMessages>" + errormessages.size() + "</DifferentJhoveMessages>"); // how often does each JHOVE error occur? int j = 0; int temp1; for (i = 0; i < errormessages.size(); i++) { temp1 = 0; for (j = 0; j < originerrors.size(); j++) { if (errormessages.get(i).equals(originerrors.get(j))) { temp1++; } } xmlsummary.println("<JhoveMessage>"); xmlsummary.println("<MessageText>" + errormessages.get(i) + "</MessageText>"); xmlsummary.println("<Occurance>" + temp1 + "</Occurance>"); xmlsummary.println("</JhoveMessage>"); } xmlsummary.println("</SampleSummary>"); xmlsummary.println("</JhoveFindingsSummary>"); xmlsummary.close(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, e, "error message", JOptionPane.ERROR_MESSAGE); } } }
YvonneTunnat/File-Format-Utilities
master/pdf-tools/src/main/java/output/XmlParserJhove.java
Java
agpl-3.0
6,325
/* * $Id: CardCollectionDao.java 475 2005-12-08 23:44:08 -0800 (Thu, 08 Dec 2005) ivaynberg $ * $Revision: 475 $ * $Date: 2005-12-08 23:44:08 -0800 (Thu, 08 Dec 2005) $ * * ============================================================================== * 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.alienlabs.hatchetharry.persistence.dao; import java.io.Serializable; import java.util.List; import org.alienlabs.hatchetharry.model.CardCollection; import org.hibernate.Session; /** * The implementation-independent DAO interface. Defines the operations required * to be supported by an implementation. * * @author igor */ public interface CardCollectionDao extends Serializable { Session getSession(); /** * Load a {@link CardCollection} from the DB, given it's <tt>id</tt>. * * @param id * The id of the Contact to load. * @return CardCollection */ CardCollection load(long id); /** * Save the CardCollection to the DB * * @param CardCollection * @return persistent instance of contact */ CardCollection save(CardCollection contact); /** * Delete a {@link CardCollection} from the DB, given it's <tt>id</tt>. * * @param id * The id of the CardCollection to delete. */ void delete(long id); /** * Return the number of CardCollections in the DB. * * @return count */ int count(); /** * Returns the list of all unique last names in the database * * @return the list of all unique last names in the database */ List<String> getUniqueLastNames(); }
AlienQueen/HatchetHarry
src/main/java/org/alienlabs/hatchetharry/persistence/dao/CardCollectionDao.java
Java
agpl-3.0
2,144
/* * Copyright (C) 2011-2013 The Animo Project * http://animotron.org * * This file is part of Animotron. * * Animotron is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Animotron is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of * the GNU Affero General Public License along with Animotron. * If not, see <http://www.gnu.org/licenses/>. */ package org.animotron.cache; import java.io.IOException; import java.io.OutputStream; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public interface Cache { public boolean available(String key) throws IOException; public void get(String key, OutputStream out) throws IOException; public void get(String key, StringBuilder out) throws IOException; public String get(String key) throws IOException; public OutputStream stream(String key, OutputStream out) throws IOException; public OutputStream stream(String key, StringBuilder out) throws IOException; public void drop(String key) throws IOException; }
animotron/core
src/main/java/org/animotron/cache/Cache.java
Java
agpl-3.0
1,548
// ----------> GENERATED FILE - DON'T TOUCH! <---------- // generator: ilarkesto.mda.legacy.generator.EntityGenerator package scrum.server.collaboration; import java.util.*; import ilarkesto.persistence.*; import ilarkesto.core.logging.Log; import ilarkesto.base.*; import ilarkesto.base.time.*; import ilarkesto.auth.*; public abstract class GComment extends AEntity implements ilarkesto.auth.ViewProtected<scrum.server.admin.User>, ilarkesto.search.Searchable, java.lang.Comparable<Comment> { // --- AEntity --- public final CommentDao getDao() { return commentDao; } protected void repairDeadDatob(ADatob datob) { } @Override public void storeProperties(Map properties) { super.storeProperties(properties); properties.put("parentId", this.parentId); properties.put("authorId", this.authorId); properties.put("published", this.published); properties.put("authorName", this.authorName); properties.put("authorEmail", this.authorEmail); properties.put("authorNameVisible", this.authorNameVisible); properties.put("text", this.text); properties.put("dateAndTime", this.dateAndTime == null ? null : this.dateAndTime.toString()); } public int compareTo(Comment other) { return toString().toLowerCase().compareTo(other.toString().toLowerCase()); } private static final ilarkesto.core.logging.Log LOG = ilarkesto.core.logging.Log.get(GComment.class); public static final String TYPE = "comment"; // ----------------------------------------------------------- // - Searchable // ----------------------------------------------------------- public boolean matchesKey(String key) { if (super.matchesKey(key)) return true; if (matchesKey(getText(), key)) return true; return false; } // ----------------------------------------------------------- // - parent // ----------------------------------------------------------- private String parentId; private transient ilarkesto.persistence.AEntity parentCache; private void updateParentCache() { parentCache = this.parentId == null ? null : (ilarkesto.persistence.AEntity)getDaoService().getById(this.parentId); } public final String getParentId() { return this.parentId; } public final ilarkesto.persistence.AEntity getParent() { if (parentCache == null) updateParentCache(); return parentCache; } public final void setParent(ilarkesto.persistence.AEntity parent) { parent = prepareParent(parent); if (isParent(parent)) return; this.parentId = parent == null ? null : parent.getId(); parentCache = parent; fireModified("parent="+parent); } protected ilarkesto.persistence.AEntity prepareParent(ilarkesto.persistence.AEntity parent) { return parent; } protected void repairDeadParentReference(String entityId) { if (this.parentId == null || entityId.equals(this.parentId)) { repairMissingMaster(); } } public final boolean isParentSet() { return this.parentId != null; } public final boolean isParent(ilarkesto.persistence.AEntity parent) { if (this.parentId == null && parent == null) return true; return parent != null && parent.getId().equals(this.parentId); } protected final void updateParent(Object value) { setParent(value == null ? null : (ilarkesto.persistence.AEntity)getDaoService().getById((String)value)); } // ----------------------------------------------------------- // - author // ----------------------------------------------------------- private String authorId; private transient scrum.server.admin.User authorCache; private void updateAuthorCache() { authorCache = this.authorId == null ? null : (scrum.server.admin.User)userDao.getById(this.authorId); } public final String getAuthorId() { return this.authorId; } public final scrum.server.admin.User getAuthor() { if (authorCache == null) updateAuthorCache(); return authorCache; } public final void setAuthor(scrum.server.admin.User author) { author = prepareAuthor(author); if (isAuthor(author)) return; this.authorId = author == null ? null : author.getId(); authorCache = author; fireModified("author="+author); } protected scrum.server.admin.User prepareAuthor(scrum.server.admin.User author) { return author; } protected void repairDeadAuthorReference(String entityId) { if (this.authorId == null || entityId.equals(this.authorId)) { setAuthor(null); } } public final boolean isAuthorSet() { return this.authorId != null; } public final boolean isAuthor(scrum.server.admin.User author) { if (this.authorId == null && author == null) return true; return author != null && author.getId().equals(this.authorId); } protected final void updateAuthor(Object value) { setAuthor(value == null ? null : (scrum.server.admin.User)userDao.getById((String)value)); } // ----------------------------------------------------------- // - published // ----------------------------------------------------------- private boolean published; public final boolean isPublished() { return published; } public final void setPublished(boolean published) { published = preparePublished(published); if (isPublished(published)) return; this.published = published; fireModified("published="+published); } protected boolean preparePublished(boolean published) { return published; } public final boolean isPublished(boolean published) { return this.published == published; } protected final void updatePublished(Object value) { setPublished((Boolean)value); } // ----------------------------------------------------------- // - authorName // ----------------------------------------------------------- private java.lang.String authorName; public final java.lang.String getAuthorName() { return authorName; } public final void setAuthorName(java.lang.String authorName) { authorName = prepareAuthorName(authorName); if (isAuthorName(authorName)) return; this.authorName = authorName; fireModified("authorName="+authorName); } protected java.lang.String prepareAuthorName(java.lang.String authorName) { authorName = Str.removeUnreadableChars(authorName); return authorName; } public final boolean isAuthorNameSet() { return this.authorName != null; } public final boolean isAuthorName(java.lang.String authorName) { if (this.authorName == null && authorName == null) return true; return this.authorName != null && this.authorName.equals(authorName); } protected final void updateAuthorName(Object value) { setAuthorName((java.lang.String)value); } // ----------------------------------------------------------- // - authorEmail // ----------------------------------------------------------- private java.lang.String authorEmail; public final java.lang.String getAuthorEmail() { return authorEmail; } public final void setAuthorEmail(java.lang.String authorEmail) { authorEmail = prepareAuthorEmail(authorEmail); if (isAuthorEmail(authorEmail)) return; this.authorEmail = authorEmail; fireModified("authorEmail="+authorEmail); } protected java.lang.String prepareAuthorEmail(java.lang.String authorEmail) { authorEmail = Str.removeUnreadableChars(authorEmail); return authorEmail; } public final boolean isAuthorEmailSet() { return this.authorEmail != null; } public final boolean isAuthorEmail(java.lang.String authorEmail) { if (this.authorEmail == null && authorEmail == null) return true; return this.authorEmail != null && this.authorEmail.equals(authorEmail); } protected final void updateAuthorEmail(Object value) { setAuthorEmail((java.lang.String)value); } // ----------------------------------------------------------- // - authorNameVisible // ----------------------------------------------------------- private boolean authorNameVisible; public final boolean isAuthorNameVisible() { return authorNameVisible; } public final void setAuthorNameVisible(boolean authorNameVisible) { authorNameVisible = prepareAuthorNameVisible(authorNameVisible); if (isAuthorNameVisible(authorNameVisible)) return; this.authorNameVisible = authorNameVisible; fireModified("authorNameVisible="+authorNameVisible); } protected boolean prepareAuthorNameVisible(boolean authorNameVisible) { return authorNameVisible; } public final boolean isAuthorNameVisible(boolean authorNameVisible) { return this.authorNameVisible == authorNameVisible; } protected final void updateAuthorNameVisible(Object value) { setAuthorNameVisible((Boolean)value); } // ----------------------------------------------------------- // - text // ----------------------------------------------------------- private java.lang.String text; public final java.lang.String getText() { return text; } public final void setText(java.lang.String text) { text = prepareText(text); if (isText(text)) return; this.text = text; fireModified("text="+text); } protected java.lang.String prepareText(java.lang.String text) { text = Str.removeUnreadableChars(text); return text; } public final boolean isTextSet() { return this.text != null; } public final boolean isText(java.lang.String text) { if (this.text == null && text == null) return true; return this.text != null && this.text.equals(text); } protected final void updateText(Object value) { setText((java.lang.String)value); } // ----------------------------------------------------------- // - dateAndTime // ----------------------------------------------------------- private ilarkesto.base.time.DateAndTime dateAndTime; public final ilarkesto.base.time.DateAndTime getDateAndTime() { return dateAndTime; } public final void setDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) { dateAndTime = prepareDateAndTime(dateAndTime); if (isDateAndTime(dateAndTime)) return; this.dateAndTime = dateAndTime; fireModified("dateAndTime="+dateAndTime); } protected ilarkesto.base.time.DateAndTime prepareDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) { return dateAndTime; } public final boolean isDateAndTimeSet() { return this.dateAndTime != null; } public final boolean isDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) { if (this.dateAndTime == null && dateAndTime == null) return true; return this.dateAndTime != null && this.dateAndTime.equals(dateAndTime); } protected final void updateDateAndTime(Object value) { value = value == null ? null : new ilarkesto.base.time.DateAndTime((String)value); setDateAndTime((ilarkesto.base.time.DateAndTime)value); } public void updateProperties(Map<?, ?> properties) { for (Map.Entry entry : properties.entrySet()) { String property = (String) entry.getKey(); if (property.equals("id")) continue; Object value = entry.getValue(); if (property.equals("parentId")) updateParent(value); if (property.equals("authorId")) updateAuthor(value); if (property.equals("published")) updatePublished(value); if (property.equals("authorName")) updateAuthorName(value); if (property.equals("authorEmail")) updateAuthorEmail(value); if (property.equals("authorNameVisible")) updateAuthorNameVisible(value); if (property.equals("text")) updateText(value); if (property.equals("dateAndTime")) updateDateAndTime(value); } } protected void repairDeadReferences(String entityId) { super.repairDeadReferences(entityId); repairDeadParentReference(entityId); repairDeadAuthorReference(entityId); } // --- ensure integrity --- public void ensureIntegrity() { super.ensureIntegrity(); if (!isParentSet()) { repairMissingMaster(); return; } try { getParent(); } catch (EntityDoesNotExistException ex) { LOG.info("Repairing dead parent reference"); repairDeadParentReference(this.parentId); } try { getAuthor(); } catch (EntityDoesNotExistException ex) { LOG.info("Repairing dead author reference"); repairDeadAuthorReference(this.authorId); } } static CommentDao commentDao; public static final void setCommentDao(CommentDao commentDao) { GComment.commentDao = commentDao; } }
hogi/kunagi
src/generated/java/scrum/server/collaboration/GComment.java
Java
agpl-3.0
13,504
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2019 Asqatasun.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa22; import java.util.LinkedHashSet; import org.apache.commons.lang3.StringUtils; import org.asqatasun.entity.audit.EvidenceElement; import org.asqatasun.entity.audit.ProcessResult; import org.asqatasun.entity.audit.SourceCodeRemark; import org.asqatasun.entity.audit.TestSolution; import static org.asqatasun.rules.keystore.AttributeStore.TITLE_ATTR; import org.asqatasun.rules.keystore.HtmlElementStore; import org.asqatasun.rules.keystore.RemarkMessageStore; import org.asqatasun.rules.rgaa22.test.Rgaa22RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 1.2 of the referential RGAA 2.2. * * @author jkowalczyk */ public class Rgaa22Rule01021Test extends Rgaa22RuleImplementationTestCase { /** * Default constructor */ public Rgaa22Rule01021Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.asqatasun.rules.rgaa22.Rgaa22Rule01021"); } @Override protected void setUpWebResourceMap() { getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-01.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-02.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-03.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-04.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-05.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-06.html")); getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-01.html")); getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-02.html")); getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-03.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-01.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-02.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-03.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-04.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-05.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-06.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-07.html")); } @Override protected void setProcess() { //---------------------------------------------------------------------- //------------------------------2Failed-01------------------------------ //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("Rgaa22.Test.1.2-2Failed-01"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); SourceCodeRemark processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); EvidenceElement ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-02------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-02"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-03------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-03"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-04------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-04"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "mock-frame1.html")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-05------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-05"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "mock-iframe1.html")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-06------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-06"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "mock-frame1.html")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------3NMI-01--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-3NMI-01"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.CHECK_TITLE_OF_FRAME_PERTINENCE_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "title of mock-frame1")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------3NMI-02--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-3NMI-02"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.CHECK_TITLE_OF_FRAME_PERTINENCE_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "Title of mock-iframe1")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------3NMI-03--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-3NMI-03"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.CHECK_TITLE_OF_FRAME_PERTINENCE_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "Title of mock-frame1")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------4NA-01---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-01"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-02---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-02"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-03---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-03"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-04---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-04"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-05---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-05"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-06---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-06"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-07---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-07"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); } @Override protected void setConsolidate() { assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-01").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-02").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-03").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-04").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-05").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-06").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("Rgaa22.Test.1.2-3NMI-01").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("Rgaa22.Test.1.2-3NMI-02").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("Rgaa22.Test.1.2-3NMI-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-06").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-07").getValue()); } }
dzc34/Asqatasun
rules/rules-rgaa2.2/src/test/java/org/asqatasun/rules/rgaa22/Rgaa22Rule01021Test.java
Java
agpl-3.0
23,545
package nikita.common.config; /** * Constants used for ElasticSearch queries */ public class ESConstants { public static final String QUERY_SIZE = "size"; public static final String QUERY_FROM = "from"; public static final String QUERY_QUERY = "query"; public static final String QUERY_PREFIX = "prefix"; public static final String QUERY_MATCH_PHRASE = "match_phrase"; }
HiOA-ABI/nikita-noark5-core
src/main/java/nikita/common/config/ESConstants.java
Java
agpl-3.0
396
public class Generic{ public static void main(String[] args){ Car <String> car1 = new Car <String> (); car1.setName("Buick"); car1.setPrice("100"); System.out.printf("name=%s,price=%s\n",car1.getName(),car1.getPrice()); Car <Integer> car2 = new Car <Integer> (); car2.setName(001); car2.setPrice(100); System.out.printf("name=%d,price=%d\n",car2.getName(),car2.getPrice()); Integer[] array = {1,2,3,4,5,6,7,8,9}; car2.print(array); } } /*generic class*/ class Car <T> { private T name; private T price; public Car(){ this.name = null; this.price = null; } public Car(T name,T price){ this.name = name; this.price = price; } public void setName(T name){ this.name = name; } public T getName(){ return this.name; } public void setPrice(T price){ this.price = price; } public T getPrice(){ return this.price; } public <A> void print(A[] array){ for (A var:array) System.out.printf("%s",var); } }
314942468GitHub/JavaLearnning
src/Generic.java
Java
agpl-3.0
963
/* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Magrit is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit.sshd; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import org.apache.sshd.SshServer; import org.apache.sshd.common.NamedFactory; import org.apache.sshd.common.util.SecurityUtils; import org.apache.sshd.server.CommandFactory; import org.apache.sshd.server.ForwardingFilter; import org.apache.sshd.server.PublickeyAuthenticator; import org.apache.sshd.server.UserAuth; import org.apache.sshd.server.auth.UserAuthNone; import org.apache.sshd.server.auth.UserAuthPublicKey; import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; import org.apache.sshd.server.session.ServerSession; import org.kercoin.magrit.core.Configuration; import org.kercoin.magrit.core.Context; import org.kercoin.magrit.core.Configuration.Authentication; import org.kercoin.magrit.core.services.Service; import org.kercoin.magrit.core.services.ServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class Server implements Service.UseTCP { protected final Logger log = LoggerFactory.getLogger(getClass()); private SshServer sshd; private final int port; @Inject public Server(final Context ctx, CommandFactory factory) { port = ctx.configuration().getSshPort(); sshd = SshServer.setUpDefaultServer(); if (SecurityUtils.isBouncyCastleRegistered()) { sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider("key.pem")); } else { sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("key.ser")); } PublickeyAuthenticator auth = null; if (ctx.configuration().getAuthentication() == Configuration.Authentication.SSH_PUBLIC_KEYS) { auth = ctx.getInjector().getInstance(PublickeyAuthenticator.class); } setupUserAuth(auth); sshd.setCommandFactory(factory); if (!ctx.configuration().isRemoteAllowed()) { sshd.setSessionFactory(new LocalOnlySessionFactory()); } sshd.setForwardingFilter(new ForwardingFilter() { public boolean canForwardAgent(ServerSession session) { return false; } public boolean canForwardX11(ServerSession session) { return false; } public boolean canListen(InetSocketAddress address, ServerSession session) { return false; } public boolean canConnect(InetSocketAddress address, ServerSession session) { return false; } }); } private void setupUserAuth(PublickeyAuthenticator auth) { List<NamedFactory<UserAuth>> list = new ArrayList<NamedFactory<UserAuth>>(); if (auth != null) { list.add(new UserAuthPublicKey.Factory()); sshd.setPublickeyAuthenticator(auth); } else { list.add(new UserAuthNone.Factory()); } sshd.setUserAuthFactories(list); } @Override public void start() throws ServiceException { sshd.setPort(port); try { sshd.start(); } catch (IOException e) { throw new ServiceException(e); } } @Override public String getName() { return "SSH Service"; } @Override public int getTCPPort() { return port; } @Override public void logConfig(ConfigurationLogger log, Configuration cfg) { log.logKey("SSHd", cfg.getSshPort()); log.logKey("Listening", cfg.isRemoteAllowed() ? "everybody" : "localhost"); log.logKey("Authent", cfg.getAuthentication().external()); if (cfg.getAuthentication() == Authentication.SSH_PUBLIC_KEYS) { log.logSubKey("Keys dir", cfg.getPublickeyRepositoryDir()); } log.logKey("Home dir", cfg.getRepositoriesHomeDir()); log.logKey("Work dir", cfg.getWorkHomeDir()); } }
ptitfred/magrit
server/sshd/src/main/java/org/kercoin/magrit/sshd/Server.java
Java
agpl-3.0
4,603
/* * Copyright (C) 2013 OpenJST Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openjst.protocols.basic.encoder; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; import org.openjst.commons.io.buffer.DataBufferException; import org.openjst.commons.security.checksum.CRC16; import org.openjst.protocols.basic.constants.ProtocolBasicConstants; import org.openjst.protocols.basic.pdu.PDU; public class ProtocolEncoder extends OneToOneEncoder { public static final byte[] RESERVED = new byte[]{0, 0, 0, 0, 0}; @Override protected Object encode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception { if (msg instanceof PDU) { return encodePacket((PDU) msg); } else { return msg; } } public static ChannelBuffer encodePacket(final PDU packet) throws DataBufferException { final byte[] msgBody = packet.encode(); final ChannelBuffer buffer = ChannelBuffers.buffer(16 + msgBody.length); buffer.writeByte(ProtocolBasicConstants.VERSION); buffer.writeShort(0); buffer.writeShort(packet.getType()); buffer.writeInt(msgBody.length); buffer.writeBytes(RESERVED); buffer.writeShort(CRC16.checksum(msgBody)); if (msgBody.length > 0) { buffer.writeBytes(msgBody); } return buffer; } }
devmix/openjst
protocol/basic/commons/src/main/java/org/openjst/protocols/basic/encoder/ProtocolEncoder.java
Java
agpl-3.0
2,229
package com.thegame.server.presentation.exceptions; import com.thegame.server.common.exceptions.TypifiedException; /** * @author e103880 */ public class PresentationException extends TypifiedException{ private final PresentationExceptionType exceptionType; private final Object[] arguments; public PresentationException(final PresentationExceptionType _exceptionType){ this(_exceptionType,new Object[]{}); } public PresentationException(final PresentationExceptionType _exceptionType,final Object... _arguments){ super(_exceptionType.getDescription()); this.exceptionType=_exceptionType; this.arguments=_arguments; } public PresentationException(final Throwable _cause,final PresentationExceptionType _exceptionType){ this(_cause,_exceptionType,new Object[]{}); } public PresentationException(final Throwable _cause,final PresentationExceptionType _exceptionType,final Object... _arguments){ super(_exceptionType.getDescription(),_cause); this.exceptionType=_exceptionType; this.arguments=_arguments; } @Override public PresentationExceptionType getExceptionType(){ return this.exceptionType; } @Override public Object[] getArguments() { return arguments; } @Override public String getMessage() { return getProcessedMessage(); } }
bernatmv/thegame
server/server-presentation/src/main/java/com/thegame/server/presentation/exceptions/PresentationException.java
Java
agpl-3.0
1,333
/** * Copyright (C) 2013 The Language Archive, Max Planck Institute for * Psycholinguistics * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307, USA. */ package nl.mpi.yams.common.data; import java.io.Serializable; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; /** * Created on : Aug 28, 2013, 5:24:13 PM * * @author Peter Withers <peter.withers@mpi.nl> */ @XmlRootElement(name = "Highlight") public class DataNodeHighlight implements Serializable { private String dataNodeId = null; private String highlightPath = null; public String getDataNodeId() { return dataNodeId; } @XmlAttribute(name = "ID") public void setDataNodeId(String dataNodeId) { this.dataNodeId = dataNodeId; } public String getHighlightPath() { return highlightPath; } @XmlAttribute(name = "Path") public void setHighlightPath(String highlightPath) { this.highlightPath = highlightPath; } }
TheLanguageArchive/YAMS
common/src/main/java/nl/mpi/yams/common/data/DataNodeHighlight.java
Java
agpl-3.0
1,663
/* * JBILLING CONFIDENTIAL * _____________________ * * [2003] - [2012] Enterprise jBilling Software Ltd. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Enterprise jBilling Software. * The intellectual and technical concepts contained * herein are proprietary to Enterprise jBilling Software * and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden. */ package com.sapienter.jbilling.server.pluggableTask.admin; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.iterators.ArrayListIterator; import org.apache.log4j.Logger; import com.sapienter.jbilling.common.SessionInternalError; import com.sapienter.jbilling.server.pluggableTask.PluggableTask; import com.sapienter.jbilling.server.util.Constants; import com.sapienter.jbilling.server.util.Context; import com.sapienter.jbilling.server.util.audit.EventLogger; public class PluggableTaskBL<T> { private static final Logger LOG = Logger.getLogger(PluggableTaskBL.class); private EventLogger eLogger = null; private PluggableTaskDAS das = null; private PluggableTaskParameterDAS dasParameter = null; private PluggableTaskDTO pluggableTask = null; public PluggableTaskBL(Integer pluggableTaskId) { init(); set(pluggableTaskId); } public PluggableTaskBL() { init(); } private void init() { eLogger = EventLogger.getInstance(); das = (PluggableTaskDAS) Context.getBean(Context.Name.PLUGGABLE_TASK_DAS); dasParameter = new PluggableTaskParameterDAS(); } public void set(Integer id) { pluggableTask = das.find(id); } public void set(Integer entityId, Integer typeId) { pluggableTask = das.findByEntityType(entityId, typeId); } public void set(PluggableTaskDTO task) { pluggableTask = task; } public PluggableTaskDTO getDTO() { return pluggableTask; } public int create(Integer executorId, PluggableTaskDTO dto) { validate(dto); LOG.debug("Creating a new pluggable task row " + dto); pluggableTask = das.save(dto); eLogger.audit(executorId, null, Constants.TABLE_PLUGGABLE_TASK, pluggableTask.getId(), EventLogger.MODULE_TASK_MAINTENANCE, EventLogger.ROW_CREATED, null, null, null); return pluggableTask.getId(); } public void createParameter(Integer taskId, PluggableTaskParameterDTO dto) { PluggableTaskDTO task = das.find(taskId); dto.setTask(task); task.getParameters().add(dasParameter.save(dto)); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(taskId); } public void update(Integer executorId, PluggableTaskDTO dto) { if (dto == null || dto.getId() == null) { throw new SessionInternalError("task to update can't be null"); } validate(dto); List<PluggableTaskParameterDTO> parameterDTOList = dasParameter.findAllByTask(dto); for (PluggableTaskParameterDTO param: dto.getParameters()) { parameterDTOList.remove(dasParameter.find(param.getId())); param.expandValue(); } for (PluggableTaskParameterDTO param: parameterDTOList){ dasParameter.delete(param); } LOG.debug("updating " + dto); pluggableTask = das.save(dto); eLogger.audit(executorId, null , Constants.TABLE_PLUGGABLE_TASK, dto.getId(), EventLogger.MODULE_TASK_MAINTENANCE, EventLogger.ROW_UPDATED, null, null, null); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(dto.getId()); das.invalidateCache(); // 3rd level cache pluggableTask.populateParamValues(); } public void delete(Integer executor) { eLogger.audit(executor, null, Constants.TABLE_PLUGGABLE_TASK, pluggableTask.getId(), EventLogger.MODULE_TASK_MAINTENANCE, EventLogger.ROW_DELETED, null, null, null); das.delete(pluggableTask); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(pluggableTask.getId()); } public void deleteParameter(Integer executor, Integer id) { eLogger.audit(executor, null, Constants.TABLE_PLUGGABLE_TASK_PARAMETER, id, EventLogger.MODULE_TASK_MAINTENANCE, EventLogger.ROW_DELETED, null, null, null); PluggableTaskParameterDTO toDelete = dasParameter.find(id); toDelete.getTask().getParameters().remove(toDelete); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(toDelete.getTask().getId()); dasParameter.delete(toDelete); } public void updateParameters(PluggableTaskDTO dto) { // update the parameters from the dto for (PluggableTaskParameterDTO parameter: dto.getParameters()) { updateParameter(parameter); } } private void updateParameter(PluggableTaskParameterDTO dto) { dto.expandValue(); dasParameter.save(dto); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(dto.getTask().getId()); } public T instantiateTask() throws PluggableTaskException { PluggableTaskDTO localTask = getDTO(); String fqn = localTask.getType().getClassName(); T result; try { Class taskClazz = Class.forName(fqn); //.asSubclass(result.getClass()); result = (T) taskClazz.newInstance(); } catch (ClassCastException e) { throw new PluggableTaskException("Task id: " + pluggableTask.getId() + ": implementation class does not implements PaymentTask:" + fqn, e); } catch (InstantiationException e) { throw new PluggableTaskException("Task id: " + pluggableTask.getId() + ": Can not instantiate : " + fqn, e); } catch (IllegalAccessException e) { throw new PluggableTaskException("Task id: " + pluggableTask.getId() + ": Can not find public constructor for : " + fqn, e); } catch (ClassNotFoundException e) { throw new PluggableTaskException("Task id: " + pluggableTask.getId() + ": Unknown class: " + fqn, e); } if (result instanceof PluggableTask) { PluggableTask pluggable = (PluggableTask) result; pluggable.initializeParamters(localTask); } else { throw new PluggableTaskException("Plug-in has to extend PluggableTask " + pluggableTask.getId()); } return result; } private void validate(PluggableTaskDTO task) { List<ParameterDescription> missingParameters = new ArrayList<ParameterDescription>(); try { // start by getting an instance of this type PluggableTask instance = (PluggableTask) PluggableTaskManager.getInstance( task.getType().getClassName(), task.getType().getCategory().getInterfaceName()); // loop through the descriptions of parameters for (ParameterDescription param: instance.getParameterDescriptions()) { if (param.isRequired()) { if(task.getParameters()== null || task.getParameters().size() == 0) { missingParameters.add(param); } else { boolean found = false; for (PluggableTaskParameterDTO parameter:task.getParameters()) { if (parameter.getName().equals(param.getName()) && parameter.getStrValue() != null && parameter.getStrValue().trim().length() > 0) { found = true; break; } } if (!found) { missingParameters.add(param); } } } } } catch (PluggableTaskException e) { LOG.error("Getting instance of plug-in for validation", e); throw new SessionInternalError("Validating plug-in"); } if (missingParameters.size() > 0) { SessionInternalError exception = new SessionInternalError("Validation of new plug-in"); String messages[] = new String[missingParameters.size()]; int f=0; for (ParameterDescription param: missingParameters) { messages[f] = new String("PluggableTaskWS,parameter,plugins.error.required_parameter," + param.getName()); f++; } exception.setErrorMessages(messages); throw exception; } // now validate that the processing order is not already taken boolean nonUniqueResult= false; try { PluggableTaskDTO samePlugin = das.findByEntityCategoryOrder(task.getEntityId(), task.getType().getCategory().getId(), task.getProcessingOrder()); if (samePlugin != null && !samePlugin.getId().equals(task.getId())) { nonUniqueResult=true; } } catch (Exception e) { nonUniqueResult=true; } if (nonUniqueResult) { SessionInternalError exception = new SessionInternalError("Validation of new plug-in"); exception.setErrorMessages(new String[] { "PluggableTaskWS,processingOrder,plugins.error.same_order," + task.getProcessingOrder()}); throw exception; } } }
rahith/ComtalkA-S
src/java/com/sapienter/jbilling/server/pluggableTask/admin/PluggableTaskBL.java
Java
agpl-3.0
10,431
/* * StatusBarWidget.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.editors.text.status; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.*; import org.rstudio.core.client.widget.IsWidgetWithHeight; public class StatusBarWidget extends Composite implements StatusBar, IsWidgetWithHeight { private int height_; interface Binder extends UiBinder<HorizontalPanel, StatusBarWidget> { } public StatusBarWidget() { Binder binder = GWT.create(Binder.class); HorizontalPanel hpanel = binder.createAndBindUi(this); hpanel.setVerticalAlignment(HorizontalPanel.ALIGN_TOP); hpanel.setCellWidth(hpanel.getWidget(2), "100%"); initWidget(hpanel); height_ = 16; } public int getHeight() { return height_; } public Widget asWidget() { return this; } public StatusBarElement getPosition() { return position_; } public StatusBarElement getFunction() { return function_; } public StatusBarElement getLanguage() { return language_; } public void setFunctionVisible(boolean visible) { function_.setContentsVisible(visible); funcIcon_.setVisible(visible); } @UiField StatusBarElementWidget position_; @UiField StatusBarElementWidget function_; @UiField StatusBarElementWidget language_; @UiField Image funcIcon_; }
Sage-Bionetworks/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/status/StatusBarWidget.java
Java
agpl-3.0
1,945
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.client.communication; import ilarkesto.core.logging.Log; import ilarkesto.core.time.Tm; import java.util.LinkedList; import scrum.client.DataTransferObject; import scrum.client.core.ApplicationStartedEvent; import scrum.client.core.ApplicationStartedHandler; import scrum.client.project.Requirement; import scrum.client.workspace.BlockCollapsedEvent; import scrum.client.workspace.BlockCollapsedHandler; import scrum.client.workspace.BlockExpandedEvent; import scrum.client.workspace.BlockExpandedHandler; import com.google.gwt.user.client.Timer; public class Pinger extends GPinger implements ServerDataReceivedHandler, BlockExpandedHandler, BlockCollapsedHandler, ApplicationStartedHandler { private static Log log = Log.get(Pinger.class); public static final int MIN_DELAY = 1000; public static final int MAX_DELAY = 5000; private Timer timer; private int maxDelay = MAX_DELAY; private long lastDataReceiveTime = Tm.getCurrentTimeMillis(); private LinkedList<Long> pingTimes = new LinkedList<Long>(); private boolean disabled; @Override public void onApplicationStarted(ApplicationStartedEvent event) { timer = new Timer() { @Override public void run() { if (!disabled && !serviceCaller.containsServiceCall(PingServiceCall.class)) { final long start = Tm.getCurrentTimeMillis(); new PingServiceCall().execute(new Runnable() { @Override public void run() { long time = Tm.getCurrentTimeMillis() - start; pingTimes.add(time); if (pingTimes.size() > 10) pingTimes.removeFirst(); } }); } reschedule(); } }; reschedule(); } public void setDisabled(boolean disabled) { this.disabled = disabled; } public boolean isDisabled() { return disabled; } public void shutdown() { log.info("Shutting down"); if (timer == null) return; timer.cancel(); timer = null; } @Override public void onServerDataReceived(ServerDataReceivedEvent event) { DataTransferObject data = event.getData(); if (data.containsEntities()) { lastDataReceiveTime = Tm.getCurrentTimeMillis(); reschedule(); } } @Override public void onBlockCollapsed(BlockCollapsedEvent event) { deactivatePowerPolling(); } @Override public void onBlockExpanded(BlockExpandedEvent event) { Object object = event.getObject(); if (object instanceof Requirement) { Requirement requirement = (Requirement) object; if (requirement.isWorkEstimationVotingActive()) activatePowerPolling(); } } public void reschedule() { if (timer == null) return; long idle = Tm.getCurrentTimeMillis() - lastDataReceiveTime; idle = (int) (idle * 0.15); if (idle < MIN_DELAY) idle = MIN_DELAY; if (idle > maxDelay) idle = maxDelay; timer.scheduleRepeating((int) idle); } private void activatePowerPolling() { maxDelay = MIN_DELAY; log.debug("PowerPolling activated"); } private void deactivatePowerPolling() { if (maxDelay == MAX_DELAY) return; maxDelay = MAX_DELAY; lastDataReceiveTime = Tm.getCurrentTimeMillis(); log.debug("PowerPolling deactivated"); } public Long getAvaragePingTime() { if (pingTimes.isEmpty()) return null; long sum = 0; for (Long time : pingTimes) { sum += time; } return sum / pingTimes.size(); } public String getAvaragePingTimeMessage() { Long time = getAvaragePingTime(); if (time == null) return null; return "Current response time: " + time + " ms."; } }
MiguelSMendoza/Kunagi
WEB-INF/classes/scrum/client/communication/Pinger.java
Java
agpl-3.0
4,177
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.11.06 at 05:19:55 PM ICT // package org.opencps.api.dossierlog.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="total" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="data" type="{}DossierLogModel" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "total", "data" }) @XmlRootElement(name = "DossierLogResultsModel") public class DossierLogResultsModel { protected Integer total; protected List<DossierLogModel> data; /** * Gets the value of the total property. * * @return * possible object is * {@link Integer } * */ public Integer getTotal() { return total; } /** * Sets the value of the total property. * * @param value * allowed object is * {@link Integer } * */ public void setTotal(Integer value) { this.total = value; } /** * Gets the value of the data property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the data property. * * <p> * For example, to add a new item, do as follows: * <pre> * getData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DossierLogModel } * * */ public List<DossierLogModel> getData() { if (data == null) { data = new ArrayList<DossierLogModel>(); } return this.data; } }
VietOpenCPS/opencps-v2
modules/backend-api-rest/src/main/java/org/opencps/api/dossierlog/model/DossierLogResultsModel.java
Java
agpl-3.0
2,858
// ----------> GENERATED FILE - DON'T TOUCH! <---------- // generator: ilarkesto.mda.legacy.generator.DaoGenerator package scrum.server.admin; import java.util.*; import ilarkesto.persistence.*; import ilarkesto.core.logging.Log; import ilarkesto.base.*; import ilarkesto.base.time.*; import ilarkesto.auth.*; import ilarkesto.fp.*; public abstract class GUserDao extends ilarkesto.auth.AUserDao<User> { public final String getEntityName() { return User.TYPE; } public final Class getEntityClass() { return User.class; } public Set<User> getEntitiesVisibleForUser(final scrum.server.admin.User user) { return getEntities(new Predicate<User>() { public boolean test(User e) { return Auth.isVisible(e, user); } }); } // --- clear caches --- public void clearCaches() { namesCache = null; usersByAdminCache.clear(); usersByEmailVerifiedCache.clear(); emailsCache = null; usersByCurrentProjectCache.clear(); currentProjectsCache = null; usersByColorCache.clear(); colorsCache = null; usersByLastLoginDateAndTimeCache.clear(); lastLoginDateAndTimesCache = null; usersByRegistrationDateAndTimeCache.clear(); registrationDateAndTimesCache = null; usersByDisabledCache.clear(); usersByHideUserGuideBlogCache.clear(); usersByHideUserGuideCalendarCache.clear(); usersByHideUserGuideFilesCache.clear(); usersByHideUserGuideForumCache.clear(); usersByHideUserGuideImpedimentsCache.clear(); usersByHideUserGuideIssuesCache.clear(); usersByHideUserGuideJournalCache.clear(); usersByHideUserGuideNextSprintCache.clear(); usersByHideUserGuideProductBacklogCache.clear(); usersByHideUserGuideCourtroomCache.clear(); usersByHideUserGuideQualityBacklogCache.clear(); usersByHideUserGuideReleasesCache.clear(); usersByHideUserGuideRisksCache.clear(); usersByHideUserGuideSprintBacklogCache.clear(); usersByHideUserGuideWhiteboardCache.clear(); loginTokensCache = null; openIdsCache = null; } @Override public void entityDeleted(EntityEvent event) { super.entityDeleted(event); if (event.getEntity() instanceof User) { clearCaches(); } } @Override public void entitySaved(EntityEvent event) { super.entitySaved(event); if (event.getEntity() instanceof User) { clearCaches(); } } // ----------------------------------------------------------- // - name // ----------------------------------------------------------- public final User getUserByName(java.lang.String name) { return getEntity(new IsName(name)); } private Set<java.lang.String> namesCache; public final Set<java.lang.String> getNames() { if (namesCache == null) { namesCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isNameSet()) namesCache.add(e.getName()); } } return namesCache; } private static class IsName implements Predicate<User> { private java.lang.String value; public IsName(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isName(value); } } // ----------------------------------------------------------- // - admin // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByAdminCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean admin) { return getEntities(new IsAdmin(admin)); } }); public final Set<User> getUsersByAdmin(boolean admin) { return usersByAdminCache.get(admin); } private static class IsAdmin implements Predicate<User> { private boolean value; public IsAdmin(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isAdmin(); } } // ----------------------------------------------------------- // - emailVerified // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByEmailVerifiedCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean emailVerified) { return getEntities(new IsEmailVerified(emailVerified)); } }); public final Set<User> getUsersByEmailVerified(boolean emailVerified) { return usersByEmailVerifiedCache.get(emailVerified); } private static class IsEmailVerified implements Predicate<User> { private boolean value; public IsEmailVerified(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isEmailVerified(); } } // ----------------------------------------------------------- // - email // ----------------------------------------------------------- public final User getUserByEmail(java.lang.String email) { return getEntity(new IsEmail(email)); } private Set<java.lang.String> emailsCache; public final Set<java.lang.String> getEmails() { if (emailsCache == null) { emailsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isEmailSet()) emailsCache.add(e.getEmail()); } } return emailsCache; } private static class IsEmail implements Predicate<User> { private java.lang.String value; public IsEmail(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isEmail(value); } } // ----------------------------------------------------------- // - currentProject // ----------------------------------------------------------- private final Cache<scrum.server.project.Project,Set<User>> usersByCurrentProjectCache = new Cache<scrum.server.project.Project,Set<User>>( new Cache.Factory<scrum.server.project.Project,Set<User>>() { public Set<User> create(scrum.server.project.Project currentProject) { return getEntities(new IsCurrentProject(currentProject)); } }); public final Set<User> getUsersByCurrentProject(scrum.server.project.Project currentProject) { return usersByCurrentProjectCache.get(currentProject); } private Set<scrum.server.project.Project> currentProjectsCache; public final Set<scrum.server.project.Project> getCurrentProjects() { if (currentProjectsCache == null) { currentProjectsCache = new HashSet<scrum.server.project.Project>(); for (User e : getEntities()) { if (e.isCurrentProjectSet()) currentProjectsCache.add(e.getCurrentProject()); } } return currentProjectsCache; } private static class IsCurrentProject implements Predicate<User> { private scrum.server.project.Project value; public IsCurrentProject(scrum.server.project.Project value) { this.value = value; } public boolean test(User e) { return e.isCurrentProject(value); } } // ----------------------------------------------------------- // - color // ----------------------------------------------------------- private final Cache<java.lang.String,Set<User>> usersByColorCache = new Cache<java.lang.String,Set<User>>( new Cache.Factory<java.lang.String,Set<User>>() { public Set<User> create(java.lang.String color) { return getEntities(new IsColor(color)); } }); public final Set<User> getUsersByColor(java.lang.String color) { return usersByColorCache.get(color); } private Set<java.lang.String> colorsCache; public final Set<java.lang.String> getColors() { if (colorsCache == null) { colorsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isColorSet()) colorsCache.add(e.getColor()); } } return colorsCache; } private static class IsColor implements Predicate<User> { private java.lang.String value; public IsColor(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isColor(value); } } // ----------------------------------------------------------- // - lastLoginDateAndTime // ----------------------------------------------------------- private final Cache<ilarkesto.base.time.DateAndTime,Set<User>> usersByLastLoginDateAndTimeCache = new Cache<ilarkesto.base.time.DateAndTime,Set<User>>( new Cache.Factory<ilarkesto.base.time.DateAndTime,Set<User>>() { public Set<User> create(ilarkesto.base.time.DateAndTime lastLoginDateAndTime) { return getEntities(new IsLastLoginDateAndTime(lastLoginDateAndTime)); } }); public final Set<User> getUsersByLastLoginDateAndTime(ilarkesto.base.time.DateAndTime lastLoginDateAndTime) { return usersByLastLoginDateAndTimeCache.get(lastLoginDateAndTime); } private Set<ilarkesto.base.time.DateAndTime> lastLoginDateAndTimesCache; public final Set<ilarkesto.base.time.DateAndTime> getLastLoginDateAndTimes() { if (lastLoginDateAndTimesCache == null) { lastLoginDateAndTimesCache = new HashSet<ilarkesto.base.time.DateAndTime>(); for (User e : getEntities()) { if (e.isLastLoginDateAndTimeSet()) lastLoginDateAndTimesCache.add(e.getLastLoginDateAndTime()); } } return lastLoginDateAndTimesCache; } private static class IsLastLoginDateAndTime implements Predicate<User> { private ilarkesto.base.time.DateAndTime value; public IsLastLoginDateAndTime(ilarkesto.base.time.DateAndTime value) { this.value = value; } public boolean test(User e) { return e.isLastLoginDateAndTime(value); } } // ----------------------------------------------------------- // - registrationDateAndTime // ----------------------------------------------------------- private final Cache<ilarkesto.base.time.DateAndTime,Set<User>> usersByRegistrationDateAndTimeCache = new Cache<ilarkesto.base.time.DateAndTime,Set<User>>( new Cache.Factory<ilarkesto.base.time.DateAndTime,Set<User>>() { public Set<User> create(ilarkesto.base.time.DateAndTime registrationDateAndTime) { return getEntities(new IsRegistrationDateAndTime(registrationDateAndTime)); } }); public final Set<User> getUsersByRegistrationDateAndTime(ilarkesto.base.time.DateAndTime registrationDateAndTime) { return usersByRegistrationDateAndTimeCache.get(registrationDateAndTime); } private Set<ilarkesto.base.time.DateAndTime> registrationDateAndTimesCache; public final Set<ilarkesto.base.time.DateAndTime> getRegistrationDateAndTimes() { if (registrationDateAndTimesCache == null) { registrationDateAndTimesCache = new HashSet<ilarkesto.base.time.DateAndTime>(); for (User e : getEntities()) { if (e.isRegistrationDateAndTimeSet()) registrationDateAndTimesCache.add(e.getRegistrationDateAndTime()); } } return registrationDateAndTimesCache; } private static class IsRegistrationDateAndTime implements Predicate<User> { private ilarkesto.base.time.DateAndTime value; public IsRegistrationDateAndTime(ilarkesto.base.time.DateAndTime value) { this.value = value; } public boolean test(User e) { return e.isRegistrationDateAndTime(value); } } // ----------------------------------------------------------- // - disabled // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByDisabledCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean disabled) { return getEntities(new IsDisabled(disabled)); } }); public final Set<User> getUsersByDisabled(boolean disabled) { return usersByDisabledCache.get(disabled); } private static class IsDisabled implements Predicate<User> { private boolean value; public IsDisabled(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isDisabled(); } } // ----------------------------------------------------------- // - hideUserGuideBlog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideBlogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideBlog) { return getEntities(new IsHideUserGuideBlog(hideUserGuideBlog)); } }); public final Set<User> getUsersByHideUserGuideBlog(boolean hideUserGuideBlog) { return usersByHideUserGuideBlogCache.get(hideUserGuideBlog); } private static class IsHideUserGuideBlog implements Predicate<User> { private boolean value; public IsHideUserGuideBlog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideBlog(); } } // ----------------------------------------------------------- // - hideUserGuideCalendar // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideCalendarCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideCalendar) { return getEntities(new IsHideUserGuideCalendar(hideUserGuideCalendar)); } }); public final Set<User> getUsersByHideUserGuideCalendar(boolean hideUserGuideCalendar) { return usersByHideUserGuideCalendarCache.get(hideUserGuideCalendar); } private static class IsHideUserGuideCalendar implements Predicate<User> { private boolean value; public IsHideUserGuideCalendar(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideCalendar(); } } // ----------------------------------------------------------- // - hideUserGuideFiles // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideFilesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideFiles) { return getEntities(new IsHideUserGuideFiles(hideUserGuideFiles)); } }); public final Set<User> getUsersByHideUserGuideFiles(boolean hideUserGuideFiles) { return usersByHideUserGuideFilesCache.get(hideUserGuideFiles); } private static class IsHideUserGuideFiles implements Predicate<User> { private boolean value; public IsHideUserGuideFiles(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideFiles(); } } // ----------------------------------------------------------- // - hideUserGuideForum // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideForumCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideForum) { return getEntities(new IsHideUserGuideForum(hideUserGuideForum)); } }); public final Set<User> getUsersByHideUserGuideForum(boolean hideUserGuideForum) { return usersByHideUserGuideForumCache.get(hideUserGuideForum); } private static class IsHideUserGuideForum implements Predicate<User> { private boolean value; public IsHideUserGuideForum(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideForum(); } } // ----------------------------------------------------------- // - hideUserGuideImpediments // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideImpedimentsCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideImpediments) { return getEntities(new IsHideUserGuideImpediments(hideUserGuideImpediments)); } }); public final Set<User> getUsersByHideUserGuideImpediments(boolean hideUserGuideImpediments) { return usersByHideUserGuideImpedimentsCache.get(hideUserGuideImpediments); } private static class IsHideUserGuideImpediments implements Predicate<User> { private boolean value; public IsHideUserGuideImpediments(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideImpediments(); } } // ----------------------------------------------------------- // - hideUserGuideIssues // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideIssuesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideIssues) { return getEntities(new IsHideUserGuideIssues(hideUserGuideIssues)); } }); public final Set<User> getUsersByHideUserGuideIssues(boolean hideUserGuideIssues) { return usersByHideUserGuideIssuesCache.get(hideUserGuideIssues); } private static class IsHideUserGuideIssues implements Predicate<User> { private boolean value; public IsHideUserGuideIssues(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideIssues(); } } // ----------------------------------------------------------- // - hideUserGuideJournal // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideJournalCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideJournal) { return getEntities(new IsHideUserGuideJournal(hideUserGuideJournal)); } }); public final Set<User> getUsersByHideUserGuideJournal(boolean hideUserGuideJournal) { return usersByHideUserGuideJournalCache.get(hideUserGuideJournal); } private static class IsHideUserGuideJournal implements Predicate<User> { private boolean value; public IsHideUserGuideJournal(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideJournal(); } } // ----------------------------------------------------------- // - hideUserGuideNextSprint // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideNextSprintCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideNextSprint) { return getEntities(new IsHideUserGuideNextSprint(hideUserGuideNextSprint)); } }); public final Set<User> getUsersByHideUserGuideNextSprint(boolean hideUserGuideNextSprint) { return usersByHideUserGuideNextSprintCache.get(hideUserGuideNextSprint); } private static class IsHideUserGuideNextSprint implements Predicate<User> { private boolean value; public IsHideUserGuideNextSprint(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideNextSprint(); } } // ----------------------------------------------------------- // - hideUserGuideProductBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideProductBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideProductBacklog) { return getEntities(new IsHideUserGuideProductBacklog(hideUserGuideProductBacklog)); } }); public final Set<User> getUsersByHideUserGuideProductBacklog(boolean hideUserGuideProductBacklog) { return usersByHideUserGuideProductBacklogCache.get(hideUserGuideProductBacklog); } private static class IsHideUserGuideProductBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideProductBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideProductBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideCourtroom // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideCourtroomCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideCourtroom) { return getEntities(new IsHideUserGuideCourtroom(hideUserGuideCourtroom)); } }); public final Set<User> getUsersByHideUserGuideCourtroom(boolean hideUserGuideCourtroom) { return usersByHideUserGuideCourtroomCache.get(hideUserGuideCourtroom); } private static class IsHideUserGuideCourtroom implements Predicate<User> { private boolean value; public IsHideUserGuideCourtroom(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideCourtroom(); } } // ----------------------------------------------------------- // - hideUserGuideQualityBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideQualityBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideQualityBacklog) { return getEntities(new IsHideUserGuideQualityBacklog(hideUserGuideQualityBacklog)); } }); public final Set<User> getUsersByHideUserGuideQualityBacklog(boolean hideUserGuideQualityBacklog) { return usersByHideUserGuideQualityBacklogCache.get(hideUserGuideQualityBacklog); } private static class IsHideUserGuideQualityBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideQualityBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideQualityBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideReleases // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideReleasesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideReleases) { return getEntities(new IsHideUserGuideReleases(hideUserGuideReleases)); } }); public final Set<User> getUsersByHideUserGuideReleases(boolean hideUserGuideReleases) { return usersByHideUserGuideReleasesCache.get(hideUserGuideReleases); } private static class IsHideUserGuideReleases implements Predicate<User> { private boolean value; public IsHideUserGuideReleases(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideReleases(); } } // ----------------------------------------------------------- // - hideUserGuideRisks // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideRisksCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideRisks) { return getEntities(new IsHideUserGuideRisks(hideUserGuideRisks)); } }); public final Set<User> getUsersByHideUserGuideRisks(boolean hideUserGuideRisks) { return usersByHideUserGuideRisksCache.get(hideUserGuideRisks); } private static class IsHideUserGuideRisks implements Predicate<User> { private boolean value; public IsHideUserGuideRisks(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideRisks(); } } // ----------------------------------------------------------- // - hideUserGuideSprintBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideSprintBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideSprintBacklog) { return getEntities(new IsHideUserGuideSprintBacklog(hideUserGuideSprintBacklog)); } }); public final Set<User> getUsersByHideUserGuideSprintBacklog(boolean hideUserGuideSprintBacklog) { return usersByHideUserGuideSprintBacklogCache.get(hideUserGuideSprintBacklog); } private static class IsHideUserGuideSprintBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideSprintBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideSprintBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideWhiteboard // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideWhiteboardCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideWhiteboard) { return getEntities(new IsHideUserGuideWhiteboard(hideUserGuideWhiteboard)); } }); public final Set<User> getUsersByHideUserGuideWhiteboard(boolean hideUserGuideWhiteboard) { return usersByHideUserGuideWhiteboardCache.get(hideUserGuideWhiteboard); } private static class IsHideUserGuideWhiteboard implements Predicate<User> { private boolean value; public IsHideUserGuideWhiteboard(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideWhiteboard(); } } // ----------------------------------------------------------- // - loginToken // ----------------------------------------------------------- public final User getUserByLoginToken(java.lang.String loginToken) { return getEntity(new IsLoginToken(loginToken)); } private Set<java.lang.String> loginTokensCache; public final Set<java.lang.String> getLoginTokens() { if (loginTokensCache == null) { loginTokensCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isLoginTokenSet()) loginTokensCache.add(e.getLoginToken()); } } return loginTokensCache; } private static class IsLoginToken implements Predicate<User> { private java.lang.String value; public IsLoginToken(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isLoginToken(value); } } // ----------------------------------------------------------- // - openId // ----------------------------------------------------------- public final User getUserByOpenId(java.lang.String openId) { return getEntity(new IsOpenId(openId)); } private Set<java.lang.String> openIdsCache; public final Set<java.lang.String> getOpenIds() { if (openIdsCache == null) { openIdsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isOpenIdSet()) openIdsCache.add(e.getOpenId()); } } return openIdsCache; } private static class IsOpenId implements Predicate<User> { private java.lang.String value; public IsOpenId(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isOpenId(value); } } // --- valueObject classes --- @Override protected Set<Class> getValueObjectClasses() { Set<Class> ret = new HashSet<Class>(super.getValueObjectClasses()); return ret; } @Override public Map<String, Class> getAliases() { Map<String, Class> aliases = new HashMap<String, Class>(super.getAliases()); return aliases; } // --- dependencies --- scrum.server.project.ProjectDao projectDao; public void setProjectDao(scrum.server.project.ProjectDao projectDao) { this.projectDao = projectDao; } }
hogi/kunagi
src/generated/java/scrum/server/admin/GUserDao.java
Java
agpl-3.0
31,402
/* * RapidMiner * * Copyright (C) 2001-2011 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator; /** * These listeners will be notified after a new operator was added to a chain. * * @author Ingo Mierswa */ public interface AddListener { public void operatorAdded(Operator newChild); }
aborg0/rapidminer-vega
src/com/rapidminer/operator/AddListener.java
Java
agpl-3.0
1,124
package info.nightscout.androidaps.plugins.SmsCommunicator; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Comparator; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.utils.DateUtil; /** * A simple {@link Fragment} subclass. */ public class SmsCommunicatorFragment extends SubscriberFragment { private static Logger log = LoggerFactory.getLogger(SmsCommunicatorFragment.class); private static SmsCommunicatorPlugin smsCommunicatorPlugin; public static SmsCommunicatorPlugin getPlugin() { if(smsCommunicatorPlugin==null){ smsCommunicatorPlugin = new SmsCommunicatorPlugin(); } return smsCommunicatorPlugin; } TextView logView; public SmsCommunicatorFragment() { super(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.smscommunicator_fragment, container, false); logView = (TextView) view.findViewById(R.id.smscommunicator_log); updateGUI(); return view; } @Subscribe public void onStatusEvent(final EventSmsCommunicatorUpdateGui ev) { updateGUI(); } @Override protected void updateGUI() { Activity activity = getActivity(); if (activity != null) activity.runOnUiThread(new Runnable() { @Override public void run() { class CustomComparator implements Comparator<SmsCommunicatorPlugin.Sms> { public int compare(SmsCommunicatorPlugin.Sms object1, SmsCommunicatorPlugin.Sms object2) { return (int) (object1.date.getTime() - object2.date.getTime()); } } Collections.sort(getPlugin().messages, new CustomComparator()); int messagesToShow = 40; int start = Math.max(0, getPlugin().messages.size() - messagesToShow); String logText = ""; for (int x = start; x < getPlugin().messages.size(); x++) { SmsCommunicatorPlugin.Sms sms = getPlugin().messages.get(x); if (sms.received) { logText += DateUtil.timeString(sms.date) + " &lt;&lt;&lt; " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>"; } else if (sms.sent) { logText += DateUtil.timeString(sms.date) + " &gt;&gt;&gt; " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>"; } } logView.setText(Html.fromHtml(logText)); } }); } }
RoumenGeorgiev/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorFragment.java
Java
agpl-3.0
3,402
/* * ADL2-core * Copyright (c) 2013-2014 Marand d.o.o. (www.marand.com) * * This file is part of ADL2-core. * * ADL2-core is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openehr.adl.am.mixin; import com.google.common.collect.ImmutableMap; import org.openehr.jaxb.am.CAttribute; import org.openehr.jaxb.am.Cardinality; import org.openehr.jaxb.rm.*; import java.lang.reflect.Constructor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author markopi */ class AmMixinsInternal { private static final Map<Class<?>, Class<? extends AmMixin>> configuration; private static final Map<Class<?>, Constructor<? extends AmMixin>> constructors; static { Map<Class<?>, Class<? extends AmMixin>> conf = ImmutableMap.<Class<?>, Class<? extends AmMixin>>builder() .put(IntervalOfDate.class, IntervalOfDateMixin.class) .put(IntervalOfTime.class, IntervalOfTimeMixin.class) .put(IntervalOfDateTime.class, IntervalOfDateTimeMixin.class) .put(IntervalOfInteger.class, IntervalOfIntegerMixin.class) .put(IntervalOfReal.class, IntervalOfRealMixin.class) .put(MultiplicityInterval.class, MultiplicityIntervalMixin.class) .put(CAttribute.class, CAttributeMixin.class) .put(IntervalOfDuration.class, IntervalOfDurationMixin.class) .put(Cardinality.class, CardinalityMixin.class) .build(); configuration = ImmutableMap.copyOf(conf); constructors = new ConcurrentHashMap<>(); } static <T, M extends AmMixin<?>> M create(T from) { Constructor<? extends AmMixin> mixinConstructor = getMixinClass(from.getClass()); try { return (M) mixinConstructor.newInstance(from); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException( "Error constructing mixin class " + mixinConstructor.getDeclaringClass() + " for class " + from.getClass()); } } private static Constructor<? extends AmMixin> getMixinClass(Class<?> fromClass) { Constructor<? extends AmMixin> result = constructors.get(fromClass); if (result == null) { Class<?> cls = fromClass; while (cls != null) { Class<? extends AmMixin> mixinClass = configuration.get(cls); if (mixinClass != null) { try { result = mixinClass.getConstructor(fromClass); } catch (NoSuchMethodException e) { throw new IllegalStateException( "Missing mixin " + mixinClass.getName() + " constructor for " + fromClass.getName()); } constructors.put(fromClass, result); return result; } cls = cls.getSuperclass(); } throw new IllegalArgumentException("No mixin defined for class " + fromClass); } return result; } }
lonangel/adl2-core
adl-parser/src/main/java/org/openehr/adl/am/mixin/AmMixinsInternal.java
Java
agpl-3.0
3,715
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.actions; import com.rapidminer.RapidMiner; import com.rapidminer.core.license.ProductConstraintManager; import com.rapidminer.gui.MainFrame; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.dialogs.AboutBox; import java.awt.event.ActionEvent; /** * The type About action. * * @author Simon Fischer */ public class AboutAction extends ResourceAction { private static final long serialVersionUID = 1L; private MainFrame mainFrame; /** * Instantiates a new About action. * * @param mainFrame the main frame */ public AboutAction(MainFrame mainFrame) { super("about"); this.mainFrame = mainFrame; setCondition(EDIT_IN_PROGRESS, DONT_CARE); } @Override public void actionPerformed(ActionEvent e) { new AboutBox(mainFrame, RapidMiner.getLongVersion(), ProductConstraintManager.INSTANCE.getActiveLicense()) .setVisible(true); } }
cm-is-dog/rapidminer-studio-core
src/main/java/com/rapidminer/gui/actions/AboutAction.java
Java
agpl-3.0
1,819
/* * PHEX - The pure-java Gnutella-servent. * Copyright (C) 2001 - 2006 Arne Babenhauserheide ( arne_bab <at> web <dot> de ) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Created on 08.02.2005 * --- CVS Information --- * $Id: RSSParser.java 3682 2007-01-09 15:32:14Z gregork $ */ package phex.util; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RSSParser { /** This Class reads out RSS-files passed to it and * collects them in the array "magnets[]". * Check the usage in phex.gui.dialogs.NewDowloadDialog */ /** * List of possible EOL characters, not exactly according to YAML 4.1.4 */ private static final String EOL_CHARACTERS = "\r\n"; private static final char[] AMPERSAND_AMP = new char[] {'a', 'm', 'p', ';'}; private static final String START_OF_ELEMENT_CHAR = "<"; private static final String END_OF_ELEMENT_CHAR = ">"; private static final String END_OF_ELEMENT_CHARN = "/"; private static final char[] XML_LINE = new char[] {'<', '?', 'x', 'm', 'l'}; private static final char[] MAGNET_PREFIX = new char[] {'m', 'a', 'g', 'n', 'e', 't'}; private static final char[] HTTP_PREFIX = new char[] {'h', 't', 't', 'p', ':', '/'}; private static final char[] MAGNET_TAG = new char[] {'<', 'm', 'a', 'g', 'n', 'e', 't', '>'}; private static final char[] ENCLOSURE_TAG_START = new char[] {'<', 'e', 'n', 'c', 'l', 'o', 's', 'u'}; private static final char[] ENCLOSURE_TAG_MID = new char[] {'r', 'e'}; private static final char[] URL_IDENTIFIER = new char[] {'u', 'r', 'l', '=', '"'}; //" private static final char[] ITEM_ELEMENT = new char[] {'<', 'i', 't', 'e', 'm', '>',}; private static final char[] END_OF_ITEM_ELEMENT = new char[] {'<', '/', 'i', 't', 'e', 'm', '>',}; private static final char[] RSS_TAG = new char[] {'<', 'r', 's', 's', '>',}; private static final char[] END_OF_RSS_TAG = new char[] {'<', '/', 'r', 's', 's', '>',}; private final PushbackReader reader; private final List<String> magnets; public RSSParser(Reader reader) { magnets = new ArrayList<String>(); this.reader = new PushbackReader(reader, 6); } public void start() throws IOException { try { /* The FileReader checks, if the File begins with "#MAGMA" * and sends the characters following the "#MAGMA" to the * listFinder. */ char buff[] = new char[5]; int readBytes = 0; while (readBytes != 5) { int count = reader.read(buff, readBytes, 5); if (count == -1) { throw new IOException("Input file is no XML-File (" + String.valueOf(buff) + ")."); } readBytes += count; } if (Arrays.equals(buff, XML_LINE)) { parseXml(); } } finally { reader.close(); } } public List getMagnets() { // Can be called to get the included magnets return magnets; } private void parseXml() throws IOException { int pos = 0; int c; while (true) { c = reader.read(); if (c == RSS_TAG[pos]) { pos++; if (pos == RSS_TAG.length) { // found rss-tag.. find the first item. parseList(); pos = 0; } } else if (c == -1) { // reached the end... return; } else {// next char of rss tag not found... skip line... pos = 0; //skipToEndOfObject(); parseList(); // ignore that this is careless } } } private void parseList() throws IOException { int pos = 0; int c; while (true) { c = reader.read(); if (c == ITEM_ELEMENT[pos]) { pos++; if (pos == ITEM_ELEMENT.length) { // found list: element.. skip line and continue to parse body. parseItemBody(); pos = 0; } } else if (c == END_OF_RSS_TAG[pos]) { pos++; if (pos == END_OF_RSS_TAG.length) { // RSS_TAG ended. pos = 0; return; } } else if (c == -1) { // reached the end... return; } else {// next char of list element not found... skip line... pos = 0; } } } public void parseItemBody() throws IOException { int c; int pos = 0; while (true) { c = reader.read(); if (c == MAGNET_TAG[pos]) { pos++; if (pos == MAGNET_TAG.length) { // we found a magnet-element // pre check if this really is a magnet.. char buff[] = new char[6]; int readBytes = 0; while (readBytes != 6) { int count = reader.read(buff, readBytes, 6); if (count == -1) { return; } readBytes += count; } reader.unread(buff); if (Arrays.equals(buff, MAGNET_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); } else if (Arrays.equals(buff, HTTP_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); } else { // skip to the end of this magnet-tag, // it doesn't contain a magnet nor a http-uri. } pos = 0; } } /** * Code to read out enclosures with * http- or magnet-uris doesn't work yet. */ else if (c == ENCLOSURE_TAG_START[pos]) { pos++; if (pos == ENCLOSURE_TAG_START.length) { // we found an enclosure-tag // pre check if this contains a magnet or http-url.. pos = 0; while (true) { c = reader.read(); //go forward up to the end of the URL-identifier. if (c == URL_IDENTIFIER[pos]) { pos++; if (pos == URL_IDENTIFIER.length) { //this containis an url-identifier. // check for magnet or http-start. char buff[] = new char[6]; int readBytes = 0; while (readBytes != 6) { int count = reader.read(buff, readBytes, 6); if (count == -1) { return; } readBytes += count; } reader.unread(buff); if (Arrays.equals(buff, MAGNET_PREFIX)) { // reached quoted magnet pos = 0; parseMagnet(); break; } else if (Arrays.equals(buff, HTTP_PREFIX)) { // reached quoted http-url pos = 0; parseMagnet(); break; } } } else if (END_OF_ELEMENT_CHAR.indexOf(c) != -1) { //return if we reached the end of the enclosure. pos = 0; break; } else if (c == -1) { pos = 0; return; } else { pos = 0; } } // end of inner while (true) } else // pos != ENCLOSURE_TAG_START.length { // next letter } } else if (c == -1) { // reached the EOF pos = 0; return; } /** * Commented it out, because it creaded an Array Out of Bounds error * ToDo: Catch the Error and read out the titles of the items to use them along the magnets. * ToDo: Read out the content of the rss-items, so they can be shown alongside the magnet in the list (best in a tooltip). */ else if (pos <= 6 && c == END_OF_ITEM_ELEMENT[pos]) { pos++; if (pos == END_OF_ITEM_ELEMENT.length) { // the item ended. pos = 0; return; } } /* **/ else { pos = 0; // didn't continue as magnet or enclosure tag, reset pos. } } //end of of while-loop } public void parseMagnet() throws IOException { StringBuffer magnetBuf = new StringBuffer(); int c; while (true) { c = reader.read(); if (c == ' ' || EOL_CHARACTERS.indexOf(c) != -1) {// skip all line folding characters.. and all spaces continue; } else if (c == '<') {// found the end of the magnet. break; } /** * only necessary when we are able to read out enclosures. */ else if (c == '"') //" { // found the end of the magnet. break; } else if (c == -1) { // unexpected end... return; } else if (c == '&') { char buff[] = new char[4]; int readBytes = 0; while (readBytes != 4) { int count = reader.read(buff, readBytes, 4); if (count == -1) { return; } readBytes += count; } if (Arrays.equals(buff, AMPERSAND_AMP)) { // reached quoted magnet magnetBuf.append('&'); } else { reader.unread(buff); magnetBuf.append((char) c); } } else { magnetBuf.append((char) c); } } magnets.add(magnetBuf.toString()); } /** * Skips all content till end of line. */ private void skipToEndOfObject() throws IOException { // Only gets the next ending of any object. Could be improved to get // the end of a specific object supplied by the calling funktion. // At the moment ends either with "/>" or with "</" int c; while (true) { c = reader.read(); if (c < 0) {// stream ended... a valid line could not be read... return return; } else if (START_OF_ELEMENT_CHAR.indexOf(c) != -1) {// we found a possble end o the object... check if there are followups c = reader.read(); if (END_OF_ELEMENT_CHARN.indexOf(c) != -1) { return; } else { // the last character was no End of Element char... push it back reader.unread(c); } } else if (END_OF_ELEMENT_CHARN.indexOf(c) != -1) {// we found a possble end o the object... check if there are followups c = reader.read(); if (END_OF_ELEMENT_CHAR.indexOf(c) != -1) { return; } else { // the last character was no End of Element char... push it back reader.unread(c); } } } } }
deepstupid/phex
src/main/java/phex/util/RSSParser.java
Java
agpl-3.0
13,551
package integration.tests; import static org.junit.Assert.assertEquals; import gr.ntua.vision.monitoring.VismoConfiguration; import gr.ntua.vision.monitoring.VismoVMInfo; import gr.ntua.vision.monitoring.dispatch.VismoEventDispatcher; import gr.ntua.vision.monitoring.events.MonitoringEvent; import gr.ntua.vision.monitoring.notify.VismoEventRegistry; import gr.ntua.vision.monitoring.rules.Rule; import gr.ntua.vision.monitoring.rules.VismoRulesEngine; import gr.ntua.vision.monitoring.service.ClusterHeadNodeFactory; import gr.ntua.vision.monitoring.service.Service; import gr.ntua.vision.monitoring.service.VismoService; import gr.ntua.vision.monitoring.zmq.ZMQFactory; import java.io.IOException; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZContext; /** * This is used to test the general facilities of the {@link VismoService}; thus is should receive events from producers, process * them in a rules engine and dispatch them to consumers. */ public class VismoServiceTest { /** * This is used to count the number of events received. */ private final class EventCountRule extends Rule { /***/ private int counter = 0; /** * Constructor. * * @param engine */ public EventCountRule(final VismoRulesEngine engine) { super(engine); } /** * @param expectedNoEvents */ public void hasSeenExpectedNoEvents(final int expectedNoEvents) { assertEquals(expectedNoEvents, counter); } /** * @see gr.ntua.vision.monitoring.rules.RuleProc#performWith(java.lang.Object) */ @Override public void performWith(final MonitoringEvent e) { if (e != null) ++counter; } } /** the log target. */ private static final Logger log = LoggerFactory.getLogger(VismoServiceTest.class); /***/ private static final int NO_GET_OPS = 100; /***/ private static final int NO_PUT_OPS = 100; /***/ @SuppressWarnings("serial") private static final Properties p = new Properties() { { setProperty("cloud.name", "visioncloud.eu"); setProperty("cloud.heads", "10.0.2.211, 10.0.2.212"); setProperty("cluster.name", "vision-1"); setProperty("cluster.head", "10.0.2.211"); setProperty("producers.point", "tcp://127.0.0.1:56429"); setProperty("consumers.port", "56430"); setProperty("udp.port", "56431"); setProperty("cluster.head.port", "56432"); setProperty("cloud.head.port", "56433"); setProperty("mon.group.addr", "228.5.6.7"); setProperty("mon.group.port", "12345"); setProperty("mon.ping.period", "60000"); setProperty("startup.rules", "PassThroughRule"); setProperty("web.port", "9996"); } }; /***/ EventCountRule countRule; /***/ private final VismoConfiguration conf = new VismoConfiguration(p); /***/ private FakeObjectService obs; /** the object under test. */ private Service service; /** the socket factory. */ private final ZMQFactory socketFactory = new ZMQFactory(new ZContext()); /** * @throws IOException */ @Before public void setUp() throws IOException { obs = new FakeObjectService(new VismoEventDispatcher(socketFactory, conf, "fake-obs")); service = new ClusterHeadNodeFactory(conf, socketFactory) { @Override protected void submitRules(final VismoRulesEngine engine) { countRule = new EventCountRule(engine); countRule.submit(); super.submitRules(engine); } }.build(new VismoVMInfo()); } /***/ @After public void tearDown() { if (service != null) service.halt(); } /** * @throws InterruptedException */ @Test public void vismoDeliversEventsToClient() throws InterruptedException { final VismoEventRegistry reg = new VismoEventRegistry(socketFactory, "tcp://127.0.0.1:" + conf.getConsumersPort()); final CountDownLatch latch = new CountDownLatch(1); final ConsumerHandler consumer = new ConsumerHandler(latch, NO_GET_OPS + NO_PUT_OPS); service.start(); reg.registerToAll(consumer); final long start = System.currentTimeMillis(); doGETs(NO_GET_OPS); doPUTs(NO_PUT_OPS); log.debug("waiting event delivery..."); latch.await(10, TimeUnit.SECONDS); final double dur = (System.currentTimeMillis() - start) / 1000.0; log.debug("{} events delivered to client in {} sec ({} events/sec)", new Object[] { consumer.getNoReceivedEvents(), dur, consumer.getNoReceivedEvents() / dur }); consumerHasReceivedExpectedNoEvents(consumer, NO_GET_OPS + NO_PUT_OPS); } /** * @throws InterruptedException */ @Test public void vismoReceivesEventsFromProducers() throws InterruptedException { service.start(); doGETs(NO_GET_OPS); doPUTs(NO_PUT_OPS); waitForEventsDelivery(2000); assertThatVismoReceivedEvents(); } /***/ private void assertThatVismoReceivedEvents() { countRule.hasSeenExpectedNoEvents(NO_GET_OPS + NO_PUT_OPS); } /** * @param noOps */ private void doGETs(final int noOps) { for (int i = 0; i < noOps; ++i) obs.getEvent("ntua", "bill", "foo-container", "bar-object").send(); } /** * @param noOps */ private void doPUTs(final int noOps) { for (int i = 0; i < noOps; ++i) obs.putEvent("ntua", "bill", "foo-container", "bar-object").send(); } /** * @param consumerHandler * @param expectedNoEvents */ private static void consumerHasReceivedExpectedNoEvents(final ConsumerHandler consumerHandler, final int expectedNoEvents) { assertEquals(expectedNoEvents, consumerHandler.getNoReceivedEvents()); } /** * @param n * @throws InterruptedException */ private static void waitForEventsDelivery(final int n) throws InterruptedException { Thread.sleep(n); } }
spyrosg/VISION-Cloud-Monitoring
vismo-core/src/test/java/integration/tests/VismoServiceTest.java
Java
agpl-3.0
7,451
/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltdb.SystemProcedureCatalog.Config; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Procedure; import org.voltdb.compiler.Language; import org.voltdb.groovy.GroovyScriptProcedureDelegate; import org.voltdb.utils.LogKeys; import com.google_voltpatches.common.collect.ImmutableMap; public class LoadedProcedureSet { private static final VoltLogger hostLog = new VoltLogger("HOST"); // user procedures. ImmutableMap<String, ProcedureRunner> procs = ImmutableMap.<String, ProcedureRunner>builder().build(); // map of sysproc fragment ids to system procedures. final HashMap<Long, ProcedureRunner> m_registeredSysProcPlanFragments = new HashMap<Long, ProcedureRunner>(); final ProcedureRunnerFactory m_runnerFactory; final long m_siteId; final int m_siteIndex; final SiteProcedureConnection m_site; public LoadedProcedureSet(SiteProcedureConnection site, ProcedureRunnerFactory runnerFactory, long siteId, int siteIndex) { m_runnerFactory = runnerFactory; m_siteId = siteId; m_siteIndex = siteIndex; m_site = site; } public ProcedureRunner getSysproc(long fragmentId) { synchronized (m_registeredSysProcPlanFragments) { return m_registeredSysProcPlanFragments.get(fragmentId); } } public void registerPlanFragment(final long pfId, final ProcedureRunner proc) { synchronized (m_registeredSysProcPlanFragments) { assert(m_registeredSysProcPlanFragments.containsKey(pfId) == false); m_registeredSysProcPlanFragments.put(pfId, proc); } } public void loadProcedures( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp) { m_registeredSysProcPlanFragments.clear(); ImmutableMap.Builder<String, ProcedureRunner> builder = loadProceduresFromCatalog(catalogContext, backendTarget, csp); loadSystemProcedures(catalogContext, backendTarget, csp, builder); procs = builder.build(); } private ImmutableMap.Builder<String, ProcedureRunner> loadProceduresFromCatalog( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp) { // load up all the stored procedures final CatalogMap<Procedure> catalogProcedures = catalogContext.database.getProcedures(); ImmutableMap.Builder<String, ProcedureRunner> builder = ImmutableMap.<String, ProcedureRunner>builder(); for (final Procedure proc : catalogProcedures) { // Sysprocs used to be in the catalog. Now they aren't. Ignore // sysprocs found in old catalog versions. (PRO-365) if (proc.getTypeName().startsWith("@")) { continue; } ProcedureRunner runner = null; VoltProcedure procedure = null; if (proc.getHasjava()) { final String className = proc.getClassname(); Language lang; try { lang = Language.valueOf(proc.getLanguage()); } catch (IllegalArgumentException e) { // default to java for earlier compiled catalogs lang = Language.JAVA; } Class<?> procClass = null; try { procClass = catalogContext.classForProcedure(className); } catch (final ClassNotFoundException e) { if (className.startsWith("org.voltdb.")) { VoltDB.crashLocalVoltDB("VoltDB does not support procedures with package names " + "that are prefixed with \"org.voltdb\". Please use a different " + "package name and retry. Procedure name was " + className + ".", false, null); } else { VoltDB.crashLocalVoltDB("VoltDB was unable to load a procedure (" + className + ") it expected to be in the " + "catalog jarfile and will now exit.", false, null); } } try { procedure = lang.accept(procedureInstantiator, procClass); } catch (final Exception e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } } else { procedure = new ProcedureRunner.StmtProcedure(); } assert(procedure != null); runner = m_runnerFactory.create(procedure, proc, csp); builder.put(proc.getTypeName().intern(), runner); } return builder; } private static Language.CheckedExceptionVisitor<VoltProcedure, Class<?>, Exception> procedureInstantiator = new Language.CheckedExceptionVisitor<VoltProcedure, Class<?>, Exception>() { @Override public VoltProcedure visitJava(Class<?> p) throws Exception { return (VoltProcedure)p.newInstance(); } @Override public VoltProcedure visitGroovy(Class<?> p) throws Exception { return new GroovyScriptProcedureDelegate(p); } }; private void loadSystemProcedures( CatalogContext catalogContext, BackendTarget backendTarget, CatalogSpecificPlanner csp, ImmutableMap.Builder<String, ProcedureRunner> builder) { Set<Entry<String,Config>> entrySet = SystemProcedureCatalog.listing.entrySet(); for (Entry<String, Config> entry : entrySet) { Config sysProc = entry.getValue(); Procedure proc = sysProc.asCatalogProcedure(); VoltSystemProcedure procedure = null; ProcedureRunner runner = null; final String className = sysProc.getClassname(); Class<?> procClass = null; // this check is for sysprocs that don't have a procedure class if (className != null) { try { procClass = catalogContext.classForProcedure(className); } catch (final ClassNotFoundException e) { if (sysProc.commercial) { continue; } hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } try { procedure = (VoltSystemProcedure) procClass.newInstance(); } catch (final InstantiationException e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } catch (final IllegalAccessException e) { hostLog.l7dlog( Level.WARN, LogKeys.host_ExecutionSite_GenericException.name(), new Object[] { m_siteId, m_siteIndex }, e); } runner = m_runnerFactory.create(procedure, proc, csp); procedure.initSysProc(m_site, this, proc, catalogContext.cluster); builder.put(entry.getKey().intern(), runner); } } } public ProcedureRunner getProcByName(String procName) { return procs.get(procName); } }
zheguang/voltdb
src/frontend/org/voltdb/LoadedProcedureSet.java
Java
agpl-3.0
8,988
/* * Copyright © Région Nord Pas de Calais-Picardie. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.entcore.cursus.controllers; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Map; import io.vertx.core.http.*; import org.entcore.common.http.filter.ResourceFilter; import org.entcore.common.user.UserInfos; import org.entcore.common.user.UserUtils; import org.entcore.common.utils.MapFactory; import org.entcore.cursus.filters.CursusFilter; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import org.vertx.java.core.http.RouteMatcher; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import fr.wseduc.rs.*; import fr.wseduc.security.ActionType; import fr.wseduc.security.SecuredAction; import fr.wseduc.webutils.Either; import fr.wseduc.webutils.http.BaseController; public class CursusController extends BaseController { //Service private final CursusService service = new CursusService(); //Webservice client & endpoint private HttpClient cursusClient; private final URL wsEndpoint; //Webservice auth request conf private final JsonObject authConf; //Auth reply data & wallets list private Map<String, String> cursusMap; @Override public void init(Vertx vertx, JsonObject config, RouteMatcher rm, Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) { super.init(vertx, config, rm, securedActions); HttpClientOptions cursusClientOptions = new HttpClientOptions() .setDefaultHost(wsEndpoint.getHost()); if("https".equals(wsEndpoint.getProtocol())){ cursusClientOptions .setSsl(true) .setTrustAll(true) .setDefaultPort(443); } else { cursusClientOptions .setDefaultPort(wsEndpoint.getPort() == -1 ? 80 : wsEndpoint.getPort()); } cursusClient = vertx.createHttpClient(cursusClientOptions); cursusMap = MapFactory.getSyncClusterMap("cursusMap", vertx, false); /* service.refreshToken(new Handler<Boolean>() { public void handle(Boolean res) { if(!res) log.error("[Cursus][refreshToken] Error while retrieving the Token."); else log.info("[Cursus][refreshToken] Token refreshed."); } }); */ if(cursusMap.containsKey("wallets")) return; service.refreshWallets(new Handler<Boolean>() { public void handle(Boolean res) { if(!res) log.error("[Cursus][refreshWallets] Error while retrieving the wallets list."); else log.info("[Cursus][refreshWallets] Wallets list refreshed."); } }); } public CursusController(URL endpoint, final JsonObject conf){ wsEndpoint = endpoint; authConf = conf; } @Put("/refreshToken") @SecuredAction(value = "", type = ActionType.RESOURCE) @ResourceFilter(CursusFilter.class) public void refreshToken(final HttpServerRequest request){ service.refreshToken(new Handler<Boolean>() { public void handle(Boolean success) { if(success){ ok(request); } else { badRequest(request); } } }); } @Put("/refreshWallets") @SecuredAction(value = "", type = ActionType.RESOURCE) @ResourceFilter(CursusFilter.class) public void refreshWallets(final HttpServerRequest request){ service.refreshWallets(new Handler<Boolean>() { public void handle(Boolean success) { if(success){ ok(request); } else { badRequest(request); } } }); } @Get("/sales") @SecuredAction(value = "", type = ActionType.AUTHENTICATED) public void getSales(final HttpServerRequest request){ final String cardNb = request.params().get("cardNb"); if(cardNb == null){ badRequest(request); return; } service.getUserInfo(cardNb, new Handler<Either<String,JsonArray>>() { public void handle(Either<String, JsonArray> result) { if(result.isLeft()){ badRequest(request); return; } final String id = result.right().getValue().getJsonObject(0).getInteger("id").toString(); String birthDateEncoded = result.right().getValue().getJsonObject(0).getString("dateNaissance"); try { birthDateEncoded = birthDateEncoded.replace("/Date(", ""); birthDateEncoded = birthDateEncoded.substring(0, birthDateEncoded.indexOf("+")); final Date birthDate = new Date(Long.parseLong(birthDateEncoded)); UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { public void handle(UserInfos infos) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { Date sessionBirthDate = format.parse(infos.getBirthDate()); if(sessionBirthDate.compareTo(birthDate) == 0){ service.getSales(id, cardNb, new Handler<Either<String,JsonArray>>() { public void handle(Either<String, JsonArray> result) { if(result.isLeft()){ badRequest(request); return; } JsonObject finalResult = new JsonObject() .put("wallets", new JsonArray(cursusMap.get("wallets"))) .put("sales", result.right().getValue()); renderJson(request, finalResult); } }); } else { badRequest(request); } } catch (ParseException e) { badRequest(request); return; } } }); } catch(Exception e){ badRequest(request); } } }); } /** * Inner service class. */ private class CursusService{ public void authWrapper(final Handler<Boolean> handler){ JsonObject authObject = new JsonObject(); if(cursusMap.get("auth") != null) authObject = new JsonObject(cursusMap.get("auth")); Long currentDate = Calendar.getInstance().getTimeInMillis(); Long expirationDate = 0l; if(authObject != null) expirationDate = authObject.getLong("tokenInit", 0l) + authConf.getLong("tokenDelay", 1800000l); if(expirationDate < currentDate){ log.info("[Cursus] Token seems to have expired."); refreshToken(handler); } else { handler.handle(true); } } public void refreshToken(final Handler<Boolean> handler){ HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/AuthentificationImpl.svc/json/AuthentificationExtranet", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(false); log.error(response.statusMessage()); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { log.info("[Cursus][refreshToken] Token refreshed."); JsonObject authData = new JsonObject(body.toString()); authData.put("tokenInit", new Date().getTime()); cursusMap.put("auth", authData.encode()); handler.handle(true); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(authConf.encode()); } public void refreshWallets(final Handler<Boolean> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(false); return; } int schoolYear = Calendar.getInstance().get(Calendar.MONTH) < 8 ? Calendar.getInstance().get(Calendar.YEAR) - 1 : Calendar.getInstance().get(Calendar.YEAR); /* JSON */ JsonObject reqBody = new JsonObject(); reqBody .put("numSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("typeListes", new JsonArray() .add(new JsonObject() .put("typeListe", "LST_PORTEMONNAIE") .put("param1", schoolYear + "-" + (schoolYear + 1)) ) ); /* */ /* XML / String reqBody = "<tem:GetListes xmlns:tem=\"http://tempuri.org/\" xmlns:wcf=\"http://schemas.datacontract.org/2004/07/WcfExtranetChequeBL.POCO.Parametres\">" + "<tem:numSite>"+ authConf.getString("numSite") +"</tem:numSite>" + "<tem:typeListes>" + "<wcf:RechercheTypeListe>" + "<wcf:typeListe>LST_PORTEMONNAIE</wcf:typeListe>" + "<wcf:param1>"+ schoolYear + "-" + (schoolYear + 1) +"</wcf:param1>" + "</wcf:RechercheTypeListe>" + "</tem:typeListes>" + "<tem:tokenId>"+ authData.getString("tokenId") +"</tem:tokenId>" + "</tem:GetListes>"; /* */ HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/GeneralImpl.svc/json/GetListes", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(false); log.error(response.statusMessage()); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { try{ cursusMap.put("wallets", new JsonArray(body.toString()).getJsonObject(0) .getJsonArray("parametres").encode()); handler.handle(true); } catch(Exception e){ handler.handle(false); } } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); }; public void getUserInfo(final String cardNb, final Handler<Either<String, JsonArray>> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(new Either.Left<String, JsonArray>("[Cursus][getUserInfo] Issue while retrieving token.")); return; } JsonObject reqBody = new JsonObject(); reqBody .put("numSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("filtres", new JsonObject() .put("numeroCarte", cardNb)); HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/BeneficiaireImpl.svc/json/GetListeBeneficiaire", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(new Either.Left<String, JsonArray>("invalid.status.code")); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { handler.handle(new Either.Right<String, JsonArray>(new JsonArray(body.toString()))); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); } public void getSales(final String numeroDossier, final String cardNb, final Handler<Either<String, JsonArray>> handler){ authWrapper(new Handler<Boolean>() { public void handle(Boolean gotToken) { if(!gotToken){ handler.handle(new Either.Left<String, JsonArray>("[Cursus][getSales] Issue while retrieving token.")); return; } JsonObject reqBody = new JsonObject(); reqBody .put("numeroSite", authConf.getString("numSite")) .put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId")) .put("filtresSoldesBeneficiaire", new JsonObject() .put("numeroDossier", numeroDossier) .put("numeroCarte", cardNb)); HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/BeneficiaireImpl.svc/json/GetSoldesBeneficiaire", new Handler<HttpClientResponse>() { public void handle(HttpClientResponse response) { if(response.statusCode() >= 300){ handler.handle(new Either.Left<String, JsonArray>("invalid.status.code")); return; } response.bodyHandler(new Handler<Buffer>() { public void handle(Buffer body) { handler.handle(new Either.Right<String, JsonArray>(new JsonArray(body.toString()))); } }); } }); req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8") .putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); req.end(reqBody.encode()); } }); } } }
OPEN-ENT-NG/cursus
src/main/java/org/entcore/cursus/controllers/CursusController.java
Java
agpl-3.0
13,069
/* * LICENCE : CloudUnit is available under the Affero Gnu Public License GPL V3 : https://www.gnu.org/licenses/agpl-3.0.html * but CloudUnit is licensed too under a standard commercial license. * Please contact our sales team if you would like to discuss the specifics of our Enterprise license. * If you are not sure whether the GPL is right for you, * you can always test our software under the GPL and inspect the source code before you contact us * about purchasing a commercial license. * * LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse * or promote products derived from this project without prior written permission from Treeptik. * Products or services derived from this software may not be called "CloudUnit" * nor may "Treeptik" or similar confusing terms appear in their names without prior written permission. * For any questions, contact us : contact@treeptik.fr */ package fr.treeptik.cloudunit.modules.redis; import fr.treeptik.cloudunit.modules.AbstractModuleControllerTestIT; /** * Created by guillaume on 01/10/16. */ public class Wildfly8Redis32ModuleControllerTestIT extends AbstractModuleControllerTestIT { public Wildfly8Redis32ModuleControllerTestIT() { super.server = "wildfly-8"; super.module = "redis-3-2"; super.numberPort = "6379"; super.managerPrefix = ""; super.managerSuffix = ""; super.managerPageContent = ""; } @Override protected void checkConnection(String forwardedPort) { new CheckRedisConnection().invoke(forwardedPort); } }
Treeptik/cloudunit
cu-manager/src/test/java/fr/treeptik/cloudunit/modules/redis/Wildfly8Redis32ModuleControllerTestIT.java
Java
agpl-3.0
1,612
package com.wirecard.acqp.two; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; @Ignore @SuppressWarnings("javadoc") public class ThreadingLongrunningTest { /** * The number of threads to use in this test. */ private static final int NUM_THREADS = 12; /** * Flag to indicate the concurrent test has failed. */ private boolean failed; @Test public void testConcurrently() { final ParserHardeningLongrunningTest pt = new ParserHardeningLongrunningTest(); final String msg = "F0F1F0F0723C440188E18008F1F9F5F4F0F5F6F2F0F0F0F0F0F0F0F0F0F0F0F1F4F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F5F0F5F0F1F2F0F1F3F0F3F0F9F5F8F9F2F7F8F1F3F0F3F0F9F0F1F2F0F1F5F1F1F5F4F1F1F8F1F2F0F6F0F1F3F4F0F1F0F6F2F0F0F3F5F0F0F1F2F0F1F4F5F4F9F3F5F482F0F0F0F0F0F0F1D9C5E3D382F0F0F0F0F0F0F1404040C3C3C240E3F140E28899A340D581948540404040404040C3C3C240E3F140E28899A340D340D7C1D5F0F6F0E3F6F1F0F5F0F0F0F0F1F9F2F0F35C5C5CF4F2F0F7F0F1F0F3F2F1F2F4F3F2F891C982A884F6E38581889492C1C2C5C1C1C1C699D894A8E7A694F07EF9F7F8F0F2F1F1F0F2F5F1F0F0F0F0F6F0F0F0F5F9F1D7C1D5F1F2"; Runnable runnable = new Runnable() { public void run() { try { pt.testParserHardeningJCB(); pt.testParserHardeningMC(); String fieldValue = MsgAccessoryImpl.readFieldValue(msg, "MASTERCARD", "2"); assertEquals("PAN (Field 2) was not read correctly.", "5405620000000000014", fieldValue); String mti = MsgAccessoryImpl.readFieldValue(msg, "MASTERCARD", "0"); assertEquals("mti was not read correctly.", "0100", mti); pt.testParserHardeningVisa(); } catch (Exception e) { failed = true; } } }; Thread[] threads = new Thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(runnable); } for (int i = 0; i < NUM_THREADS; i++) { threads[i].start(); } for (int i = 0; i < NUM_THREADS; i++) { try { threads[i].join(); } catch (InterruptedException e) { failed = true; } } assertFalse(failed); } // @Test obsolet but temp // public void testGetFieldValueMixedgetFieldMethods() // throws IllegalArgumentException, ISOException, // IllegalStateException, UnsupportedEncodingException { // // // UtilityMethodAccess after construktor // String msg = // "F0F1F0F0723C440188E18008F1F9F5F4F0F5F6F2F0F0F0F0F0F0F0F0F0F0F0F1F4F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F5F0F5F0F1F2F0F1F3F0F3F0F9F5F8F9F2F7F8F1F3F0F3F0F9F0F1F2F0F1F5F1F1F5F4F1F1F8F1F2F0F6F0F1F3F4F0F1F0F6F2F0F0F3F5F0F0F1F2F0F1F4F5F4F9F3F5F482F0F0F0F0F0F0F1D9C5E3D382F0F0F0F0F0F0F1404040C3C3C240E3F140E28899A340D581948540404040404040C3C3C240E3F140E28899A340D340D7C1D5F0F6F0E3F6F1F0F5F0F0F0F0F1F9F2F0F35C5C5CF4F2F0F7F0F1F0F3F2F1F2F4F3F2F891C982A884F6E38581889492C1C2C5C1C1C1C699D894A8E7A694F07EF9F7F8F0F2F1F1F0F2F5F1F0F0F0F0F6F0F0F0F5F9F1D7C1D5F1F2"; // assertEquals("PAN (Field 2) was not read correctly.", // "5405620000000000014", // msgAccessoryInitial.getFieldValue(msg, "MASTERCARD", "2")); // // assertEquals("PAN (Field 2) was not equal.", // "5400041234567898", // msgAccessoryInitial.getFieldValue("2")); // // // UtilityMethodAccess after construktor // assertEquals("PAN (Field 2) was not read correctly.", // "5405620000000000014", // msgAccessoryInitial.getFieldValue(msg, "MASTERCARD", "2")); // // } }
wakantanka/get_iso_8583
src/test/java/com/wirecard/acqp/two/ThreadingLongrunningTest.java
Java
agpl-3.0
3,989
package com.simplyian.superplots.actions; import static org.mockito.Matchers.contains; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import java.util.Arrays; import java.util.List; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.simplyian.superplots.EconHook; import com.simplyian.superplots.SPSettings; import com.simplyian.superplots.SuperPlotsPlugin; import com.simplyian.superplots.plot.Plot; import com.simplyian.superplots.plot.PlotManager; public class ActionWithdrawTest { private SuperPlotsPlugin main; private ActionWithdraw action; private PlotManager plotManager; private Player player; private EconHook econ; @Before public void setup() { main = mock(SuperPlotsPlugin.class); action = new ActionWithdraw(main); econ = mock(EconHook.class); when(main.getEconomy()).thenReturn(econ); plotManager = mock(PlotManager.class); when(main.getPlotManager()).thenReturn(plotManager); SPSettings settings = mock(SPSettings.class); when(main.getSettings()).thenReturn(settings); when(settings.getInfluenceMultiplier()).thenReturn(1.5); when(settings.getInitialPlotSize()).thenReturn(10); player = mock(Player.class); when(player.getName()).thenReturn("albireox"); } @After public void tearDown() { main = null; action = null; plotManager = null; player = null; } @Test public void test_perform_notInPlot() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(plotManager.getPlotAt(playerLoc)).thenReturn(null); List<String> args = Arrays.asList("asdf"); action.perform(player, args); verify(player).sendMessage(contains("not in a plot")); } @Test public void test_perform_mustBeAdministrator() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(false); when(player.getName()).thenReturn("albireox"); List<String> args = Arrays.asList(); action.perform(player, args); verify(player).sendMessage(contains("must be an administrator")); } @Test public void test_perform_noAmount() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); List<String> args = Arrays.asList(); action.perform(player, args); verify(player).sendMessage(contains("did not specify")); } @Test public void test_perform_notANumber() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(econ.getBalance("albireox")).thenReturn(200.0); List<String> args = Arrays.asList("400x"); action.perform(player, args); verify(player).sendMessage(contains("not a valid amount")); } @Test public void test_perform_notEnoughMoney() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(plot.getFunds()).thenReturn(200); List<String> args = Arrays.asList("400"); action.perform(player, args); verify(player).sendMessage(contains("doesn't have that much money")); } @Test public void test_perform_success() { World world = mock(World.class); Location playerLoc = new Location(world, 0, 0, 0); when(player.getLocation()).thenReturn(playerLoc); Plot plot = mock(Plot.class); when(plotManager.getPlotAt(playerLoc)).thenReturn(plot); when(plot.isAdministrator("albireox")).thenReturn(true); when(player.getName()).thenReturn("albireox"); when(plot.getFunds()).thenReturn(400); List<String> args = Arrays.asList("400"); action.perform(player, args); verify(player).sendMessage(contains("has been withdrawn")); verify(plot).subtractFunds(400); verify(econ).addBalance("albireox", 400); } }
simplyianm/SuperPlots
src/test/java/com/simplyian/superplots/actions/ActionWithdrawTest.java
Java
agpl-3.0
5,323