repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
NickCharsley/zoodb | src/org/zoodb/internal/server/index/IndexFactory.java | 2783 | /*
* Copyright 2009-2015 Tilmann Zaeschke. All rights reserved.
*
* This file is part of ZooDB.
*
* ZooDB 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.
*
* ZooDB 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 ZooDB. If not, see <http://www.gnu.org/licenses/>.
*
* See the README and COPYING files for further information.
*/
package org.zoodb.internal.server.index;
import org.zoodb.internal.server.DiskIO.PAGE_TYPE;
import org.zoodb.internal.server.StorageChannel;
public class IndexFactory {
/**
* @param type
* @param storage
* @return a new index
*/
public static LongLongIndex createIndex(PAGE_TYPE type, StorageChannel storage) {
return new PagedLongLong(type, storage);
}
/**
* @param type
* @param storage
* @param pageId page id of the root page
* @return an index reconstructed from disk
*/
public static LongLongIndex loadIndex(PAGE_TYPE type, StorageChannel storage, int pageId) {
return new PagedLongLong(type, storage, pageId);
}
/**
* @param type
* @param storage
* @return a new index
*/
public static LongLongIndex.LongLongUIndex createUniqueIndex(PAGE_TYPE type,
StorageChannel storage) {
return new PagedUniqueLongLong(type, storage);
}
/**
* @param type
* @param storage
* @param pageId page id of the root page
* @return an index reconstructed from disk
*/
public static LongLongIndex.LongLongUIndex loadUniqueIndex(PAGE_TYPE type,
StorageChannel storage, int pageId) {
return new PagedUniqueLongLong(type, storage, pageId);
}
/**
* EXPERIMENTAL! Index that has bit width of key and value as parameters.
* @param type
* @param storage
* @return a new index
*/
public static LongLongIndex.LongLongUIndex createUniqueIndex(PAGE_TYPE type,
StorageChannel storage, int keySize, int valSize) {
return new PagedUniqueLongLong(type, storage, keySize, valSize);
}
/**
* EXPERIMENTAL! Index that has bit width of key and value as parameters.
* @param type
* @param storage
* @param pageId page id of the root page
* @return an index reconstructed from disk
*/
public static LongLongIndex.LongLongUIndex loadUniqueIndex(PAGE_TYPE type,
StorageChannel storage, int pageId, int keySize, int valSize) {
return new PagedUniqueLongLong(type, storage, pageId, keySize, valSize);
}
}
| gpl-3.0 |
deodaj/MCMBTools | src/main/java/com/Deoda/MCMBTools/proxy/IProxy.java | 65 | package com.Deoda.MCMBTools.proxy;
public interface IProxy {
}
| gpl-3.0 |
Raulvo/vhdl | assembler/src/assembler/Opcodes.java | 3587 | /*******************************************************************************
* Copyright (c) 2016 Raul Vidal Ortiz.
*
* This file is part of Assembler.
*
* Assembler 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.
*
* Assembler 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 Assembler. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package assembler;
public final class Opcodes {
public static final String nop = "00000000";
public static final String halt = "11111111";
public static final String addd = "00000001";
public static final String subd = "00000010";
public static final String movd = "00001001";
public static final String movi = "00011001";
public static final String movhi = "00101001";
public static final String ld = "01000000";
public static final String sd = "01000001";
public static final String jmp = "10000100";
public static final String beq = "10000000";
public static final Integer bitsinst = 32;
public static final Integer bytesinst = bitsinst/8;
public static final Integer bitsopcode = 8;
public static final Integer bitsreg = 5;
public static final Integer numregs = (int) Math.pow(2, Opcodes.bitsreg);
public static final Integer bitsaddress = 32;
public static final Integer bitsoffset = 14;
public static final Integer bitsimmmov = 19;
public static final Integer bitsjmpaddr = 24;
public static final Integer limitposaddr = (int) Math.pow(2,Opcodes.bitsaddress-1)-1;
public static final Integer limitnegaddr = 0;
public static final Integer limitposoffset = (int) Math.pow(2, Opcodes.bitsoffset-1)-1;
public static final Integer limitnegoffset = (int) -(Math.pow(2, Opcodes.bitsoffset-1));
public static final Integer limitposimmov = (int) Math.pow(2, Opcodes.bitsimmmov-1)-1;
public static final Integer limitnegimmov = (int) -(Math.pow(2, Opcodes.bitsimmmov-1));
public static final Integer limitposjmpaddr = (int) Math.pow(2, Opcodes.bitsjmpaddr-1)-1;
public static final Integer limitnegjmpaddr = (int) -(Math.pow(2, Opcodes.bitsjmpaddr-1));
private Opcodes() {}
public static String OpStringToOpcode(String op) {
switch (op) {
case "nop":
return Opcodes.nop;
case "halt":
return Opcodes.halt;
case "addd":
return Opcodes.addd;
case "subd":
return Opcodes.subd;
case "movd":
return Opcodes.movd;
case "movi":
return Opcodes.movi;
case "movhi":
return Opcodes.movhi;
case "ld":
return Opcodes.ld;
case "sd":
return Opcodes.sd;
case "jmp":
return Opcodes.jmp;
case "beq":
return Opcodes.beq;
}
return null;
}
public static String addZeroes(String binary, Integer size) {
if (binary.length() < size) {
Integer distance = size-binary.length();
for (int i = 0; i < distance; i++) {
binary = "0".concat(binary);
}
}
return binary;
}
public static String trimOnes(String binary, Integer size) {
Integer distance = binary.length() - size;
return binary.substring(distance);
}
}
| gpl-3.0 |
encapturemd/MirthConnect | client/src/com/mirth/connect/plugins/TransformerStepPlugin.java | 610 | /*
* Copyright (c) Mirth Corporation. All rights reserved.
*
* http://www.mirthcorp.com
*
* The software in this package is published under the terms of the MPL license a copy of which has
* been included with this distribution in the LICENSE.txt file.
*/
package com.mirth.connect.plugins;
import com.mirth.connect.client.ui.editors.transformer.TransformerPane;
public abstract class TransformerStepPlugin extends MirthEditorPanePlugin {
public TransformerStepPlugin(String name) {
super(name);
}
public abstract void initialize(TransformerPane pane);
}
| mpl-2.0 |
tfearn/AdaptinetSDK | src/org/adaptinet/mimehandlers/MimeHTML_HTTP.java | 15471 | /**
* Copyright (C), 2012 Adaptinet.org (Todd Fearn, Anthony Graffeo)
*
* 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.adaptinet.mimehandlers;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import org.adaptinet.http.HTTP;
import org.adaptinet.http.Request;
import org.adaptinet.http.Response;
import org.adaptinet.socket.PropData;
import org.adaptinet.transceiver.ITransceiver;
public class MimeHTML_HTTP implements MimeBase {
private String url = null;
private String urlBase = null;
private String webBase = null;
private String mimeType = null;
private String pathName = null;
private ITransceiver transceiver = null;
private int status = 200;
private boolean bAdminPort = false;
static private String PLUGIN_ENTRY = "plugins/plugin?entry=";
static private String PEER_ENTRY = "peers/peer?entry=";
static private int PLUGIN_ENTRYLEN = 0;
static private int PEER_ENTRYLEN = 0;
static final String footer = "<br><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" "
+ "width=\"100%\" ><tr><td width=\"127\" class=\"footerorange\">"
+ "<IMG height=\"1\" src=\"/images/space.gif\" width=\"127\"></td><td width=\"400\" "
+ "class=\"footerorange\"><IMG height=\"1\" src=\"/images/space.gif\" width=\"400\"></td>"
+ "<td width=\"100%\" class=\"footerorange\"><IMG height=\"1\" src=\"/images/space.gif\" "
+ "width=\"1\"></td></tr><tr><td width=\"127\" class=\"footerorange\">"
+ "<IMG height=27 src=\"/images/space.gif\" width=127></td><td align=\"left\" "
+ "class=\"footerorange\" nowrap>25 B Vreeland Rd. Suite 103, Florham Park, NJ"
+ " 07932 973-451-9600 fx 973-439-1745</td>"
+ "<td width=\"100%\" class=\"footerorange\"><IMG height=27 "
+ "src=\"/images/space.gif\" width=1></td></tr><tr><td width=\"127\">"
+ "<IMG height=1 src=\"/images/space.gif\" width=127></td><td align=\"left\" "
+ "class=\"footer\" nowrap>all materials © Adaptinet Inc. All rights reserved.</td>"
+ "<td align=\"right\" width=\"100%\" class=\"footer\" nowrap>"
+ "<A class=\"footerlink\" href=\"#\">contact Adaptinet</A> | "
+ " <A class=\"footerlink\" href=\"#\">support</A> </td></tr></table><br><br><br><br>";
static {
PLUGIN_ENTRYLEN = PLUGIN_ENTRY.length();
PEER_ENTRYLEN = PEER_ENTRY.length();
}
public MimeHTML_HTTP() {
}
public void init(String u, ITransceiver s) {
transceiver = s;
urlBase = s.getHTTPRoot();
webBase = s.getWebRoot();
if (urlBase == null || urlBase.equals(".")) {
urlBase = System.getProperty("user.dir", "");
}
if (!urlBase.endsWith(File.separator))
urlBase += File.separator;
if (webBase == null || webBase.equals(".")) {
webBase = System.getProperty("user.dir", "");
}
if (!webBase.endsWith(File.separator))
webBase += File.separator;
url = u;
parseUrl();
}
private void parseUrl() {
try {
pathName = URLDecoder.decode(url, "UTF-8");
} catch (Exception e) {
pathName = url;
}
if (pathName.endsWith("/"))
pathName += "index.html";
if (pathName.startsWith("/"))
pathName = pathName.substring(1);
int dot = pathName.indexOf(".");
if (dot > 0) {
String ext = pathName.substring(dot + 1);
setMimeForExt(ext);
} else
mimeType = HTTP.contentTypeHTML;
}
public String getContentType() {
return mimeType;
}
private void setMimeForExt(String ext) {
if (ext.equalsIgnoreCase("jpg"))
mimeType = HTTP.contentTypeJPEG;
else if (ext.equalsIgnoreCase("htm") || ext.equalsIgnoreCase("html"))
mimeType = HTTP.contentTypeHTML;
else if (ext.equalsIgnoreCase("gif"))
mimeType = HTTP.contentTypeGIF;
else if (ext.equalsIgnoreCase("xsl"))
mimeType = HTTP.contentTypeXML;
else
mimeType = HTTP.contentTypeHTML;
}
public ByteArrayOutputStream process(ITransceiver transceiver,
Request request) {
// note: this process has gotten pretty big, really fast
// need to revisit the exception handling here, there is a better way
File file = null;
String monitor = null;
long length = 0;
try {
bAdminPort = (request.getPort() == transceiver.getAdminPort());
status = isAuthorized(request.getUsername(), request.getPassword());
if (!bAdminPort) {
// non-admin port are regular html requests...
String base = webBase;
if (bAdminPort)
base = urlBase;
file = new File(base + pathName);
if (file.isFile() == false || !file.canRead())
throw new FileNotFoundException();
else
length = file.length();
} else {
if (pathName.equalsIgnoreCase("configuration.html")) {
if (status == HTTP.UNAUTHORIZED || bAdminPort == false)
throw new IllegalAccessException();
monitor = getConfiguration(transceiver);
System.out.println(monitor);
if (monitor != null)
length = monitor.length();
else
status = HTTP.NOT_FOUND;
} else if (pathName.equalsIgnoreCase("monitor.html")) {
if (status == HTTP.UNAUTHORIZED || bAdminPort == false)
throw new IllegalAccessException();
try {
monitor = getMonitor();
length = monitor.length();
} catch (Exception e) {
monitor = e.getMessage();
status = HTTP.INTERNAL_SERVER_ERROR;
} catch (Throwable t) {
monitor = t.getMessage();
status = HTTP.INTERNAL_SERVER_ERROR;
}
} else if (pathName.equalsIgnoreCase("plugins.html")) {
if (status == HTTP.UNAUTHORIZED || bAdminPort == false)
throw new IllegalAccessException();
monitor = getPlugins(transceiver);
if (monitor != null)
length = monitor.length();
else
status = HTTP.INTERNAL_SERVER_ERROR;
} else if (pathName.equalsIgnoreCase("peers.html")) {
if (status == HTTP.UNAUTHORIZED || bAdminPort == false)
throw new IllegalAccessException();
monitor = getPeers(transceiver);
if (monitor != null)
length = monitor.length();
else
status = HTTP.INTERNAL_SERVER_ERROR;
} else if (pathName.startsWith(PLUGIN_ENTRY)) {
if (status == HTTP.UNAUTHORIZED || bAdminPort == false)
throw new IllegalAccessException();
if (pathName.length() > PLUGIN_ENTRYLEN)
monitor = getPluginEntry(transceiver, pathName
.substring(PLUGIN_ENTRYLEN));
else
monitor = getPluginEntry(transceiver, "");
if (monitor != null)
length = monitor.length();
else
status = HTTP.NOT_FOUND;
} else if (pathName.startsWith(PEER_ENTRY)) {
if (status == HTTP.UNAUTHORIZED || bAdminPort == false)
throw new IllegalAccessException();
if (pathName.length() > PEER_ENTRYLEN)
monitor = getPeerEntry(transceiver, pathName
.substring(PEER_ENTRYLEN));
else
monitor = getPeerEntry(transceiver, "");
if (monitor != null)
length = monitor.length();
else
status = HTTP.NOT_FOUND;
} else if (pathName.startsWith("setadmin?")) {
if (status == HTTP.UNAUTHORIZED || bAdminPort == false)
throw new IllegalAccessException();
monitor = setAdmin(pathName.substring(9), request);
length = monitor.length();
} else // files
{
String base = webBase;
if (bAdminPort)
base = urlBase;
file = new File(base + pathName);
if (file.isFile() == false || !file.canRead())
throw new FileNotFoundException();
else
length = file.length();
}
}
} catch (IOException e) {
status = HTTP.NOT_FOUND;
} catch (IllegalAccessException iae) {
status = HTTP.UNAUTHORIZED;
} catch (Exception e) {
status = HTTP.INTERNAL_SERVER_ERROR;
}
try {
Response resp = new Response(request.getOutStream(), transceiver
.getHost(), mimeType);
resp.setResponse(new ByteArrayOutputStream());
resp.setStatus(status);
resp.writeHeader(length);
if (status != HTTP.OK)
return null;
BufferedOutputStream out = new BufferedOutputStream(request
.getOutStream());
if (file != null) {
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(file));
byte[] bytes = new byte[255];
while (true) {
int read = in.read(bytes);
if (read < 0)
break;
out.write(bytes, 0, read);
}
in.close();
} else if (monitor != null) {
out.write(monitor.getBytes());
}
out.flush();
} catch (Exception e) {
}
return null;
}
public static String getPlugins(ITransceiver transceiver) {
try {
return PluginXML.getEntries(transceiver);
} catch (Exception e) {
return null;
}
}
public static String getPeers(ITransceiver transceiver) {
try {
return PeerXML.getEntries(transceiver);
} catch (Exception e) {
return null;
}
}
public static String getConfiguration(ITransceiver transceiver) {
try {
return TransceiverConfiguration.getConfiguration(transceiver);
} catch (Exception e) {
return null;
}
}
public static String getPluginEntry(ITransceiver transceiver, String entry) {
try {
return PluginXML.getEntry(transceiver, entry);
} catch (Exception e) {
return null;
}
}
public static String getPeerEntry(ITransceiver transceiver, String peer) {
try {
return PeerXML.getEntry(transceiver, peer);
} catch (Exception e) {
return null;
}
}
public static String getLicenseKey(ITransceiver transceiver) {
try {
// return
// simpleTransform.transform(licensingXML.getLicense(transceiver),
// transceiver.getHTTPRoot() + "/licensing.xsl");
return null;
} catch (Exception e) {
return null;
}
}
private String setAdmin(String params, Request request) {
try {
StringTokenizer tokenizer = new StringTokenizer(params, "&");
int size = tokenizer.countTokens() * 2;
String token = null;
Properties properties = new Properties();
for (int i = 0; i < size; i += 2) {
if (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
int loc = token.indexOf('=');
properties.setProperty(token.substring(0, loc), token
.substring(loc + 1, token.length()));
}
}
String userid = properties.getProperty("userid");
String current = properties.getProperty("current");
String password = properties.getProperty("password");
String confirm = properties.getProperty("password2");
// check current password here
if (isAuthorized(request.getUsername(), current) == HTTP.UNAUTHORIZED)
return "<H2>The current password is incorrect for user: "
+ request.getUsername() + "</H2>";
if (!password.equals(confirm))
return "<H2>The password does not match the confirm password</H2>";
if (password.equals(""))
return "<H2>The password cannot be empty.</H2>";
MessageDigest md = MessageDigest.getInstance("MD5");
String digest = new String(md.digest(password.getBytes()));
String userpass = userid + ":" + digest;
String authfile = urlBase + ".xbpasswd";
FileOutputStream fs = new FileOutputStream(authfile);
fs.write(userpass.getBytes());
fs.close();
return "<H2>Change password success for " + userid + "</H2>";
} catch (Exception e) {
}
return "<H2>Change password failure.</H2>";
}
public int getStatus() {
return status;
}
private int isAuthorized(String username, String password) {
try {
if (!bAdminPort)
return HTTP.OK;
String authfile = urlBase + ".xbpasswd";
File file = new File(authfile);
if (!file.isFile())
return HTTP.OK;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String userpass = br.readLine();
br.close();
StringTokenizer st = new StringTokenizer(userpass, ":");
String user = st.hasMoreTokens() ? st.nextToken() : "";
String pass = st.hasMoreTokens() ? st.nextToken() : "";
MessageDigest md = MessageDigest.getInstance("MD5");
String digest = new String(md.digest(password != null ? password
.getBytes() : "".getBytes()));
if (user.equals(username) && pass.equals(digest))
return HTTP.OK;
} catch (IOException ioe) {
} catch (NullPointerException npe) {
} catch (Exception e) {
e.printStackTrace();
}
return HTTP.UNAUTHORIZED;
}
String getMonitor() {
StringBuffer buffer = new StringBuffer();
try {
Vector<PropData> vec = transceiver.requestList();
buffer.append("<html><head><title>Status</title>");
buffer.append("<link rel=\"Stylesheet\" href=\"/style.css\">");
buffer.append("<script language=\"JavaScript\" src=\"/css.js\"></script></head>");
buffer.append("<body BGCOLOR=\"#FFFFFF\">");
buffer.append("<TABLE cellPadding=0 cellSpacing=0 border=0 WIDTH=\"500\"<tr><TD><IMG alt=\"\" src=\"images/empty.gif\" width=30 border=0></TD><td>");
buffer.append("<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">");
buffer.append("<tr valign=\"top\" class=\"header\">");
buffer.append("<td>Plugin Name</td>");
buffer.append("<td>System ID</td>");
buffer.append("<td>Status</td>");
buffer.append("<td>Control</td></tr>");
Enumeration<PropData> e = vec.elements();
while (e.hasMoreElements()) {
PropData data = e.nextElement();
buffer.append("<tr class=\"text\">");
buffer.append("<td><strong>");
buffer.append(data.getName());
buffer.append("</strong></td>");
buffer.append("<td>");
buffer.append(data.getId());
buffer.append("</td>");
buffer.append("<td>");
buffer.append(data.getState());
buffer.append("</td>");
buffer.append("<td>");
buffer.append("<FORM Method=\"POST\" Action=\"\">");
buffer
.append("<INPUT type=\"hidden\" name=\"command\" value=\"killrequest\"></INPUT>");
buffer
.append("<INPUT TYPE=\"Submit\" value=\" Kill \"></INPUT>");
buffer
.append("<INPUT type=\"checkbox\" name=\"Force\" value=\"true\">Force</INPUT>");
buffer.append("<INPUT type=\"hidden\" ");
buffer.append("name=\"SYSTEMID\" ");
buffer.append("value=\">");
buffer.append(data.getId());
buffer.append("\"></INPUT>");
buffer.append("<INPUT type=\"hidden\" ");
buffer.append("name=\"Name\" ");
buffer.append("value=\">");
buffer.append(data.getName());
buffer.append("\"></INPUT>");
buffer.append("</td>");
}
buffer.append("</FORM>");
buffer.append("</table></td></tr></table>");
buffer.append(footer);
buffer.append("</body>");
buffer.append("</html>");
} catch (Exception e) {
return null;
}
return buffer.toString();
}
}
| mpl-2.0 |
dimy93/sports-cubed-android | OSMBonusPack/src/org/osmdroid/bonuspack/utils/WebImageCache.java | 1601 | package org.osmdroid.bonuspack.utils;
import java.util.LinkedHashMap;
import android.graphics.Bitmap;
import android.util.Log;
/**
* Simple memory cache for handling images loaded from the web.
* The url is the key.
* @author M.Kergall
*/
public class WebImageCache {
LinkedHashMap<String, Bitmap> mCacheMap;
int mCapacity;
public WebImageCache(int maxItems) {
mCapacity = maxItems;
mCacheMap = new LinkedHashMap<String, Bitmap>(maxItems+1, 1.1f, true){
private static final long serialVersionUID = -4831331496601290979L;
protected boolean removeEldestEntry(Entry<String, Bitmap> eldest) {
return size() > mCapacity;
}
};
}
private void putInCache(String url, Bitmap image){
synchronized(mCacheMap){
mCacheMap.put(url, image);
}
//Log.d(BonusPackHelper.LOG_TAG, "WebImageCache:updateCache size="+mCacheMap.size());
}
/**
* get the image, either from the cache, or from the web if not in the cache.
* Can be called by multiple threads.
* If 2 threads ask for the same url simultaneously, this could put the image twice in the cache.
* => TODO, have a "queue" of current requests.
* @param url of the image
* @return the image, or null if any failure.
*/
public Bitmap get(String url){
Bitmap image;
synchronized(mCacheMap) {
image = mCacheMap.get(url);
}
if (image == null){
Log.d(BonusPackHelper.LOG_TAG, "WebImageCache:load :"+url);
image = BonusPackHelper.loadBitmap(url);
if (image != null){
putInCache(url, image);
}
}
return image;
}
}
| mpl-2.0 |
itesla/ipst-core | commons/src/main/java/eu/itesla_project/commons/io/mmap/MemoryMappedFileFactory.java | 600 | /**
* Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium)
* 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 eu.itesla_project.commons.io.mmap;
import java.io.IOException;
import java.nio.file.Path;
/**
*
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
*/
public interface MemoryMappedFileFactory {
MemoryMappedFile create(Path path) throws IOException;
}
| mpl-2.0 |
lucemans/ShapeClient-SRC | net/minecraft/entity/ai/EntityAIMoveIndoors.java | 3231 | package net.minecraft.entity.ai;
import net.minecraft.entity.EntityCreature;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.village.Village;
import net.minecraft.village.VillageDoorInfo;
public class EntityAIMoveIndoors extends EntityAIBase
{
private final EntityCreature entityObj;
private VillageDoorInfo doorInfo;
private int insidePosX = -1;
private int insidePosZ = -1;
public EntityAIMoveIndoors(EntityCreature entityObjIn)
{
this.entityObj = entityObjIn;
this.setMutexBits(1);
}
/**
* Returns whether the EntityAIBase should begin execution.
*/
public boolean shouldExecute()
{
BlockPos blockpos = new BlockPos(this.entityObj);
if ((!this.entityObj.world.isDaytime() || this.entityObj.world.isRaining() && !this.entityObj.world.getBiome(blockpos).canRain()) && this.entityObj.world.provider.hasSkyLight())
{
if (this.entityObj.getRNG().nextInt(50) != 0)
{
return false;
}
else if (this.insidePosX != -1 && this.entityObj.getDistanceSq((double)this.insidePosX, this.entityObj.posY, (double)this.insidePosZ) < 4.0D)
{
return false;
}
else
{
Village village = this.entityObj.world.getVillageCollection().getNearestVillage(blockpos, 14);
if (village == null)
{
return false;
}
else
{
this.doorInfo = village.getDoorInfo(blockpos);
return this.doorInfo != null;
}
}
}
else
{
return false;
}
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
public boolean continueExecuting()
{
return !this.entityObj.getNavigator().noPath();
}
/**
* Execute a one shot task or start executing a continuous task
*/
public void startExecuting()
{
this.insidePosX = -1;
BlockPos blockpos = this.doorInfo.getInsideBlockPos();
int i = blockpos.getX();
int j = blockpos.getY();
int k = blockpos.getZ();
if (this.entityObj.getDistanceSq(blockpos) > 256.0D)
{
Vec3d vec3d = RandomPositionGenerator.findRandomTargetBlockTowards(this.entityObj, 14, 3, new Vec3d((double)i + 0.5D, (double)j, (double)k + 0.5D));
if (vec3d != null)
{
this.entityObj.getNavigator().tryMoveToXYZ(vec3d.xCoord, vec3d.yCoord, vec3d.zCoord, 1.0D);
}
}
else
{
this.entityObj.getNavigator().tryMoveToXYZ((double)i + 0.5D, (double)j, (double)k + 0.5D, 1.0D);
}
}
/**
* Resets the task
*/
public void resetTask()
{
this.insidePosX = this.doorInfo.getInsideBlockPos().getX();
this.insidePosZ = this.doorInfo.getInsideBlockPos().getZ();
this.doorInfo = null;
}
}
| mpl-2.0 |
seedstack/business | core/src/test/java/org/seedstack/business/fixtures/identity/GuiceIdentityGenerator.java | 678 | /*
* Copyright © 2013-2021, 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.business.fixtures.identity;
import javax.inject.Named;
import org.seedstack.business.domain.Entity;
import org.seedstack.business.util.SequenceGenerator;
@Named("guice")
public class GuiceIdentityGenerator implements SequenceGenerator {
@Override
public <E extends Entity<Long>> Long generate(Class<E> entityClass) {
return (long) Math.random();
}
}
| mpl-2.0 |
Appverse/appverse-server | framework/modules/backend/core/enterprise-converters/src/main/java/org/appverse/web/framework/backend/core/enterprise/converters/AbstractDozerB2IBeanConverter.java | 10846 | /*
Copyright (c) 2012 GFT Appverse, S.L., Sociedad Unipersonal.
This Source Code Form is subject to the terms of the Appverse Public License
Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this
file, You can obtain one at http://www.appverse.mobi/licenses/apl_v2.0.pdf. [^]
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the conditions of the AppVerse Public License v2.0
are met.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.appverse.web.framework.backend.core.enterprise.converters;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.appverse.web.framework.backend.core.beans.AbstractBusinessBean;
import org.appverse.web.framework.backend.core.beans.AbstractIntegrationBean;
import org.dozer.Mapper;
import org.dozer.spring.DozerBeanMapperFactoryBean;
public abstract class AbstractDozerB2IBeanConverter<BusinessBean extends AbstractBusinessBean, IntegrationBean extends AbstractIntegrationBean>
implements IB2IBeanConverter<BusinessBean, IntegrationBean> {
private Class<IntegrationBean> integrationBeanClass;
private Class<BusinessBean> businessBeanClass;
private String SCOPE_WITHOUT_DEPENDENCIES = "default-scope-without-dependencies";
private String SCOPE_COMPLETE = "default-scope-complete";
private String SCOPE_CUSTOM = "default-scope-custom";
@Resource
protected DozerBeanMapperFactoryBean dozerBeanMapperFactoryBean;
public AbstractDozerB2IBeanConverter() {
}
@Override
public IntegrationBean convert(BusinessBean bean) throws Exception {
return convert(bean, ConversionType.Complete);
}
@Override
public IntegrationBean convert(BusinessBean businessBean,
ConversionType conversionType) throws Exception {
return convert(businessBean, getScope(conversionType));
}
@Override
public IntegrationBean convert(BusinessBean businessBean,
String scope) throws Exception {
return ((Mapper) dozerBeanMapperFactoryBean.getObject()).map(
businessBean, integrationBeanClass, scope);
}
@Override
public void convert(final BusinessBean businessBean,
IntegrationBean integrationBean) throws Exception {
convert(businessBean, integrationBean, ConversionType.Complete);
}
@Override
public void convert(final BusinessBean businessBean,
IntegrationBean integrationBean, ConversionType conversionType)
throws Exception {
convert(businessBean, integrationBean, getScope(conversionType));
}
@Override
public void convert(final BusinessBean businessBean,
IntegrationBean integrationBean, String scope)
throws Exception{
((Mapper) dozerBeanMapperFactoryBean.getObject()).map(businessBean,
integrationBean, scope);
}
@Override
public BusinessBean convert(IntegrationBean bean) throws Exception {
return convert(bean, ConversionType.Complete);
}
@Override
public void convert(final IntegrationBean integrationBean,
BusinessBean businessBean) throws Exception {
convert(integrationBean, businessBean, ConversionType.Complete);
}
@Override
public void convert(final IntegrationBean integrationBean,
BusinessBean businessBean, ConversionType conversionType)
throws Exception {
convert(integrationBean, businessBean, getScope(conversionType));
}
@Override
public void convert(final IntegrationBean integrationBean,
BusinessBean businessBean, String scope)
throws Exception {
((Mapper) dozerBeanMapperFactoryBean.getObject()).map(integrationBean,
businessBean, scope);
}
@Override
public BusinessBean convert(IntegrationBean integrationBean,
ConversionType conversionType) throws Exception {
return convert(integrationBean, getScope(conversionType));
}
@Override
public BusinessBean convert(IntegrationBean integrationBean,
String scope) throws Exception {
return ((Mapper) dozerBeanMapperFactoryBean.getObject()).map(
integrationBean, businessBeanClass, scope);
}
@Override
public List<IntegrationBean> convertBusinessList(
List<BusinessBean> businessBeans) throws Exception {
List<IntegrationBean> integrationBeans = new ArrayList<IntegrationBean>();
for (BusinessBean businessBean : businessBeans) {
IntegrationBean integrationBean = convert(businessBean,
ConversionType.Complete);
integrationBeans.add(integrationBean);
}
return integrationBeans;
}
@Override
public List<IntegrationBean> convertBusinessList(
List<BusinessBean> businessBeans, ConversionType conversionType)
throws Exception {
return convertBusinessList(businessBeans, getScope(conversionType));
}
@Override
public List<IntegrationBean> convertBusinessList(
List<BusinessBean> businessBeans, String scope)
throws Exception {
List<IntegrationBean> integrationBeans = new ArrayList<IntegrationBean>();
for (BusinessBean businessBean : businessBeans) {
IntegrationBean integrationBean = ((Mapper) dozerBeanMapperFactoryBean
.getObject()).map(businessBean, integrationBeanClass,
scope);
integrationBeans.add(integrationBean);
}
return integrationBeans;
}
@Override
public void convertBusinessList(final List<BusinessBean> businessBeans,
List<IntegrationBean> integrationBeans) throws Exception {
if (businessBeans.size() != integrationBeans.size()) {
throw new ListDiffersSizeException();
}
for (int i = 0; i < businessBeans.size(); i++) {
convert(businessBeans.get(i), integrationBeans.get(i),
ConversionType.Complete);
}
}
@Override
public void convertBusinessList(final List<BusinessBean> businessBeans,
List<IntegrationBean> integrationBeans,
ConversionType conversionType) throws Exception {
convertBusinessList(businessBeans, integrationBeans, getScope(conversionType));
}
@Override
public void convertBusinessList(final List<BusinessBean> businessBeans,
List<IntegrationBean> integrationBeans,
String scope) throws Exception {
if (businessBeans.size() != integrationBeans.size()) {
throw new ListDiffersSizeException();
}
for (int i = 0; i < businessBeans.size(); i++) {
((Mapper) dozerBeanMapperFactoryBean.getObject()).map(
businessBeans.get(i), integrationBeans.get(i),
scope);
}
}
@Override
public List<BusinessBean> convertIntegrationList(
List<IntegrationBean> integrationBeans) throws Exception {
List<BusinessBean> businessBeans = new ArrayList<BusinessBean>();
for (IntegrationBean integrationBean : integrationBeans) {
BusinessBean businessBean = convert(integrationBean,
ConversionType.Complete);
businessBeans.add(businessBean);
}
return businessBeans;
}
@Override
public List<BusinessBean> convertIntegrationList(
List<IntegrationBean> integrationBeans,
ConversionType conversionType) throws Exception {
return convertIntegrationList(integrationBeans, getScope(conversionType));
}
@Override
public List<BusinessBean> convertIntegrationList(
List<IntegrationBean> integrationBeans,
String scope) throws Exception {
List<BusinessBean> businessBeans = new ArrayList<BusinessBean>();
for (IntegrationBean integrationBean : integrationBeans) {
BusinessBean businessBean = ((Mapper) dozerBeanMapperFactoryBean
.getObject()).map(integrationBean, businessBeanClass,
scope);
businessBeans.add(businessBean);
}
return businessBeans;
}
@Override
public void convertIntegrationList(
final List<IntegrationBean> integrationBeans,
List<BusinessBean> businessBeans) throws Exception {
if (integrationBeans.size() != businessBeans.size()) {
throw new ListDiffersSizeException();
}
for (int i = 0; i < integrationBeans.size(); i++) {
convert(integrationBeans.get(i), businessBeans.get(i),
ConversionType.Complete);
}
}
@Override
public void convertIntegrationList(
final List<IntegrationBean> integrationBeans,
List<BusinessBean> businessBeans, ConversionType conversionType)
throws Exception {
convertIntegrationList(integrationBeans, businessBeans, getScope(conversionType));
}
@Override
public void convertIntegrationList(
final List<IntegrationBean> integrationBeans,
List<BusinessBean> businessBeans, String scope)
throws Exception {
if (integrationBeans.size() != businessBeans.size()) {
throw new ListDiffersSizeException();
}
for (int i = 0; i < integrationBeans.size(); i++) {
((Mapper) dozerBeanMapperFactoryBean.getObject()).map(
integrationBeans.get(i), businessBeans.get(i),
scope);
}
}
@Override
public String getScope(ConversionType conversionType) {
String scope = null;
if (conversionType == ConversionType.WithoutDependencies) {
scope = SCOPE_WITHOUT_DEPENDENCIES;
} else if (conversionType == ConversionType.Custom) {
scope = SCOPE_CUSTOM;
} else {
scope = SCOPE_COMPLETE;
}
return scope;
}
public void setBeanClasses(Class<BusinessBean> businessBeanClass,
Class<IntegrationBean> integrationBeanClass) {
this.integrationBeanClass = integrationBeanClass;
this.businessBeanClass = businessBeanClass;
}
@Override
public void setScopes(String... scopes) {
if (scopes.length > 0) {
this.SCOPE_COMPLETE = scopes[0];
}
if (scopes.length > 1) {
this.SCOPE_WITHOUT_DEPENDENCIES = scopes[1];
}
if (scopes.length > 2) {
this.SCOPE_CUSTOM = scopes[2];
}
}
}
| mpl-2.0 |
echocat/jomon | resources/src/main/java/org/echocat/jomon/resources/UriEnabledResource.java | 707 | /*****************************************************************************************
* *** BEGIN LICENSE BLOCK *****
*
* Version: MPL 2.0
*
* echocat Jomon, Copyright (c) 2012-2013 echocat
*
* 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/.
*
* *** END LICENSE BLOCK *****
****************************************************************************************/
package org.echocat.jomon.resources;
import javax.annotation.Nonnull;
public interface UriEnabledResource extends Resource {
@Nonnull
public String getUri();
}
| mpl-2.0 |
GreenDelta/olca-converter | src/main/java/org/openlca/olcatdb/ecospold2/ES2ChildDataset.java | 386 | package org.openlca.olcatdb.ecospold2;
import org.openlca.olcatdb.parsing.Context;
/**
* @Element childActivityDataset
* @ContentModel (activityDescription, flowData, modellingAndValidation,
* administrativeInformation, namespace:uri="##other")
*/
@Context(name = "childActivityDataset", parentName = "ecoSpold")
public class ES2ChildDataset extends ES2Dataset {
}
| mpl-2.0 |
jmmaloney4/hs2 | src/main/java/hs/minion/RaidLeader.java | 870 | package hs.minion;
import hs.CardClass;
import hs.CardSet;
public class RaidLeader extends Minion {
static final String Name = "Raid Leader";
static final int Cost = 3;
static final CardClass Class = CardClass.NEUTRAL;
static final String Text = "Your other minions have +1 Attack.";
static final MinionRace Race = MinionRace.NEUTRAL;
static final int Attack = 2;
static final int Health = 2;
static CardSet Set = CardSet.BASIC;
@Override
public String getName() {
return Name;
}
@Override
public int getNormalCost() {
return Cost;
}
@Override
public String getText() {
return Text;
}
@Override
public CardClass getCardClass() {
return Class;
}
@Override
public int getNormalHealth() {
return Health;
}
@Override
public int getNormalAttack() {
return Attack;
}
@Override
public CardSet getCardSet() {
return Set;
}
}
| mpl-2.0 |
powsybl/powsybl-core | iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/GeneratorAdderImpl.java | 4274 | /**
* Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium)
* 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 com.powsybl.iidm.network.impl;
import com.powsybl.iidm.network.*;
/**
*
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
*/
class GeneratorAdderImpl extends AbstractInjectionAdder<GeneratorAdderImpl> implements GeneratorAdder {
private final VoltageLevelExt voltageLevel;
private EnergySource energySource = EnergySource.OTHER;
private double minP = Double.NaN;
private double maxP = Double.NaN;
private TerminalExt regulatingTerminal;
private Boolean voltageRegulatorOn;
private double targetP = Double.NaN;
private double targetQ = Double.NaN;
private double targetV = Double.NaN;
private double ratedS = Double.NaN;
GeneratorAdderImpl(VoltageLevelExt voltageLevel) {
this.voltageLevel = voltageLevel;
}
@Override
protected NetworkImpl getNetwork() {
return voltageLevel.getNetwork();
}
@Override
protected String getTypeDescription() {
return "Generator";
}
@Override
public GeneratorAdderImpl setEnergySource(EnergySource energySource) {
this.energySource = energySource;
return this;
}
@Override
public GeneratorAdderImpl setMaxP(double maxP) {
this.maxP = maxP;
return this;
}
@Override
public GeneratorAdderImpl setMinP(double minP) {
this.minP = minP;
return this;
}
@Override
public GeneratorAdder setVoltageRegulatorOn(boolean voltageRegulatorOn) {
this.voltageRegulatorOn = voltageRegulatorOn;
return this;
}
@Override
public GeneratorAdder setRegulatingTerminal(Terminal regulatingTerminal) {
this.regulatingTerminal = (TerminalExt) regulatingTerminal;
return this;
}
@Override
public GeneratorAdderImpl setTargetP(double targetP) {
this.targetP = targetP;
return this;
}
@Override
public GeneratorAdderImpl setTargetQ(double targetQ) {
this.targetQ = targetQ;
return this;
}
@Override
public GeneratorAdderImpl setTargetV(double targetV) {
this.targetV = targetV;
return this;
}
@Override
public GeneratorAdder setRatedS(double ratedS) {
this.ratedS = ratedS;
return this;
}
@Override
public GeneratorImpl add() {
NetworkImpl network = getNetwork();
if (network.getMinValidationLevel() == ValidationLevel.EQUIPMENT && voltageRegulatorOn == null) {
voltageRegulatorOn = false;
}
String id = checkAndGetUniqueId();
TerminalExt terminal = checkAndGetTerminal();
ValidationUtil.checkMinP(this, minP);
ValidationUtil.checkMaxP(this, maxP);
ValidationUtil.checkActivePowerLimits(this, minP, maxP);
ValidationUtil.checkRegulatingTerminal(this, regulatingTerminal, network);
network.setValidationLevelIfGreaterThan(ValidationUtil.checkActivePowerSetpoint(this, targetP, network.getMinValidationLevel()));
network.setValidationLevelIfGreaterThan(ValidationUtil.checkVoltageControl(this, voltageRegulatorOn, targetV, targetQ, network.getMinValidationLevel()));
ValidationUtil.checkActivePowerLimits(this, minP, maxP);
ValidationUtil.checkRatedS(this, ratedS);
GeneratorImpl generator
= new GeneratorImpl(network.getRef(),
id, getName(), isFictitious(), energySource,
minP, maxP,
voltageRegulatorOn, regulatingTerminal != null ? regulatingTerminal : terminal,
targetP, targetQ, targetV,
ratedS);
generator.addTerminal(terminal);
voltageLevel.attach(terminal, false);
network.getIndex().checkAndAdd(generator);
network.getListeners().notifyCreation(generator);
return generator;
}
}
| mpl-2.0 |
Burning-Man-Earth/iBurn-Android | iBurn/src/main/java/com/gaiagps/iburn/PrefsHelper.java | 2742 | package com.gaiagps.iburn;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by davidbrodsky on 7/1/15.
*/
public class PrefsHelper {
private static final String SHOWED_WELCOME = "welcomed_2018"; // boolean
private static final String POPULATED_DB_VERSION = "db_populated_ver"; // long
private static final String VALID_UNLOCK_CODE = "unlocked_2018"; // boolean
private static final String SCHEDULED_UPDATE = "sched_update"; // boolean
private static final String DEFAULT_RESOURCE_VERSION = "resver"; // long
private static final String RESOURCE_VERSION_PREFIX = "res-"; // long
private static final String SHARED_PREFS_NAME = PrefsHelper.class.getSimpleName();
private SharedPreferences sharedPrefs;
private SharedPreferences.Editor editor;
public PrefsHelper(Context context) {
sharedPrefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
editor = sharedPrefs.edit();
}
/**
* @return whether a valid unlock code has been presented for this year
*/
public boolean enteredValidUnlockCode() {
return sharedPrefs.getBoolean(VALID_UNLOCK_CODE, false);
}
public void setEnteredValidUnlockCode(boolean didEnter) {
editor.putBoolean(VALID_UNLOCK_CODE, didEnter).apply();
}
public boolean didShowWelcome() {
return sharedPrefs.getBoolean(SHOWED_WELCOME, false);
}
public void setDidShowWelcome(boolean didShow) {
editor.putBoolean(SHOWED_WELCOME, didShow).commit();
}
public void setDatabaseVersion(long version) {
editor.putLong(POPULATED_DB_VERSION, version).commit();
}
public long getDatabaseVersion() {
return sharedPrefs.getLong(POPULATED_DB_VERSION, 0);
}
/**
* @return whether the application successfully registered a {@link com.gaiagps.iburn.service.DataUpdateService} task
*/
public boolean didScheduleUpdate() {
return sharedPrefs.getBoolean(SCHEDULED_UPDATE, false);
}
public void setDidScheduleUpdate(boolean didScheduleUpdate) {
editor.putBoolean(SCHEDULED_UPDATE, didScheduleUpdate).apply();
}
public void setBaseResourcesVersion(long version) {
editor.putLong(DEFAULT_RESOURCE_VERSION, version).commit();
}
public long getResourceVersion(String resourceName) {
return sharedPrefs.getLong(RESOURCE_VERSION_PREFIX + resourceName, sharedPrefs.getLong(DEFAULT_RESOURCE_VERSION, 0));
}
public void setResourceVersion(String resourceName, long resourceVersion) {
editor.putLong(RESOURCE_VERSION_PREFIX + resourceName, resourceVersion).apply();
}
}
| mpl-2.0 |
sensiasoft/lib-ows | ogc-services-sps/src/main/java/org/vast/ows/sps/ConfirmRequestWriterV20.java | 2147 | /***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Original Code is the "OGC Service Framework".
The Initial Developer of the Original Code is Spotimage S.A.
Portions created by the Initial Developer are Copyright (C) 2007
the Initial Developer. All Rights Reserved.
Contributor(s):
Philippe Merigot <philippe.merigot@spotimage.fr>
******************************* END LICENSE BLOCK ***************************/
package org.vast.ows.sps;
import org.w3c.dom.Element;
import org.vast.ogc.OGCRegistry;
import org.vast.ows.OWSException;
import org.vast.ows.swe.SWERequestWriter;
import org.vast.xml.DOMHelper;
/**
* <p>
* Provides methods to generate an XML SPS Confirm
* request based on values contained in a ConfirmRequest object
* for version 2.0
* </p>
*
* @author Alexandre Robin <alexandre.robin@spotimage.fr>
* @date Feb, 258 2008
**/
public class ConfirmRequestWriterV20 extends SWERequestWriter<ConfirmRequest>
{
/**
* KVP Request
*/
@Override
public String buildURLQuery(ConfirmRequest request) throws OWSException
{
throw new SPSException(noKVP + "SPS 2.0 " + request.getOperation());
}
/**
* XML Request
*/
@Override
public Element buildXMLQuery(DOMHelper dom, ConfirmRequest request) throws OWSException
{
dom.addUserPrefix("sps", OGCRegistry.getNamespaceURI(SPSUtils.SPS, request.getVersion()));
// root element
Element rootElt = dom.createElement("sps:" + request.getOperation());
addCommonXML(dom, rootElt, request);
// taskID
dom.setElementValue(rootElt, "sps:task", request.getTaskID());
return rootElt;
}
} | mpl-2.0 |
clementf2b/FaceT | app/src/main/java/fyp/hkust/facet/util/CustomTypeFaceSpan.java | 1186 | package fyp.hkust.facet.util;
/**
* Created by ClementNg on 2/4/2017.
*/
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;
public class CustomTypeFaceSpan extends TypefaceSpan {
private final Typeface newType;
public CustomTypeFaceSpan(String family, Typeface type) {
super(family);
newType = type;
}
@Override
public void updateDrawState(TextPaint ds) {
applyCustomTypeFace(ds, newType);
}
@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, newType);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf) {
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null) {
oldStyle = 0;
} else {
oldStyle = old.getStyle();
}
int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}
if ((fake & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(tf);
}
} | mpl-2.0 |
seedstack/business | core/src/main/java/org/seedstack/business/domain/BaseRepository.java | 2661 | /*
* Copyright © 2013-2021, 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.business.domain;
import java.lang.reflect.Type;
import javax.inject.Inject;
import org.seedstack.business.internal.utils.BusinessUtils;
import org.seedstack.business.specification.dsl.SpecificationBuilder;
/**
* An helper base class that can be extended to create an <strong>implementation</strong> of a
* repository interface which, in turn, must extend {@link Repository}.
*
* <p> This class is mainly used as a common base for specialized technology-specific
* implementations. Client code will often extend these more specialized classes instead of this
* one. </p>
*
* @param <A> Type of the aggregate root.
* @param <I> Type of the aggregate root identifier.
* @see Repository
* @see org.seedstack.business.util.inmemory.BaseInMemoryRepository
*/
public abstract class BaseRepository<A extends AggregateRoot<I>, I> implements Repository<A, I> {
private static final int AGGREGATE_INDEX = 0;
private static final int KEY_INDEX = 1;
private final Class<A> aggregateRootClass;
private final Class<I> idClass;
@Inject
private SpecificationBuilder specificationBuilder;
/**
* Creates a base domain repository. Actual classes managed by the repository are determined by
* reflection.
*/
@SuppressWarnings("unchecked")
protected BaseRepository() {
Type[] generics = BusinessUtils.resolveGenerics(BaseRepository.class, getClass());
this.aggregateRootClass = (Class<A>) generics[AGGREGATE_INDEX];
this.idClass = (Class<I>) generics[KEY_INDEX];
}
/**
* Creates a base domain repository. Actual classes managed by the repository are specified
* explicitly. This can be used to create a dynamic implementation of a repository.
*
* @param aggregateRootClass the aggregate root class.
* @param idClass the aggregate root identifier class.
*/
protected BaseRepository(Class<A> aggregateRootClass, Class<I> idClass) {
this.aggregateRootClass = aggregateRootClass;
this.idClass = idClass;
}
@Override
public Class<A> getAggregateRootClass() {
return aggregateRootClass;
}
@Override
public Class<I> getIdentifierClass() {
return idClass;
}
@Override
public SpecificationBuilder getSpecificationBuilder() {
return specificationBuilder;
}
}
| mpl-2.0 |
Devexperts/QD | dxlib/src/main/java/com/devexperts/util/TypedMap.java | 1349 | /*
* !++
* QDS - Quick Data Signalling Library
* !-
* Copyright (C) 2002 - 2021 Devexperts LLC
* !-
* 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 com.devexperts.util;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Typed thread-safe key-value map where different values have different types and are distinguished
* by globally-unique keys that are instances of {@link TypedKey}.
*/
@SuppressWarnings({"unchecked"})
public class TypedMap {
private final Map<TypedKey<?>, Object> values = new IdentityHashMap<>();
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*/
public synchronized <T> T get(TypedKey<T> key) {
return (T) values.get(key);
}
/**
* Changes the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old value is replaced by the specified value.
*/
public synchronized <T> void set(TypedKey<T> key, T value) {
values.put(key, value);
}
@Override
public String toString() {
return values.toString();
}
}
| mpl-2.0 |
smithkm/gcs | src/com/trollworks/gcs/character/Page.java | 1978 | /*
* Copyright (c) 1998-2014 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* version 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/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as defined
* by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.character;
import com.trollworks.toolkit.ui.GraphicsUtilities;
import com.trollworks.toolkit.ui.UIUtilities;
import com.trollworks.toolkit.ui.print.PrintManager;
import com.trollworks.toolkit.utility.units.LengthUnits;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/** A printer page. */
public class Page extends JPanel {
private PageOwner mOwner;
/**
* Creates a new page.
*
* @param owner The page owner.
*/
public Page(PageOwner owner) {
super(new BorderLayout());
mOwner = owner;
setOpaque(true);
setBackground(Color.white);
PrintManager pageSettings = mOwner.getPageSettings();
Insets insets = mOwner.getPageAdornmentsInsets(this);
double[] size = pageSettings != null ? pageSettings.getPageSize(LengthUnits.POINTS) : new double[] { 8.5 * 72.0, 11.0 * 72.0 };
double[] margins = pageSettings != null ? pageSettings.getPageMargins(LengthUnits.POINTS) : new double[] { 36.0, 36.0, 36.0, 36.0 };
setBorder(new EmptyBorder(insets.top + (int) margins[0], insets.left + (int) margins[1], insets.bottom + (int) margins[2], insets.right + (int) margins[3]));
Dimension pageSize = new Dimension((int) size[0], (int) size[1]);
UIUtilities.setOnlySize(this, pageSize);
setSize(pageSize);
}
@Override
protected void paintComponent(Graphics gc) {
super.paintComponent(GraphicsUtilities.prepare(gc));
mOwner.drawPageAdornments(this, gc);
}
}
| mpl-2.0 |
os2indberetning/OS2_Android | app/src/androidTest/java/eindberetning/it_minds/dk/eindberetningmobil_android/views/UploadingViewTest.java | 1086 | package eindberetning.it_minds.dk.eindberetningmobil_android.views;
import android.widget.TextView;
import org.junit.Test;
import eindberetning.it_minds.dk.eindberetningmobil_android.BaseTest;
import eindberetning.it_minds.dk.eindberetningmobil_android.data.StaticData;
import it_minds.dk.eindberetningmobil_android.R;
import it_minds.dk.eindberetningmobil_android.views.UploadingView;
public class UploadingViewTest extends BaseTest<UploadingView> {
@Override
public void runBeforeGetActivity() {
getSettings().setProfile(StaticData.createSimpleProfile());
}
public UploadingViewTest() {
super(UploadingView.class);
}
@Test
public void testLayout() {
solo.waitForView(R.id.uploading_view_image);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
getActivity().updateStatusText("asd-swag");
}
});
TextView view = (TextView) solo.getView(R.id.upload_view_status_text);
assertEquals(view.getText(), "asd-swag");
}
}
| mpl-2.0 |
etomica/etomica | etomica-core/src/main/java/etomica/data/history/HistoryComplete.java | 3360 | /* 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 etomica.data.history;
/**
* History that records a data from a simulation. When existing space
* is insufficient to hold new data, the array to hold the data is doubled
* in length.
*
* @author Andrew Schultz
*/
public class HistoryComplete implements History {
public HistoryComplete() {this(100);}
public HistoryComplete(int n) {
setHistoryLength(n);
reset();
doCollapseOnReset = true;
}
/**
* Sets the number of values kept in the history.
*/
public void setHistoryLength(int n) {
int originalLength = history.length;
if (n < cursor) {
throw new IllegalArgumentException("decreasing history length would clobber data");
}
if (n==originalLength) return;
double[] temp = new double[n];
System.arraycopy(xValues,0,temp,0,cursor);
xValues = temp;
for (int i = cursor; i<n; i++) {
xValues[i] = Double.NaN;
}
temp = new double[n];
System.arraycopy(history,0,temp,0,cursor);
history = temp;
for (int i = cursor; i<n; i++) {
history[i] = Double.NaN;
}
}
public int getHistoryLength() {
return history.length;
}
public int getSampleCount() {
return cursor;
}
/**
* Removes entire history, setting all values to NaN.
*/
public void reset() {
int nValues = getHistoryLength();
if (doCollapseOnReset && nValues > 100) {
xValues = new double[100];
history = new double[100];
}
for(int i=0; i<nValues; i++) {
xValues[i] = Double.NaN;
history[i] = Double.NaN;
}
cursor = 0;
}
public double[] getXValues() {
return xValues;
}
public boolean addValue(double x, double y) {
if (cursor == history.length) {
int newLength = history.length*2;
if (newLength == 0) {
newLength = 1;
}
setHistoryLength(newLength);
}
xValues[cursor] = x;
history[cursor] = y;
cursor++;
return true;
}
/**
* Returns an the history
*/
public double[] getHistory() {
return history;
}
/**
* Sets a flag that determines if the history is collapsed (to 100 data
* points) when reset is called. If the current history length is less
* than 100, the history length is unchanged.
*/
public void setCollapseOnReset(boolean flag) {
doCollapseOnReset = flag;
}
/**
* Returns true if the history is collapsed (to 100 data points) when reset
* is called. If the current history length is less than 100, the history
* length is unchanged.
*/
public boolean isCollapseOnReset() {
return doCollapseOnReset;
}
public boolean willDiscardNextData() {
return false;
}
private double[] history = new double[0];
private double[] xValues = new double[0];
private int cursor;
private boolean doCollapseOnReset;
}
| mpl-2.0 |
arian-22/AlgoritmosGeneticos-UTN | Ejercicio-03/src/tsp/Ciudad.java | 1265 | package tsp;
public class Ciudad {
private String nombre;
private int id;
private CiudadesDistancias[] distanciasC = new CiudadesDistancias[22];
private boolean visitado = false;
private boolean inicial = false;
Ciudad(int idd, String nom){
nombre = nom;
id = idd;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public CiudadesDistancias distanciasACiudades(int i) {
return distanciasC[i];
}
public CiudadesDistancias[] getDistancias() {
return distanciasC;
}
public void setDistancias(CiudadesDistancias[] distancias) {
this.distanciasC = distancias;
}
public boolean getVisitado() {
return visitado;
}
public void setVisitado(){
this.visitado = true;
}
public void setInicial(){
this.inicial = true;
}
public boolean getInicial() {
return inicial;
}
public int getDistancia(String cd){
int distancia = 0;
for (int i=0;i<22;i++){
if(distanciasC[i].getCiudadDestino().equals(cd)){
distancia=distanciasC[i].getDistancia();
}
}
return distancia;
}
}
| mpl-2.0 |
scauwe/Generic-File-Driver-for-IDM | shim/src/main/java/info/vancauwenberge/filedriver/filereader/csv/CSVFileReader.java | 7573 | /*******************************************************************************
* Copyright (c) 2007, 2018 Stefaan Van Cauwenberge
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Initial Developer of the Original Code is
* Stefaan Van Cauwenberge. Portions created by
* the Initial Developer are Copyright (C) 2007, 2018 by
* Stefaan Van Cauwenberge. All Rights Reserved.
*
* Contributor(s): none so far.
* Stefaan Van Cauwenberge: Initial API and implementation
*******************************************************************************/
package info.vancauwenberge.filedriver.filereader.csv;
import java.io.File;
import java.io.FileInputStream;
import java.io.Reader;
import java.util.Map;
import com.novell.nds.dirxml.driver.Trace;
import com.novell.nds.dirxml.driver.xds.Constraint;
import com.novell.nds.dirxml.driver.xds.DataType;
import com.novell.nds.dirxml.driver.xds.Parameter;
import com.novell.nds.dirxml.driver.xds.XDSParameterException;
import info.vancauwenberge.filedriver.api.AbstractStrategy;
import info.vancauwenberge.filedriver.api.IFileReadStrategy;
import info.vancauwenberge.filedriver.exception.ReadException;
import info.vancauwenberge.filedriver.filepublisher.IPublisher;
import info.vancauwenberge.filedriver.filereader.RecordQueue;
import info.vancauwenberge.filedriver.shim.driver.GenericFileDriverShim;
import info.vancauwenberge.filedriver.util.TraceLevel;
import info.vancauwenberge.filedriver.util.Util;
public class CSVFileReader extends AbstractStrategy implements IFileReadStrategy {
private boolean useHeaderNames;
private char seperator;
private String encoding;
private boolean hasHeader;
private boolean skipEmptyLines;
private Thread parsingThread;
private RecordQueue queue;
private String[] schema;
private Trace trace;
private CSVFileParser handler;
protected enum Parameters implements IStrategyParameters {
//@formatter:off
SKIP_EMPTY_LINES("csvReader_skipEmptyLines","true",DataType.BOOLEAN),
USE_HEADER_NAMES("csvReader_UseHeaderNames","true",DataType.BOOLEAN),
HAS_HEADER ("csvReader_hasHeader" ,"true",DataType.BOOLEAN),
FORCED_ENCODING ("csvReader_forcedEncoding",null ,DataType.STRING),
SEPERATOR ("csvReader_seperator" ,"," ,DataType.STRING);
//@formatter:on
private Parameters(final String name, final String defaultValue, final DataType dataType) {
this.name = name;
this.defaultValue = defaultValue;
this.dataType = dataType;
}
private final String name;
private final String defaultValue;
private final DataType dataType;
@Override
public String getParameterName() {
return name;
}
@Override
public String getDefaultValue() {
return defaultValue;
}
@Override
public DataType getDataType() {
return dataType;
}
@Override
public Constraint[] getConstraints() {
return null;
}
}
/*
* (non-Javadoc)
*
* @see
* info.vancauwenberge.filedriver.api.IFileReader#init(com.novell.nds.dirxml
* .driver.Trace, java.util.Map)
*/
@Override
public void init(final Trace trace, final Map<String, Parameter> driverParams, final IPublisher publisher)
throws XDSParameterException {
if (trace.getTraceLevel() > TraceLevel.TRACE) {
trace.trace("CSVFileReader.init() driverParams:" + driverParams);
}
this.trace = trace;
useHeaderNames = getBoolValueFor(Parameters.USE_HEADER_NAMES, driverParams);
// driverParams.get(TAG_USE_HEADER_NAMES).toBoolean().booleanValue();
encoding = getStringValueFor(Parameters.FORCED_ENCODING, driverParams);
// driverParams.get(TAG_FORCED_ENCODING).toString();
hasHeader = getBoolValueFor(Parameters.HAS_HEADER, driverParams);
// driverParams.get(TAG_HAS_HEADER).toBoolean().booleanValue();
skipEmptyLines = getBoolValueFor(Parameters.SKIP_EMPTY_LINES, driverParams);
// driverParams.get(TAG_SKIP_EMPTY_LINES).toBoolean().booleanValue();
if ("".equals(encoding)) {
encoding = Util.getSystemDefaultEncoding();
trace.trace("No encoding given. Using system default of " + encoding, TraceLevel.ERROR_WARN);
}
// Tabs and spaces in the driver config are removed by Designer, so we
// need to use a special 'encoding' for the tab character.
final String strSeperator = getStringValueFor(Parameters.SEPERATOR, driverParams);
// driverParams.get(TAG_SEPERATOR).toString();
if ("{tab}".equalsIgnoreCase(strSeperator)) {
seperator = '\t';
} else if ("{space}".equalsIgnoreCase(strSeperator)) {
seperator = ' ';
} else if ((strSeperator != null) && !"".equals(strSeperator)) {
seperator = strSeperator.charAt(0);// This is a required field, so
// we should have at least one
// character
} else {
throw new XDSParameterException("Invalid parameter value for seperator:" + strSeperator);
}
schema = GenericFileDriverShim.getSchemaAsArray(driverParams);
}
/*
* (non-Javadoc)
*
* @see
* info.vancauwenberge.filedriver.api.IFileReader#openFile(com.novell.nds.
* dirxml.driver.Trace, java.io.File)
*/
@Override
public void openFile(final File f) throws ReadException {
try {
// Start the parser that will parse this document
final FileInputStream fr = new FileInputStream(f);
final Reader reader = new UnicodeReader(fr, encoding);
handler = new CSVFileParser(seperator, schema, skipEmptyLines, hasHeader, useHeaderNames);
handler.resetParser();
queue = handler.getQueue();
parsingThread = new Thread() {
@Override
public void run() {
try {
handler.doParse(reader);
} catch (final Exception e) {
Util.printStackTrace(trace, e);
queue.setFinishedInError(e);
}
}
};
parsingThread.setDaemon(true);
parsingThread.setName("CSVParser");
parsingThread.start();
} catch (final Exception e1) {
trace.trace("Exception while handeling CSV document:" + e1.getMessage(), TraceLevel.ERROR_WARN);
throw new ReadException("Exception while handeling CSV document:" + e1.getMessage(), e1);
}
}
/*
* (non-Javadoc)
*
* @see
* info.vancauwenberge.filedriver.api.IFileReader#readRecord(com.novell.nds.
* dirxml.driver.Trace)
*/
@Override
public Map<String, String> readRecord() throws ReadException {
try {
return queue.getNextRecord();
} catch (final Exception e) {
throw new ReadException(e);
}
}
/*
* (non-Javadoc)
*
* @see info.vancauwenberge.filedriver.api.IFileReader#close()
*/
@Override
public void close() throws ReadException {
queue = null;
if (parsingThread.isAlive()) {
trace.trace("WARN: parsing thread is still alive...", TraceLevel.ERROR_WARN);
try {
parsingThread.join();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
// Thread is dead. Normal situation.
parsingThread = null;
handler = null;
}
@SuppressWarnings("unchecked")
@Override
public <E extends Enum<?> & IStrategyParameters> Class<E> getParametersEnum() {
return (Class<E>) Parameters.class;
}
@Override
public String[] getActualSchema() {
// The parsing is done in a seperate thread. We need to make sure that
// at least one record is read.
return handler.getCurrentSchema();
}
}
| mpl-2.0 |
splicemachine/spliceengine | mem_sql/src/main/java/com/splicemachine/derby/impl/sql/execute/MemGenericConstantActionFactory.java | 1384 | /*
* 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.derby.impl.sql.execute;
import com.splicemachine.db.catalog.UUID;
import com.splicemachine.db.iapi.sql.execute.ConstantAction;
/**
* @author Scott Fines
* Date: 1/13/16
*/
public class MemGenericConstantActionFactory extends SpliceGenericConstantActionFactory{
@Override
public ConstantAction getDropIndexConstantAction(String fullIndexName, String indexName, String tableName, String schemaName, UUID tableId, long tableConglomerateId, UUID dbId){
return new MemDropIndexConstantOperation(fullIndexName, indexName, tableName, schemaName, tableId, tableConglomerateId, dbId);
}
}
| agpl-3.0 |
RestComm/jss7 | management/shell-server-impl/src/main/java/org/restcomm/ss7/management/console/ShellServerMBean.java | 1338 | /*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.ss7.management.console;
/**
* @author sergey.povarnin
*/
public interface ShellServerMBean {
String getAddress();
void setAddress(String address);
int getPort();
void setPort(int port);
String getSecurityDomain();
void setSecurityDomain(String securityDomain);
int getQueueNumber();
}
| agpl-3.0 |
ging/isabel | components/vnc/navegador/isabel/argonauta/Argonauta.java | 3156 | /*
* ISABEL: A group collaboration tool for the Internet
* Copyright (C) 2011 Agora System S.A.
*
* This file is part of Isabel.
*
* Isabel is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Isabel 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
* Affero GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with Isabel. If not, see <http://www.gnu.org/licenses/>.
*/
package isabel.argonauta;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.awt.*;
import java.awt.event.*;
/**
* File browser.
*
* Select documents are open with xdg-open
*/
public class Argonauta {
JFileChooser fc;
/**
* main method.
*/
public static void main(String[] args) {
Argonauta demo = new Argonauta();
}
/**
* FileChooserDemo Constructor
*/
public Argonauta() {
fc = new JFileChooser();
fc.setDragEnabled(false);
// set the current directory:
// fc.setCurrentDirectory(swingFile);
// Add file filters:
javax.swing.filechooser.FileFilter filter;
filter = new FileNameExtensionFilter("Images", "jpg", "jpeg", "png",
"gif");
fc.addChoosableFileFilter(filter);
filter = new FileNameExtensionFilter("PDF", "PDF");
fc.addChoosableFileFilter(filter);
filter = new FileNameExtensionFilter("Office", "ppt", "pptx", "doc",
"docx");
fc.addChoosableFileFilter(filter);
fc.setAcceptAllFileFilterUsed(true);
// remove the approve/cancel buttons
fc.setControlButtonsAreShown(false);
// Actions & Listener:
Action openAction = createOpenAction();
Action dismissAction = createDismissAction();
fc.addActionListener(openAction);
// make custom controls
JPanel buttons = new JPanel();
buttons.add(new JButton(dismissAction));
buttons.add(new JButton(openAction));
// Main Window:
JFrame jf = new JFrame("File browser");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jf.getContentPane().add(fc, BorderLayout.CENTER);
jf.getContentPane().add(buttons, BorderLayout.SOUTH);
jf.pack();
jf.setVisible(true);
}
public Action createOpenAction() {
return new AbstractAction("Open") {
public void actionPerformed(ActionEvent e) {
if (!e.getActionCommand().equals(JFileChooser.CANCEL_SELECTION)
&& fc.getSelectedFile() != null) {
openDocument(fc.getSelectedFile().getPath());
}
}
};
}
public Action createDismissAction() {
return new AbstractAction("Dismiss") {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
}
private void openDocument(String name) {
try {
Runtime rt = Runtime.getRuntime();
String[] command = { "xdg-open", name };
rt.exec(command);
} catch (Exception e) {
System.err.println("I can not open this document: " + name);
}
}
}
| agpl-3.0 |
devmix/openjst | server/commons/webui-maven-plugin/src/test/java/org/openjst/server/commons/maven/CompileMojoTest.java | 1569 | /*
* 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.server.commons.maven;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
/**
* @author Sergey Grachev
*/
public final class CompileMojoTest extends AbstractMojoTest {
@Test(groups = "manual")
public void test() throws IOException, MojoFailureException, MojoExecutionException {
final File resourcesPath = makeTempResourcesDirectory();
try {
final CompileMojo mojo = new CompileMojo(new File(resourcesPath, "manifest.xml"));
mojo.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
FileUtils.deleteDirectory(resourcesPath);
}
}
}
| agpl-3.0 |
devmix/openjst | server/mobile/war/src/main/java/org/openjst/server/mobile/web/rest/Accounts.java | 1540 | /*
* 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.server.mobile.web.rest;
import org.openjst.server.commons.mq.IRestCrud;
import org.openjst.server.commons.mq.QueryListParams;
import org.openjst.server.commons.mq.results.QuerySingleResult;
import org.openjst.server.mobile.mq.model.AccountModel;
import org.openjst.server.mobile.mq.model.AccountSummaryModel;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
/**
* @author Sergey Grachev
*/
@Path("/accounts")
@Produces(MediaType.APPLICATION_JSON)
public interface Accounts extends IRestCrud<AccountModel, QueryListParams> {
@POST
@Path("/generateAccountAPIKey")
QuerySingleResult<String> generateAccountAPIKey(@FormParam("accountId") Long accountId);
@GET
@Path("/{id}/summary")
QuerySingleResult<AccountSummaryModel> getSummary(@PathParam("id") Long accountId);
}
| agpl-3.0 |
amapj/amapj | amapj/src/fr/amapj/model/engine/transaction/DbWrite.java | 868 | /*
* Copyright 2013-2018 Emmanuel BRUN (contact@amapj.fr)
*
* This file is part of AmapJ.
*
* AmapJ 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.
* AmapJ 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 AmapJ. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package fr.amapj.model.engine.transaction;
public @interface DbWrite
{
} | agpl-3.0 |
metreeca/metreeca | back/spec/src/main/java/com/metreeca/spec/codecs/ShapeCodec.java | 28505 | /*
* Copyright © 2013-2018 Metreeca srl. All rights reserved.
*
* This file is part of Metreeca.
*
* Metreeca 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.
*
* Metreeca 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 Metreeca. If not, see <http://www.gnu.org/licenses/>.
*/
package com.metreeca.spec.codecs;
import com.metreeca.jeep.rdf.Values;
import com.metreeca.spec.Shape;
import com.metreeca.spec.Shift;
import com.metreeca.spec.Spec;
import com.metreeca.spec.shapes.*;
import com.metreeca.spec.shifts.Count;
import com.metreeca.spec.shifts.Step;
import org.eclipse.rdf4j.model.*;
import org.eclipse.rdf4j.model.impl.LinkedHashModel;
import org.eclipse.rdf4j.model.util.RDFCollections;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.Rio;
import java.io.IOException;
import java.io.StringReader;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static com.metreeca.jeep.rdf.Cell.Missing;
import static com.metreeca.jeep.rdf.Values.bnode;
import static com.metreeca.jeep.rdf.Values.integer;
import static com.metreeca.jeep.rdf.Values.statement;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
public final class ShapeCodec {
private static final RDFFormat Format=RDFFormat.NTRIPLES;
public Resource encode(final Shape shape, final Collection<Statement> model) {
if ( shape == null ) {
throw new IllegalArgumentException("null shape");
}
if ( model == null ) {
throw new IllegalArgumentException("null model");
}
return shape(shape, model);
}
public Shape decode(final Resource root, final Collection<Statement> model) {
if ( root == null ) {
throw new IllegalArgumentException("null root");
}
if ( model == null ) {
throw new IllegalArgumentException("null model");
}
return shape(root, model);
}
public Shape decode(final String spec) { // !!! review/remove
if ( spec == null ) {
throw new IllegalArgumentException("null spec");
}
try {
final Model model=Rio.parse(new StringReader(spec), "", Format);
final Resource root=model.subjects().stream()
.filter(subject -> !model.contains(null, null, subject))
.findFirst().orElseThrow(Missing);
return decode(root, model);
} catch ( final IOException e ) {
throw new UncheckedIOException(e);
}
}
//// Shapes ////////////////////////////////////////////////////////////////////////////////////////////////////////
private Resource shape(final Shape shape, final Collection<Statement> model) {
return shape.accept(new Shape.Probe<Resource>() {
@Override public Resource visit(final Datatype datatype) { return datatype(datatype, model); }
@Override public Resource visit(final Clazz clazz) { return clazz(clazz, model); }
@Override public Resource visit(final MinExclusive minExclusive) { return minExclusive(minExclusive, model); }
@Override public Resource visit(final MaxExclusive maxExclusive) { return maxExclusive(maxExclusive, model); }
@Override public Resource visit(final MinInclusive minInclusive) { return minInclusive(minInclusive, model); }
@Override public Resource visit(final MaxInclusive maxInclusive) { return maxInclusive(maxInclusive, model); }
@Override public Resource visit(final Pattern pattern) { return pattern(pattern, model); }
@Override public Resource visit(final Like like) { return like(like, model); }
@Override public Resource visit(final MinLength minLength) { return minLength(minLength, model); }
@Override public Resource visit(final MaxLength maxLength) { return maxLength(maxLength, model); }
@Override public Resource visit(final MinCount minCount) {
return minCount(minCount, model);
}
@Override public Resource visit(final MaxCount maxCount) { return maxCount(maxCount, model); }
@Override public Resource visit(final In in) { return in(in, model); }
@Override public Resource visit(final All all) { return all(all, model); }
@Override public Resource visit(final Any any) { return any(any, model); }
@Override public Resource visit(final Trait trait) {
return trait(trait, model);
}
@Override public Resource visit(final Virtual virtual) { return virtual(virtual, model); }
@Override public Resource visit(final And and) {
return and(and, model);
}
@Override public Resource visit(final Or or) { return or(or, model); }
@Override public Resource visit(final Test test) { return test(test, model); }
@Override public Resource visit(final When when) { return when(when, model); }
@Override public Resource visit(final Alias alias) {
return alias(alias, model);
}
@Override public Resource visit(final Label label) { return label(label, model); }
@Override public Resource visit(final Notes notes) { return notes(notes, model); }
@Override public Resource visit(final Placeholder placeholder) { return placeholder(placeholder, model); }
@Override public Resource visit(final Default dflt) { return dflt(dflt, model); }
@Override public Resource visit(final Hint hint) { return hint(hint, model); }
@Override public Resource visit(final Group group) {
return group(group, model);
}
@Override protected Resource fallback(final Shape shape) {
throw new UnsupportedOperationException("unsupported shape ["+shape+"]");
}
});
}
private Shape shape(final Resource root, final Collection<Statement> model) {
final Set<Value> types=types(root, model);
return types.contains(Spec.Datatype) ? datatype(root, model)
: types.contains(Spec.Class) ? clazz(root, model)
: types.contains(Spec.MinExclusive) ? minExclusive(root, model)
: types.contains(Spec.MaxExclusive) ? maxExclusive(root, model)
: types.contains(Spec.MinInclusive) ? minInclusive(root, model)
: types.contains(Spec.MaxInclusive) ? maxInclusive(root, model)
: types.contains(Spec.Pattern) ? pattern(root, model)
: types.contains(Spec.Like) ? like(root, model)
: types.contains(Spec.MinLength) ? minLength(root, model)
: types.contains(Spec.MaxLength) ? maxLength(root, model)
: types.contains(Spec.MinCount) ? minCount(root, model)
: types.contains(Spec.MaxCount) ? maxCount(root, model)
: types.contains(Spec.In) ? in(root, model)
: types.contains(Spec.All) ? all(root, model)
: types.contains(Spec.Any) ? any(root, model)
: types.contains(Spec.required) ? required(root, model)
: types.contains(Spec.optional) ? optional(root, model)
: types.contains(Spec.repeatable) ? repeatable(root, model)
: types.contains(Spec.multiple) ? multiple(root, model)
: types.contains(Spec.only) ? only(root, model)
: types.contains(Spec.Trait) ? trait(root, model)
: types.contains(Spec.Virtual) ? virtual(root, model)
: types.contains(Spec.And) ? and(root, model)
: types.contains(Spec.Or) ? or(root, model)
: types.contains(Spec.Test) ? test(root, model)
: types.contains(Spec.When) ? when(root, model)
: types.contains(Spec.Alias) ? alias(root, model)
: types.contains(Spec.Label) ? label(root, model)
: types.contains(Spec.Notes) ? notes(root, model)
: types.contains(Spec.Placeholder) ? placeholder(root, model)
: types.contains(Spec.Default) ? dflt(root, model)
: types.contains(Spec.Hint) ? hint(root, model)
: types.contains(Spec.Group) ? group(root, model)
: types.contains(Spec.create) ? create(root, model)
: types.contains(Spec.relate) ? relate(root, model)
: types.contains(Spec.update) ? update(root, model)
: types.contains(Spec.delete) ? delete(root, model)
: types.contains(Spec.client) ? client(root, model)
: types.contains(Spec.server) ? server(root, model)
: types.contains(Spec.digest) ? digest(root, model)
: types.contains(Spec.detail) ? detail(root, model)
: types.contains(Spec.verify) ? verify(root, model)
: types.contains(Spec.filter) ? filter(root, model)
: error("unknown shape type "+types);
}
private Resource datatype(final Datatype datatype, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Datatype));
model.add(statement(node, Spec.iri, datatype.getIRI()));
return node;
}
private Shape datatype(final Resource root, final Collection<Statement> model) {
return Datatype.datatype(iri(root, Spec.iri, model));
}
private Resource clazz(final Clazz clazz, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Class));
model.add(statement(node, Spec.iri, clazz.getIRI()));
return node;
}
private Shape clazz(final Resource root, final Collection<Statement> model) {
return Clazz.clazz(iri(root, Spec.iri, model));
}
private Resource minExclusive(final MinExclusive minExclusive, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.MinExclusive));
model.add(statement(node, Spec.value, minExclusive.getValue()));
return node;
}
private Shape minExclusive(final Resource root, final Collection<Statement> model) {
return MinExclusive.minExclusive(value(root, Spec.value, model));
}
private Resource maxExclusive(final MaxExclusive maxExclusive, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.MaxExclusive));
model.add(statement(node, Spec.value, maxExclusive.getValue()));
return node;
}
private Shape maxExclusive(final Resource root, final Collection<Statement> model) {
return MaxExclusive.maxExclusive(value(root, Spec.value, model));
}
private Resource minInclusive(final MinInclusive minInclusive, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.MinInclusive));
model.add(statement(node, Spec.value, minInclusive.getValue()));
return node;
}
private Shape minInclusive(final Resource root, final Collection<Statement> model) {
return MinInclusive.minInclusive(value(root, Spec.value, model));
}
private Resource maxInclusive(final MaxInclusive maxInclusive, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.MaxInclusive));
model.add(statement(node, Spec.value, maxInclusive.getValue()));
return node;
}
private Shape maxInclusive(final Resource root, final Collection<Statement> model) {
return MaxInclusive.maxInclusive(value(root, Spec.value, model));
}
private Resource pattern(final Pattern pattern, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Pattern));
model.add(statement(node, Spec.text, Values.literal(pattern.getText())));
model.add(statement(node, Spec.flags, Values.literal(pattern.getFlags())));
return node;
}
private Shape pattern(final Resource root, final Collection<Statement> model) {
return Pattern.pattern(
literal(root, Spec.text, model).stringValue(),
literal(root, Spec.flags, model).stringValue());
}
private Resource like(final Like like, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Like));
model.add(statement(node, Spec.text, Values.literal(like.getText())));
return node;
}
private Shape like(final Resource root, final Collection<Statement> model) {
return Like.like(literal(root, Spec.text, model).stringValue());
}
private Resource minLength(final MinLength minLength, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.MinLength));
model.add(statement(node, Spec.limit, Values.literal(integer(minLength.getLimit()))));
return node;
}
private Shape minLength(final Resource root, final Collection<Statement> model) {
return MinLength.minLength(literal(root, Spec.limit, model).integerValue().intValue());
}
private Resource maxLength(final MaxLength maxLength, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.MaxLength));
model.add(statement(node, Spec.limit, Values.literal(integer(maxLength.getLimit()))));
return node;
}
private Shape maxLength(final Resource root, final Collection<Statement> model) {
return MaxLength.maxLength(literal(root, Spec.limit, model).integerValue().intValue());
}
private Resource minCount(final MinCount minCount, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.MinCount));
model.add(statement(node, Spec.limit, Values.literal(integer(minCount.getLimit()))));
return node;
}
private Shape minCount(final Resource root, final Collection<Statement> model) {
return MinCount.minCount(literal(root, Spec.limit, model).integerValue().intValue());
}
private Resource maxCount(final MaxCount maxCount, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.MaxCount));
model.add(statement(node, Spec.limit, Values.literal(integer(maxCount.getLimit()))));
return node;
}
private Shape maxCount(final Resource root, final Collection<Statement> model) {
return MaxCount.maxCount(literal(root, Spec.limit, model).integerValue().intValue());
}
private Resource in(final In in, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.In));
model.add(statement(node, Spec.values, values(in.getValues(), model)));
return node;
}
private Shape in(final Resource root, final Collection<Statement> model) {
return In.in(values(resource(root, Spec.values, model), model));
}
private Resource all(final All all, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.All));
model.add(statement(node, Spec.values, values(all.getValues(), model)));
return node;
}
private Shape all(final Resource root, final Collection<Statement> model) {
return All.all(values(resource(root, Spec.values, model), model));
}
private Resource any(final Any any, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Any));
model.add(statement(node, Spec.values, values(any.getValues(), model)));
return node;
}
private Shape any(final Resource root, final Collection<Statement> model) {
return Any.any(values(resource(root, Spec.values, model), model));
}
private Shape required(final Resource root, final Collection<Statement> model) {
return Shape.required();
}
private Shape optional(final Resource root, final Collection<Statement> model) {
return Shape.optional();
}
private Shape repeatable(final Resource root, final Collection<Statement> model) {
return Shape.repeatable();
}
private Shape multiple(final Resource root, final Collection<Statement> model) {
return Shape.multiple();
}
private Shape only(final Resource root, final Collection<Statement> model) {
return Shape.only(values(resource(root, Spec.values, model), model));
}
private Resource trait(final Trait trait, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Trait));
model.add(statement(node, Spec.step, step(trait.getStep(), model)));
model.add(statement(node, Spec.shape, shape(trait.getShape(), model)));
return node;
}
private Trait trait(final Resource root, final Collection<Statement> model) {
return Trait.trait(
step(resource(root, Spec.step, model), model),
shape(resource(root, Spec.shape, model), model)
);
}
private Resource virtual(final Virtual virtual, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Virtual));
model.add(statement(node, Spec.trait, shape(virtual.getTrait(), model)));
model.add(statement(node, Spec.shift, shift(virtual.getShift(), model)));
return node;
}
private Shape virtual(final Resource root, final Collection<Statement> model) {
return Virtual.virtual(
trait(resource(root, Spec.trait, model), model),
shift(resource(root, Spec.shift, model), model)
);
}
private Resource and(final And and, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.And));
model.add(statement(node, Spec.shapes, shapes(and.getShapes(), model)));
return node;
}
private Shape and(final Resource root, final Collection<Statement> model) {
final Resource shapes=resource(root, Spec.shapes, model);
return shapes.equals(RDF.NIL) ? And.and() : And.and(shapes(shapes, model));
}
private Resource or(final Or or, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Or));
model.add(statement(node, Spec.shapes, shapes(or.getShapes(), model)));
final Collection<Shape> shapes=or.getShapes();
return node;
}
private Shape or(final Resource root, final Collection<Statement> model) {
final Resource shapes=resource(root, Spec.shapes, model);
return shapes.equals(RDF.NIL) ? Or.or() : Or.or(shapes(shapes, model));
}
private Resource test(final Test test, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Test));
model.add(statement(node, Spec.test, shape(test.getTest(), model)));
model.add(statement(node, Spec.pass, shape(test.getPass(), model)));
model.add(statement(node, Spec.fail, shape(test.getFail(), model)));
return node;
}
private Shape test(final Resource root, final Collection<Statement> model) {
return Test.test(
shape(resource(root, Spec.test, model), model),
shape(resource(root, Spec.pass, model), model),
shape(resource(root, Spec.fail, model), model)
);
}
private Resource when(final When when, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.When));
model.add(statement(node, Spec.iri, when.getIRI()));
model.add(statement(node, Spec.values, values(when.getValues(), model)));
return node;
}
private Shape when(final Resource root, final Collection<Statement> model) {
return When.when(
iri(root, Spec.iri, model),
values(resource(root, Spec.values, model), model)
);
}
private Resource alias(final Alias alias, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Alias));
model.add(statement(node, Spec.text, Values.literal(alias.getText())));
return node;
}
private Shape alias(final Resource root, final Collection<Statement> model) {
return Alias.alias(literal(root, Spec.text, model).stringValue());
}
private Resource label(final Label label, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Label));
model.add(statement(node, Spec.text, Values.literal(label.getText())));
return node;
}
private Shape label(final Resource root, final Collection<Statement> model) {
return Label.label(literal(root, Spec.text, model).stringValue());
}
private Resource notes(final Notes notes, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Notes));
model.add(statement(node, Spec.text, Values.literal(notes.getText())));
return node;
}
private Shape notes(final Resource root, final Collection<Statement> model) {
return Notes.notes(literal(root, Spec.text, model).stringValue());
}
private Resource placeholder(final Placeholder placeholder, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Placeholder));
model.add(statement(node, Spec.text, Values.literal(placeholder.getText())));
return node;
}
private Shape placeholder(final Resource root, final Collection<Statement> model) {
return Placeholder.placeholder(literal(root, Spec.text, model).stringValue());
}
private Resource dflt(final Default dflt, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Default));
model.add(statement(node, Spec.value, dflt.getValue()));
return node;
}
private Shape dflt(final Resource root, final Collection<Statement> model) {
return Default.dflt(value(root, Spec.value, model));
}
private Resource hint(final Hint hint, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Hint));
model.add(statement(node, Spec.iri, hint.getIRI()));
return node;
}
private Shape hint(final Resource root, final Collection<Statement> model) {
return Hint.hint(iri(root, Spec.iri, model));
}
private Resource group(final Group group, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Group));
model.add(statement(node, Spec.shape, shape(group.getShape(), model)));
return node;
}
private Shape group(final Resource root, final Collection<Statement> model) {
return Group.group(shape(resource(root, Spec.shape, model), model));
}
private Shape create(final Resource root, final Collection<Statement> model) {
return Shape.create(shapes(resource(root, Spec.shapes, model), model));
}
private Shape relate(final Resource root, final Collection<Statement> model) {
return Shape.relate(shapes(resource(root, Spec.shapes, model), model));
}
private Shape update(final Resource root, final Collection<Statement> model) {
return Shape.update(shapes(resource(root, Spec.shapes, model), model));
}
private Shape delete(final Resource root, final Collection<Statement> model) {
return Shape.delete(shapes(resource(root, Spec.shapes, model), model));
}
private Shape client(final Resource root, final Collection<Statement> model) {
return Shape.client(shapes(resource(root, Spec.shapes, model), model));
}
private Shape server(final Resource root, final Collection<Statement> model) {
return Shape.server(shapes(resource(root, Spec.shapes, model), model));
}
private Shape digest(final Resource root, final Collection<Statement> model) {
return Shape.digest(shapes(resource(root, Spec.shapes, model), model));
}
private Shape detail(final Resource root, final Collection<Statement> model) {
return Shape.detail(shapes(resource(root, Spec.shapes, model), model));
}
private Shape verify(final Resource root, final Collection<Statement> model) {
return Shape.verify(shapes(resource(root, Spec.shapes, model), model));
}
private Shape filter(final Resource root, final Collection<Statement> model) {
return Shape.filter(shapes(resource(root, Spec.shapes, model), model));
}
private Shape error(final String message) {
throw new UnsupportedOperationException(message);
}
//// Shifts ////////////////////////////////////////////////////////////////////////////////////////////////////////
private Resource shift(final Shift shift, final Collection<Statement> model) {
return shift.accept(new Shift.Probe<Resource>() {
@Override protected Resource fallback(final Shift shift) {
throw new UnsupportedOperationException("unsupported shift ["+shift+"]");
}
@Override public Resource visit(final Step step) {
return step(step, model);
}
@Override public Resource visit(final Count count) { return count(count, model); }
});
}
private Shift shift(final Resource root, final Collection<Statement> model) {
final Set<Value> types=types(root, model);
return types.contains(Spec.Step) ? step(root, model)
: types.contains(Spec.Count) ? count(root, model)
: shift("unknown shape type "+types);
}
private Resource step(final Step step, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Step));
model.add(statement(node, Spec.iri, step.getIRI()));
model.add(statement(node, Spec.inverse, Values.literal(step.isInverse())));
return node;
}
private Step step(final Resource root, final Collection<Statement> model) {
return Step.step(
iri(root, Spec.iri, model),
literal(root, Spec.inverse, model).booleanValue()
);
}
private Resource count(final Count count, final Collection<Statement> model) {
final Resource node=bnode();
model.add(statement(node, RDF.TYPE, Spec.Count));
model.add(statement(node, Spec.shift, shift(count.getShift(), model)));
return node;
}
private Count count(final Resource root, final Collection<Statement> model) {
return Count.count(shift(root, model));
}
private Shift shift(final String message) {
throw new UnsupportedOperationException(message);
}
//// Shape Lists ///////////////////////////////////////////////////////////////////////////////////////////////////
private Value shapes(final Collection<Shape> shapes, final Collection<Statement> model) {
return values(shapes.stream()
.map(s -> shape(s, model))
.collect(toList()), model);
}
private Collection<Shape> shapes(final Resource shapes, final Collection<Statement> model) {
return values(shapes, model)
.stream()
.filter(v -> v instanceof Resource) // !!! error reporting
.map(v -> (Resource)v)
.map(v -> decode(v, model))
.collect(toList());
}
//// Value Lists ///////////////////////////////////////////////////////////////////////////////////////////////////
private Value values(final Collection<Value> values, final Collection<Statement> model) {
if ( values.isEmpty() ) {
return RDF.NIL;
} else {
final Resource items=bnode();
RDFCollections.asRDF(values, items, model);
return items;
}
}
private Collection<Value> values(final Resource items, final Collection<Statement> model) {
return RDFCollections.asValues(new LinkedHashModel(model), items, new ArrayList<>()); // !!! avoid model construction
}
//// Decoding //////////////////////////////////////////////////////////////////////////////////////////////////////
private Set<Value> types(final Resource root, final Collection<Statement> model) {
return objects(root, RDF.TYPE, model).collect(toSet());
}
private IRI iri(final Resource subject, final IRI predicate, final Collection<Statement> model) {
return objects(subject, predicate, model)
.filter(v -> v instanceof IRI)
.map(v -> (IRI)v)
.findFirst()
.orElseThrow(missing(subject, predicate));
}
private Resource resource(final Resource subject, final IRI predicate, final Collection<Statement> model) {
return objects(subject, predicate, model)
.filter(v -> v instanceof Resource)
.map(v -> (Resource)v)
.findFirst()
.orElseThrow(missing(subject, predicate));
}
private Literal literal(final Resource subject, final IRI predicate, final Collection<Statement> model) {
return objects(subject, predicate, model)
.filter(v -> v instanceof Literal)
.map(v -> (Literal)v)
.findFirst()
.orElseThrow(missing(subject, predicate));
}
private Value value(final Resource subject, final IRI predicate, final Collection<Statement> model) {
return objects(subject, predicate, model)
.findFirst()
.orElseThrow(missing(subject, predicate));
}
private Stream<Value> objects(final Resource subject, final IRI predicate, final Collection<Statement> model) {
return model.stream()
.filter(s -> s.getSubject().equals(subject) && s.getPredicate().equals(predicate))
.map(Statement::getObject);
}
private Supplier<IllegalArgumentException> missing(final Resource subject, final IRI predicate) {
return () -> new IllegalArgumentException(
"missing "+Values.format(predicate)+" property ["+subject+"]");
}
}
| agpl-3.0 |
SilverDav/Silverpeas-Core | core-test/src/main/java/org/silverpeas/core/test/DataSourceProvider.java | 1833 | /*
* 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.test;
import org.silverpeas.core.annotation.Provider;
import org.silverpeas.core.util.ServiceProvider;
import javax.annotation.Resource;
import javax.enterprise.inject.Produces;
import javax.sql.DataSource;
/**
* A convenient provider of the data source used in the integration tests.
* @author mmoquillon
*/
@Provider
public class DataSourceProvider {
@Resource(lookup = "java:/datasources/silverpeas")
private DataSource dataSource;
private static DataSourceProvider getInstance() {
return ServiceProvider.getSingleton(DataSourceProvider.class);
}
@Produces
public static DataSource getDataSource() {
return getInstance().dataSource;
}
}
| agpl-3.0 |
pughlab/cbioportal | core/src/main/java/org/mskcc/cbio/portal/model/Treatment.java | 4931 | /*
* Copyright (c) 2019 The Hyve B.V.
*
* 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.model;
import java.io.Serializable;
/**
* @author Pim van Nierop, pim@thehyve.nl
*/
public class Treatment implements Serializable {
private int id;
private int geneticEntityId;
private String stableId;
private String name;
private String description;
private String refLink;
/**
* Create a Treatment object from fields
*
* @param treatmentId Treatment table ID key of the treament
* @param geneticEntityId Genetic_entity table ID key associated to the treament record
* @param stableId Stable identifier of the treatment used in the cBioPortal instance
* @param name Name of the treatment
* @param description Description of the treatment
* @param refLink Url for the treatment
*/
public Treatment(int id, int geneticEntityId, String stableId, String name, String description, String refLink) {
this.geneticEntityId = geneticEntityId;
this.geneticEntityId = geneticEntityId;
this.stableId = stableId;
this.name = name;
this.description = description;
this.refLink = refLink;
}
/**
* Create a Treatment object from fields
*
* @param treatmentId Treatment table ID key of the treament
* @param geneticEntityId Genetic_entity table ID key associated to the treament record
* @param stableId Stable identifier of the treatment used in the cBioPortal instance
* @param name Name of the treatment
* @param description Description of the treatment
* @param refLink Url for the treatment
*/
public Treatment(String stableId, String name, String description, String refLink) {
this.stableId = stableId;
this.name = name;
this.description = description;
this.refLink = refLink;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the geneticEntityId
*/
public int getGeneticEntityId() {
return geneticEntityId;
}
/**
* @param geneticEntityId the geneticEntityId to set
*/
public void setGeneticEntityId(Integer geneticEntityId) {
this.geneticEntityId = geneticEntityId;
}
/**
* @return the stableId
*/
public String getStableId() {
return stableId;
}
/**
* @param stableId the stableId to set
*/
public void setStableId(String stableId) {
this.stableId = stableId;
}
/**
* @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 refLink
*/
public String getRefLink() {
return refLink;
}
/**
* @param refLink the refLink to set
*/
public void setRefLink(String refLink) {
this.refLink = refLink;
}
}
| agpl-3.0 |
Tanaguru/Tanaguru | rules/rgaa3-2016/src/test/java/org/tanaguru/rules/rgaa32016/Rgaa32016Rule101503Test.java | 4477 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2016 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.rgaa32016;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.entity.audit.ProcessResult;
import org.tanaguru.rules.rgaa32016.test.Rgaa32016RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 10-15-3 of the referential Rgaa 3-2016.
*
* @author
*/
public class Rgaa32016Rule101503Test extends Rgaa32016RuleImplementationTestCase {
/**
* Default constructor
* @param testName
*/
public Rgaa32016Rule101503Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.tanaguru.rules.rgaa32016.Rgaa32016Rule101503");
}
@Override
protected void setUpWebResourceMap() {
// addWebResource("Rgaa32016.Test.10.15.3-1Passed-01");
// addWebResource("Rgaa32016.Test.10.15.3-2Failed-01");
addWebResource("Rgaa32016.Test.10.15.3-3NMI-01");
// addWebResource("Rgaa32016.Test.10.15.3-4NA-01");
}
@Override
protected void setProcess() {
//----------------------------------------------------------------------
//------------------------------1Passed-01------------------------------
//----------------------------------------------------------------------
// checkResultIsPassed(processPageTest("Rgaa32016.Test.10.15.3-1Passed-01"), 1);
//----------------------------------------------------------------------
//------------------------------2Failed-01------------------------------
//----------------------------------------------------------------------
// ProcessResult processResult = processPageTest("Rgaa32016.Test.10.15.3-2Failed-01");
// checkResultIsFailed(processResult, 1, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.FAILED,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------3NMI-01---------------------------------
//----------------------------------------------------------------------
ProcessResult processResult = processPageTest("Rgaa32016.Test.10.15.3-3NMI-01");
checkResultIsNotTested(processResult); // temporary result to make the result buildable before implementation
// checkResultIsPreQualified(processResult, 2, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.NEED_MORE_INFO,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------4NA-01------------------------------
//----------------------------------------------------------------------
// checkResultIsNotApplicable(processPageTest("Rgaa32016.Test.10.15.3-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("Rgaa32016.Test.10.15.3-3NMI-01").getValue());
}
}
| agpl-3.0 |
andmar8/Blackboard-Java-WebservicesBBSerializableObjects | src/bbws/resource/gradecentre/column/BBLineitem.java | 6229 | /*
Blackboard WebServices Serializable Objects
Copyright (C) 2011-2013 Andrew Martin, Newcastle University
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 bbws.resource.gradecentre.column;
//bbws
import bbws.entity.enums.verbosity.BBLineitemVerbosity;
//javax
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class BBLineitem
{
private String assessmentBbId;
private String assessmentLocation;
private Boolean available;
private Integer columnPosition;
private String dateAdded;
private String dateChanged;
private BBLineitemVerbosity verbosity;
private String lineItemBbId;
private String name;
private String outcomeDefBbId;
private Float pointsPossible;
//private List<BBScore> scores;
private String title;
private String type;
private Float weight;
public BBLineitem(){}
// public BBLineitem(Lineitem li,BBLineitemVerbosity verbosity) throws Exception
// {
// this.verbosity = verbosity;
//
// switch(this.verbosity)
// {
// case WithScores:
// /*try
// {
// this.scores = bbws.util.factory.list.BBListFactory.getBBScoreListFromList(li.getScores(),bbws.gradecentre.grade.BBScore.BBScoreVerbosity.extended);
// }
// catch(Exception e)
// {
// this.scores = null;
// }*/
// case WithoutScores:
// Object o = li.getAssessmentId();
// if(o!=null)
// {
// this.assessmentBbId = o.getClass().getName();
// if(this.assessmentBbId.equalsIgnoreCase("java.lang.String"))
// {
// this.assessmentBbId = o.toString();
// }
// else if(this.assessmentBbId.equalsIgnoreCase("blackboard.persist.Id"))
// {
// this.assessmentBbId = ((blackboard.persist.Id)o).getExternalString();
// }
// }
// if(li.getAssessmentLocation().equals(AssessmentLocation.EXTERNAL)){this.assessmentLocation = "EXTERNAL";}
// else if(li.getAssessmentLocation().equals(AssessmentLocation.INTERNAL)){this.assessmentLocation = "INTERNAL";}
// else if(li.getAssessmentLocation().equals(AssessmentLocation.UNSET)){this.assessmentLocation = "UNSET";}
// this.available = li.getIsAvailable();
// this.columnPosition = li.getColumnOrder();
// this.dateAdded = getDateTimeFromCalendar(li.getDateAdded());
// this.dateChanged = getDateTimeFromCalendar(li.getDateChanged());
// this.lineItemBbId = li.getId().toExternalString();
// this.name = li.getName();
// this.outcomeDefBbId = li.getOutcomeDefinition().getId().toExternalString();
// this.pointsPossible = li.getPointsPossible();
// this.type = li.getType();
// this.weight = li.getWeight();
// return;
// }
// throw new Exception("Undefined verbosity of line item");
// }
public String getAssessmentBbId()
{
return this.assessmentBbId;
}
public void setAssessmentBbId(String assessmentBbId)
{
this.assessmentBbId = assessmentBbId;
}
public String getAssessmentLocation()
{
return this.assessmentLocation;
}
public void setAssessmentLocation(String assessmentLocation)
{
this.assessmentLocation = assessmentLocation;
}
public Boolean getAvailable()
{
return this.available;
}
public void setAvailable(Boolean available)
{
this.available = available;
}
public Integer getColumnPosition()
{
return this.columnPosition;
}
public void setColumnPosition(Integer columnPosition)
{
this.columnPosition = columnPosition;
}
public String getDateAdded()
{
return this.dateAdded;
}
public void setDateAdded(String dateAdded)
{
this.dateAdded = dateAdded;
}
public String getDateChanged()
{
return this.dateChanged;
}
public void setDateChanged(String dateChanged)
{
this.dateChanged = dateChanged;
}
public String getLineItemBbId()
{
return this.lineItemBbId;
}
public void setLineItemBbId(String lineItemBbId)
{
this.lineItemBbId = lineItemBbId;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public String getOutcomeDefBbId()
{
return this.outcomeDefBbId;
}
public void setOutcomeDefBbId(String outcomeDefBbId)
{
this.outcomeDefBbId = outcomeDefBbId;
}
public Float getPointsPossible()
{
return this.pointsPossible;
}
public void setPointsPossible(Float pointsPossible)
{
this.pointsPossible = pointsPossible;
}
/*public List<BBScore> getScores()
{
return this.scores;
}
public void setScores(List<BBScore> scores)
{
this.scores = scores;
}*/
public String getTitle()
{
return this.title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getType()
{
return this.type;
}
public void setType(String type)
{
this.type = type;
}
public Float getWeight()
{
return this.weight;
}
public void setWeight(Float weight)
{
this.weight = weight;
}
}
| agpl-3.0 |
Sage-Bionetworks/rstudio | src/gwt/src/org/rstudio/studio/client/workbench/prefs/views/AceEditorPreview.java | 4967 | /*
* AceEditorPreview.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.prefs.views;
import com.google.gwt.dom.client.*;
import com.google.gwt.dom.client.Style.BorderStyle;
import com.google.gwt.dom.client.Style.Unit;
import org.rstudio.core.client.ExternalJavaScriptLoader;
import org.rstudio.core.client.ExternalJavaScriptLoader.Callback;
import org.rstudio.core.client.theme.ThemeFonts;
import org.rstudio.core.client.widget.DynamicIFrame;
import org.rstudio.core.client.widget.FontSizer;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceResources;
public class AceEditorPreview extends DynamicIFrame
{
public AceEditorPreview(String code)
{
code_ = code;
Style style = getStyleElement().getStyle();
style.setBorderColor("#CCC");
style.setBorderWidth(1, Unit.PX);
style.setBorderStyle(BorderStyle.SOLID);
}
@Override
protected void onFrameLoaded()
{
isFrameLoaded_ = true;
if (initialThemeUrl_ != null)
setTheme(initialThemeUrl_);
if (initialFontSize_ != null)
setFontSize(initialFontSize_);
final Document doc = getDocument();
final BodyElement body = doc.getBody();
body.getStyle().setMargin(0, Unit.PX);
body.getStyle().setBackgroundColor("white");
StyleElement style = doc.createStyleElement();
style.setType("text/css");
style.setInnerText(
".ace_editor {\n" +
"border: none !important;\n" +
"}");
setFont(ThemeFonts.getFixedWidthFont());
body.appendChild(style);
DivElement div = doc.createDivElement();
div.setId("editor");
div.getStyle().setWidth(100, Unit.PCT);
div.getStyle().setHeight(100, Unit.PCT);
div.setInnerText(code_);
body.appendChild(div);
FontSizer.injectStylesIntoDocument(doc);
FontSizer.applyNormalFontSize(div);
new ExternalJavaScriptLoader(doc, AceResources.INSTANCE.acejs().getSafeUri().asString())
.addCallback(new Callback()
{
public void onLoaded()
{
new ExternalJavaScriptLoader(doc, AceResources.INSTANCE.acesupportjs().getSafeUri().asString())
.addCallback(new Callback()
{
public void onLoaded()
{
body.appendChild(doc.createScriptElement(
"var editor = ace.edit('editor');\n" +
"editor.renderer.setHScrollBarAlwaysVisible(false);\n" +
"editor.renderer.setTheme({});\n" +
"editor.setHighlightActiveLine(false);\n" +
"editor.renderer.setShowGutter(false);\n" +
"var RMode = require('mode/r').Mode;\n" +
"editor.getSession().setMode(new RMode(false, editor.getSession().getDocument()));"));
}
});
}
});
}
public void setTheme(String themeUrl)
{
if (!isFrameLoaded_)
{
initialThemeUrl_ = themeUrl;
return;
}
if (currentStyleLink_ != null)
currentStyleLink_.removeFromParent();
Document doc = getDocument();
currentStyleLink_ = doc.createLinkElement();
currentStyleLink_.setRel("stylesheet");
currentStyleLink_.setType("text/css");
currentStyleLink_.setHref(themeUrl);
doc.getBody().appendChild(currentStyleLink_);
}
public void setFontSize(double fontSize)
{
if (!isFrameLoaded_)
{
initialFontSize_ = fontSize;
return;
}
FontSizer.setNormalFontSize(getDocument(), fontSize);
}
public void setFont(String font)
{
final String STYLE_EL_ID = "__rstudio_font_family";
Document document = getDocument();
Element oldStyle = document.getElementById(STYLE_EL_ID);
StyleElement style = document.createStyleElement();
style.setAttribute("type", "text/css");
style.setInnerText(".ace_editor, .ace_text-layer {\n" +
"font-family: " + font + " !important;\n" +
"}");
document.getBody().appendChild(style);
if (oldStyle != null)
oldStyle.removeFromParent();
style.setId(STYLE_EL_ID);
}
private LinkElement currentStyleLink_;
private boolean isFrameLoaded_;
private String initialThemeUrl_;
private Double initialFontSize_;
private final String code_;
}
| agpl-3.0 |
kamax-io/matrix-appservice-email | src/main/java/io/kamax/matrix/bridge/email/controller/ApplicationServiceController.java | 5750 | /*
* matrix-appservice-email - Matrix Bridge to E-mail
* Copyright (C) 2017 Kamax Sarl
*
* https://www.kamax.io/
*
* 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 io.kamax.matrix.bridge.email.controller;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.kamax.matrix.MatrixErrorInfo;
import io.kamax.matrix.bridge.email.exception.*;
import io.kamax.matrix.bridge.email.model.matrix.MatrixTransactionPush;
import io.kamax.matrix.bridge.email.model.matrix.RoomQuery;
import io.kamax.matrix.bridge.email.model.matrix.UserQuery;
import io.kamax.matrix.bridge.email.model.matrix._MatrixApplicationService;
import io.kamax.matrix.event._MatrixEvent;
import io.kamax.matrix.json.MatrixJsonEventFactory;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
@RestController
public class ApplicationServiceController {
private Logger log = LoggerFactory.getLogger(ApplicationServiceController.class);
@Autowired
private _MatrixApplicationService as;
private JsonParser jsonParser = new JsonParser();
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler({InvalidMatrixIdException.class, InvalidBodyContentException.class})
@ResponseBody
MatrixErrorInfo handleBadRequest(HttpServletRequest request, MatrixException e) {
log.error("Error when processing {} {}", request.getMethod(), request.getServletPath(), e);
return new MatrixErrorInfo(e.getErrorCode());
}
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(NoHomeserverTokenException.class)
@ResponseBody
MatrixErrorInfo handleUnauthorized(MatrixException e) {
return new MatrixErrorInfo(e.getErrorCode());
}
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ExceptionHandler(InvalidHomeserverTokenException.class)
@ResponseBody
MatrixErrorInfo handleForbidden(MatrixException e) {
return new MatrixErrorInfo(e.getErrorCode());
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ExceptionHandler({RoomNotFoundException.class, UserNotFoundException.class})
@ResponseBody
MatrixErrorInfo handleNotFound(MatrixException e) {
return new MatrixErrorInfo(e.getErrorCode());
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Throwable.class)
@ResponseBody
MatrixErrorInfo handleGeneric(HttpServletRequest request, Throwable t) {
log.error("Error when processing {} {}", request.getMethod(), request.getServletPath(), t);
return new MatrixErrorInfo(t);
}
@RequestMapping(value = "/rooms/{roomAlias:.+}", method = GET)
public Object getRoom(
@RequestParam(name = "access_token", required = false) String accessToken,
@PathVariable String roomAlias) {
log.info("Room {} was requested by HS", roomAlias);
as.queryRoom(new RoomQuery(roomAlias, accessToken));
return EmptyJsonResponse.get();
}
@RequestMapping(value = "/users/{mxId:.+}", method = GET)
public Object getUser(
@RequestParam(name = "access_token", required = false) String accessToken,
@PathVariable String mxId) {
log.info("User {} was requested by HS", mxId);
as.queryUser(new UserQuery(as.getId(mxId), accessToken));
return EmptyJsonResponse.get();
}
@RequestMapping(value = "/transactions/{txnId:.+}", method = PUT)
public Object getTransaction(
HttpServletRequest request,
@RequestParam(name = "access_token", required = false) String accessToken,
@PathVariable String txnId) throws IOException {
log.info("Processing {}", request.getServletPath());
String json = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
try {
JsonObject rootObj = jsonParser.parse(json).getAsJsonObject();
JsonArray eventsJson = rootObj.get("events").getAsJsonArray();
List<_MatrixEvent> events = new ArrayList<>();
for (JsonElement event : eventsJson) {
events.add(MatrixJsonEventFactory.get(event.getAsJsonObject()));
}
MatrixTransactionPush transaction = new MatrixTransactionPush();
transaction.setCredentials(accessToken);
transaction.setId(txnId);
transaction.setEvents(events);
as.push(transaction);
return EmptyJsonResponse.get();
} catch (IllegalStateException e) {
throw new InvalidBodyContentException(e);
}
}
}
| agpl-3.0 |
aborg0/rapidminer-vega | src/com/rapidminer/test/RapidMinerTestCase.java | 1838 | /*
* 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.test;
import com.rapidminer.tools.LogService;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
/**
* Extends the JUnit test case by a method for asserting equality of doubles
* with respect to Double.NaN
*
* @author Simon Fischer
*/
public class RapidMinerTestCase extends TestCase {
public RapidMinerTestCase() {
super();
}
public RapidMinerTestCase(String name) {
super(name);
}
@Override
public void setUp() throws Exception {
super.setUp();
LogService.getGlobal().setVerbosityLevel(LogService.WARNING);
}
public void assertEqualsNaN(String message, double expected, double actual) {
if (Double.isNaN(expected)) {
if (!Double.isNaN(actual)) {
throw new AssertionFailedError(message + " expected: <" + expected + "> but was: <" + actual + ">");
}
} else {
assertEquals(message, expected, actual, 0.000000001);
}
}
}
| agpl-3.0 |
ua-eas/ua-kfs-5.3 | work/src/org/kuali/kfs/module/tem/document/web/struts/CloseQuestionHandler.java | 5866 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* 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.tem.document.web.struts;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.kuali.kfs.module.tem.TemConstants.CLOSE_TA_QUESTION;
import static org.kuali.kfs.module.tem.TemConstants.CONFIRM_CLOSE_QUESTION;
import static org.kuali.kfs.module.tem.TemConstants.CONFIRM_CLOSE_QUESTION_TEXT;
import static org.kuali.kfs.sys.KFSConstants.BLANK_SPACE;
import static org.kuali.kfs.sys.KFSConstants.MAPPING_BASIC;
import static org.kuali.kfs.sys.KFSConstants.NOTE_TEXT_PROPERTY_NAME;
import org.kuali.kfs.module.tem.TemConstants.TravelDocTypes;
import org.kuali.kfs.module.tem.document.TravelAuthorizationCloseDocument;
import org.kuali.kfs.module.tem.document.TravelAuthorizationDocument;
import org.kuali.kfs.module.tem.document.TravelDocument;
import org.kuali.kfs.module.tem.document.service.TravelAuthorizationService;
import org.kuali.kfs.module.tem.util.MessageUtils;
import org.kuali.rice.krad.bo.Note;
import org.kuali.rice.krad.exception.ValidationException;
import org.kuali.rice.krad.service.DataDictionaryService;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.ObjectUtils;
/**
*
*/
public class CloseQuestionHandler implements QuestionHandler<TravelDocument> {
private DataDictionaryService dataDictionaryService;
private TravelAuthorizationService travelAuthorizationService;
@Override
public <T> T handleResponse(final Inquisitive<TravelDocument,?> asker) throws Exception {
if (asker.denied(CLOSE_TA_QUESTION)) {
return (T) asker.back();
}
else if (asker.confirmed(CONFIRM_CLOSE_QUESTION)) {
return (T) asker.end();
// This is the case when the user clicks on "OK" in the end.
// After we inform the user that the close has been rerouted, we'll redirect to the portal page.
}
TravelAuthorizationDocument document = (TravelAuthorizationDocument)asker.getDocument();
try {
// Below used as a place holder to allow code to specify actionForward to return if not a 'success question'
T returnActionForward = (T) ((StrutsInquisitor) asker).getMapping().findForward(MAPPING_BASIC);
TravelAuthorizationForm form = (TravelAuthorizationForm) ((StrutsInquisitor) asker).getForm();
TravelAuthorizationCloseDocument tacDocument = travelAuthorizationService.closeAuthorization(document, form.getAnnotation(), GlobalVariables.getUserSession().getPrincipalName(), null);
form.setDocTypeName(TravelDocTypes.TRAVEL_AUTHORIZATION_CLOSE_DOCUMENT);
form.setDocument(tacDocument);
if (ObjectUtils.isNotNull(returnActionForward)) {
return returnActionForward;
}
else {
return (T) asker.confirm(CLOSE_TA_QUESTION, MessageUtils.getMessage(CONFIRM_CLOSE_QUESTION_TEXT), true, "Could not get reimbursement total for travel id ", tacDocument.getTravelDocumentIdentifier().toString(),"","");
}
}
catch (ValidationException ve) {
throw ve;
}
}
/**
* @see org.kuali.kfs.module.tem.document.web.struts.QuestionHandler#askQuestion(org.kuali.kfs.module.tem.document.web.struts.Inquisitive)
*/
@Override
public <T> T askQuestion(final Inquisitive<TravelDocument,?> asker) throws Exception {
T retval = (T) asker.confirm(CLOSE_TA_QUESTION, CONFIRM_CLOSE_QUESTION_TEXT, false);
return retval;
}
/**
*
* @param notePrefix
* @param reason
* @return
*/
public String getReturnToFiscalOfficerNote(final String notePrefix, String reason) {
String noteText = "";
// Have to check length on value entered.
final String introNoteMessage = notePrefix + BLANK_SPACE;
// Build out full message.
noteText = introNoteMessage + reason;
final int noteTextLength = noteText.length();
// Get note text max length from DD.
final int noteTextMaxLength = dataDictionaryService.getAttributeMaxLength(Note.class, NOTE_TEXT_PROPERTY_NAME).intValue();
if (isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
// Figure out exact number of characters that the user can enter.
int reasonLimit = noteTextMaxLength - noteTextLength;
if (ObjectUtils.isNull(reason)) {
// Prevent a NPE by setting the reason to a blank string.
reason = "";
}
}
return noteText;
}
public void setDataDictionaryService(final DataDictionaryService dataDictionaryService) {
this.dataDictionaryService = dataDictionaryService;
}
public void setTravelAuthorizationService(TravelAuthorizationService travelAuthorizationService) {
this.travelAuthorizationService = travelAuthorizationService;
}
}
| agpl-3.0 |
kcoolsae/Degage | db/src/main/java/be/ugent/degage/db/jdbc/JDBCAddressDAO.java | 8226 | /* JDBCAddressDAO.java
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright Ⓒ 2014-2015 Universiteit Gent
*
* This file is part of the Degage Web Application
*
* Corresponding author (see also AUTHORS.txt)
*
* Kris Coolsaet
* Department of Applied Mathematics, Computer Science and Statistics
* Ghent University
* Krijgslaan 281-S9
* B-9000 GENT Belgium
*
* The Degage Web Application 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.
*
* The Degage Web Application 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 the Degage Web Application (file LICENSE.txt in the
* distribution). If not, see <http://www.gnu.org/licenses/>.
*/
package be.ugent.degage.db.jdbc;
import be.ugent.degage.db.DataAccessException;
import be.ugent.degage.db.dao.AddressDAO;
import be.ugent.degage.db.models.Address;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* JDBC implementation of {@link AddressDAO}
*/
class JDBCAddressDAO extends AbstractDAO implements AddressDAO {
public JDBCAddressDAO(JDBCDataAccessContext context){
super (context);
}
// TODO: avoid these
static Address populateAddress(ResultSet rs) throws SQLException {
if(rs.getObject("address_id") == null)
return null;
else
return new Address(
rs.getInt("address_id"),
rs.getString("address_country"),
rs.getString("address_zipcode"),
rs.getString("address_city"),
rs.getString("address_street"),
rs.getString("address_number"),
rs.getFloat("address_latitude"),
rs.getFloat("address_longitude")
);
}
// TODO: avoid these
static Address populateAddress(ResultSet rs, String tableName) throws SQLException {
if(rs.getObject(tableName + ".address_id") == null)
return null;
else
return new Address(
rs.getInt(tableName + ".address_id"),
rs.getString(tableName + ".address_country"),
rs.getString(tableName + ".address_zipcode"),
rs.getString(tableName + ".address_city"),
rs.getString(tableName + ".address_street"),
rs.getString(tableName + ".address_number"),
rs.getFloat(tableName + ".address_latitude"),
rs.getFloat(tableName + ".address_longitude")
);
}
public static final String ADDRESS_FIELDS =
"address_id, address_city, address_zipcode, address_street, address_number, address_country, address_latitude, address_longitude ";
private LazyStatement getAddressStatement = new LazyStatement(
"SELECT " + ADDRESS_FIELDS + "FROM addresses WHERE address_id = ?");
@Override
public Address getAddress(int id) throws DataAccessException {
try {
PreparedStatement ps = getAddressStatement.value(); // reused so should not be auto-closed
ps.setInt(1, id);
try (ResultSet rs = ps.executeQuery()) {
if(rs.next()) {
return populateAddress(rs);
} else
return null;
}
} catch (SQLException ex) {
throw new DataAccessException("Could not fetch address by id.", ex);
}
}
private LazyStatement createAddressStatement = new LazyStatement(
"INSERT INTO addresses(address_city, address_zipcode, address_street, address_number, address_country, address_latitude, address_longitude) " +
"VALUES (?,?,?,?,?)",
"address_id"
);
@Override
public Address createAddress(String country, String zip, String city, String street, String num, float lat, float lng) throws DataAccessException {
try {
PreparedStatement ps = createAddressStatement.value(); // reused so should not be auto-closed
ps.setString(1, city);
ps.setString(2, zip);
ps.setString(3, street);
ps.setString(4, num);
ps.setString(5, country);
ps.setFloat(6, lat);
ps.setFloat(7, lng);
if(ps.executeUpdate() == 0)
throw new DataAccessException("No rows were affected when creating address.");
try (ResultSet keys = ps.getGeneratedKeys()) {
keys.next(); //if this fails we want an exception anyway
return new Address(keys.getInt(1), country, zip, city, street, num, lat, lng);
}
} catch (SQLException ex) {
throw new DataAccessException("Failed to create address.", ex);
}
}
private LazyStatement deleteAddressStatement = new LazyStatement(
"DELETE FROM addresses WHERE address_id = ?"
);
@Override
public void deleteAddress(int addressId) throws DataAccessException {
try {
PreparedStatement ps = deleteAddressStatement.value(); // reused so should not be auto-closed
ps.setInt(1, addressId);
if(ps.executeUpdate() == 0)
throw new DataAccessException("No rows were affected when deleting address with ID=" + addressId);
} catch(SQLException ex){
throw new DataAccessException("Failed to execute address deletion query.", ex);
}
}
// used to update addresses as part of updates of other tables
static void updateLocation(Connection conn, String joinSQL, String idName, int id, Address location) {
try (PreparedStatement ps = conn.prepareStatement(
"UPDATE addresses " + joinSQL +
" SET address_city = ?, address_zipcode = ?, address_street = ?, address_number = ?, address_country=?, address_latitude=?, address_longitude=? " +
"WHERE " + idName + " = ?"
)) {
ps.setString(1, location.getCity());
ps.setString(2, location.getZip());
ps.setString(3, location.getStreet());
ps.setString(4, location.getNum());
ps.setString(5, location.getCountry());
ps.setFloat(6, location.getLat());
ps.setFloat(7, location.getLng());
ps.setInt(8, id);
ps.executeUpdate();
} catch (SQLException ex) {
throw new DataAccessException("Failed to update location.", ex);
}
}
private LazyStatement updateAddressStatement = new LazyStatement(
"UPDATE addresses SET address_city = ?, address_zipcode = ?, address_street = ?, " +
"address_number = ?, address_country=?, " + "address_latitude = ?, address_longitude=? " +
"WHERE address_id = ?"
);
@Override
public void updateAddress(Address address) throws DataAccessException {
try {
PreparedStatement ps = updateAddressStatement.value(); // reused so should not be auto-closed
ps.setString(1, address.getCity());
ps.setString(2, address.getZip());
ps.setString(3, address.getStreet());
ps.setString(4, address.getNum());
ps.setString(5, address.getCountry());
ps.setFloat(6, address.getLat());
ps.setFloat(7, address.getLng());
ps.setInt(8, address.getId());
if(ps.executeUpdate() == 0)
throw new DataAccessException("Address update affected 0 rows.");
} catch(SQLException ex) {
throw new DataAccessException("Failed to update address.", ex);
}
}
}
| agpl-3.0 |
automenta/narchy | logic/src/main/java/alice/util/AbstractDynamicClassLoader.java | 2091 | package alice.util;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
*
* @author Alessio Mercurio
*
* Custom abstract classloader used to addAt/remove dynamically URLs from it
* needed by JavaLibrary.
*
*/
public abstract class AbstractDynamicClassLoader extends ClassLoader
{
protected final ArrayList<URL> listURLs;
protected final HashMap<String, Class<?>> classCache = new HashMap<>();
public AbstractDynamicClassLoader()
{
super(AbstractDynamicClassLoader.class.getClassLoader());
listURLs = new ArrayList<>();
}
public AbstractDynamicClassLoader(URL... urls)
{
super(AbstractDynamicClassLoader.class.getClassLoader());
listURLs = new ArrayList<>(Arrays.asList(urls));
}
public AbstractDynamicClassLoader(URL[] urls, ClassLoader parent)
{
super(parent);
listURLs = new ArrayList<>(Arrays.asList(urls));
}
@Override
public Class<?> loadClass(String className) throws ClassNotFoundException {
return findClass(className);
}
public void addURLs(URL... urls) {
if(urls == null)
throw new IllegalArgumentException("Array URLs must not be null.");
for (URL url : urls) {
if(!listURLs.contains(url))
listURLs.add(url);
}
}
public void removeURL(URL url) throws IllegalArgumentException
{
if(!listURLs.contains(url))
throw new IllegalArgumentException("URL: " + url + "not found.");
listURLs.remove(url);
}
public void removeURLs(URL... urls) throws IllegalArgumentException
{
if(urls == null)
throw new IllegalArgumentException("Array URLs must not be null.");
for (URL url : urls) {
if(!listURLs.contains(url))
throw new IllegalArgumentException("URL: " + url + "not found.");
listURLs.remove(url);
}
}
public void removeAllURLs()
{
if(!listURLs.isEmpty())
listURLs.clear();
}
public URL[] getURLs()
{
URL[] result = new URL[listURLs.size()];
listURLs.toArray(result);
return result;
}
public Class<?>[] getLoadedClasses() {
return classCache.values().toArray(new Class[0]);
}
}
| agpl-3.0 |
medsob/Tanaguru | engine/crawler/src/test/java/org/tanaguru/service/mock/MockParameterDataService.java | 7102 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This file is part of Tanaguru.
*
* Tanaguru 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.service.mock;
import java.util.Collection;
import java.util.Set;
import org.tanaguru.entity.audit.Audit;
import org.tanaguru.entity.parameterization.Parameter;
import org.tanaguru.entity.parameterization.ParameterElement;
import org.tanaguru.entity.parameterization.ParameterFamily;
import org.tanaguru.entity.parameterization.ParameterImpl;
import org.tanaguru.entity.service.parameterization.ParameterDataService;
import org.tanaguru.sdk.entity.dao.GenericDAO;
import org.tanaguru.sdk.entity.factory.GenericFactory;
/**
*
* @author jkowalczyk
*/
public class MockParameterDataService implements ParameterDataService{
@Override
public Parameter create(ParameterElement pe, String string, Audit audit) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Parameter getParameter(ParameterElement pe, String string) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Parameter getParameter(Audit audit, String string) {
Parameter param = new ParameterImpl();
param.setValue("1000");
return param;
}
@Override
public Parameter getLevelParameter(String string) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Set<Parameter> getParameterSet(ParameterFamily pf, Audit audit) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Set<Parameter> getParameterSet(ParameterFamily pf, Collection<Parameter> clctn) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Set<Parameter> getDefaultParameterSet() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Parameter getDefaultParameter(ParameterElement pe) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Parameter getDefaultLevelParameter() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Set<Parameter> getParameterSetFromAudit(Audit audit) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getReferentialKeyFromAudit(Audit audit) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getLevelKeyFromAudit(Audit audit) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Set<Parameter> updateParameterSet(Set<Parameter> set, Set<Parameter> set1) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Set<Parameter> updateParameter(Set<Parameter> set, Parameter prmtr) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Parameter create() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void create(Parameter e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void delete(Parameter e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void delete(Long k) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void delete(Collection<Parameter> clctn) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Collection<Parameter> findAll() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Parameter read(Long k) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Parameter saveOrUpdate(Parameter e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Collection<Parameter> saveOrUpdate(Collection<Parameter> clctn) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setEntityDao(GenericDAO<Parameter, Long> gdao) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setEntityFactory(GenericFactory<Parameter> gf) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Parameter update(Parameter e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/IfcTaskTypeEnum.java | 15449 | /**
* 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 org.bimserver.models.ifc4;
/******************************************************************************
* 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 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 Task Type Enum</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcTaskTypeEnum()
* @model
* @generated
*/
public enum IfcTaskTypeEnum 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>DEMOLITION</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #DEMOLITION_VALUE
* @generated
* @ordered
*/
DEMOLITION(1, "DEMOLITION", "DEMOLITION"),
/**
* The '<em><b>DISMANTLE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #DISMANTLE_VALUE
* @generated
* @ordered
*/
DISMANTLE(2, "DISMANTLE", "DISMANTLE"),
/**
* The '<em><b>ATTENDANCE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #ATTENDANCE_VALUE
* @generated
* @ordered
*/
ATTENDANCE(3, "ATTENDANCE", "ATTENDANCE"),
/**
* The '<em><b>USERDEFINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #USERDEFINED_VALUE
* @generated
* @ordered
*/
USERDEFINED(4, "USERDEFINED", "USERDEFINED"),
/**
* The '<em><b>RENOVATION</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #RENOVATION_VALUE
* @generated
* @ordered
*/
RENOVATION(5, "RENOVATION", "RENOVATION"),
/**
* The '<em><b>MAINTENANCE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #MAINTENANCE_VALUE
* @generated
* @ordered
*/
MAINTENANCE(6, "MAINTENANCE", "MAINTENANCE"),
/**
* The '<em><b>NOTDEFINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NOTDEFINED_VALUE
* @generated
* @ordered
*/
NOTDEFINED(7, "NOTDEFINED", "NOTDEFINED"),
/**
* The '<em><b>REMOVAL</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REMOVAL_VALUE
* @generated
* @ordered
*/
REMOVAL(8, "REMOVAL", "REMOVAL"),
/**
* The '<em><b>DISPOSAL</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #DISPOSAL_VALUE
* @generated
* @ordered
*/
DISPOSAL(9, "DISPOSAL", "DISPOSAL"),
/**
* The '<em><b>MOVE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #MOVE_VALUE
* @generated
* @ordered
*/
MOVE(10, "MOVE", "MOVE"),
/**
* The '<em><b>OPERATION</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #OPERATION_VALUE
* @generated
* @ordered
*/
OPERATION(11, "OPERATION", "OPERATION"),
/**
* The '<em><b>INSTALLATION</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #INSTALLATION_VALUE
* @generated
* @ordered
*/
INSTALLATION(12, "INSTALLATION", "INSTALLATION"),
/**
* The '<em><b>CONSTRUCTION</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CONSTRUCTION_VALUE
* @generated
* @ordered
*/
CONSTRUCTION(13, "CONSTRUCTION", "CONSTRUCTION"),
/**
* The '<em><b>LOGISTIC</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #LOGISTIC_VALUE
* @generated
* @ordered
*/
LOGISTIC(14, "LOGISTIC", "LOGISTIC");
/**
* 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>DEMOLITION</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>DEMOLITION</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #DEMOLITION
* @model
* @generated
* @ordered
*/
public static final int DEMOLITION_VALUE = 1;
/**
* The '<em><b>DISMANTLE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>DISMANTLE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #DISMANTLE
* @model
* @generated
* @ordered
*/
public static final int DISMANTLE_VALUE = 2;
/**
* The '<em><b>ATTENDANCE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>ATTENDANCE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #ATTENDANCE
* @model
* @generated
* @ordered
*/
public static final int ATTENDANCE_VALUE = 3;
/**
* 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 = 4;
/**
* The '<em><b>RENOVATION</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>RENOVATION</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #RENOVATION
* @model
* @generated
* @ordered
*/
public static final int RENOVATION_VALUE = 5;
/**
* The '<em><b>MAINTENANCE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>MAINTENANCE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #MAINTENANCE
* @model
* @generated
* @ordered
*/
public static final int MAINTENANCE_VALUE = 6;
/**
* 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 = 7;
/**
* The '<em><b>REMOVAL</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>REMOVAL</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #REMOVAL
* @model
* @generated
* @ordered
*/
public static final int REMOVAL_VALUE = 8;
/**
* The '<em><b>DISPOSAL</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>DISPOSAL</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #DISPOSAL
* @model
* @generated
* @ordered
*/
public static final int DISPOSAL_VALUE = 9;
/**
* The '<em><b>MOVE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>MOVE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #MOVE
* @model
* @generated
* @ordered
*/
public static final int MOVE_VALUE = 10;
/**
* The '<em><b>OPERATION</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>OPERATION</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #OPERATION
* @model
* @generated
* @ordered
*/
public static final int OPERATION_VALUE = 11;
/**
* The '<em><b>INSTALLATION</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>INSTALLATION</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #INSTALLATION
* @model
* @generated
* @ordered
*/
public static final int INSTALLATION_VALUE = 12;
/**
* The '<em><b>CONSTRUCTION</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>CONSTRUCTION</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #CONSTRUCTION
* @model
* @generated
* @ordered
*/
public static final int CONSTRUCTION_VALUE = 13;
/**
* The '<em><b>LOGISTIC</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>LOGISTIC</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #LOGISTIC
* @model
* @generated
* @ordered
*/
public static final int LOGISTIC_VALUE = 14;
/**
* An array of all the '<em><b>Ifc Task Type Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final IfcTaskTypeEnum[] VALUES_ARRAY = new IfcTaskTypeEnum[] { NULL, DEMOLITION, DISMANTLE, ATTENDANCE, USERDEFINED, RENOVATION, MAINTENANCE, NOTDEFINED, REMOVAL, DISPOSAL, MOVE, OPERATION, INSTALLATION, CONSTRUCTION,
LOGISTIC, };
/**
* A public read-only list of all the '<em><b>Ifc Task Type Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<IfcTaskTypeEnum> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Ifc Task 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 IfcTaskTypeEnum get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
IfcTaskTypeEnum result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc Task 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 IfcTaskTypeEnum getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
IfcTaskTypeEnum result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc Task 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 IfcTaskTypeEnum get(int value) {
switch (value) {
case NULL_VALUE:
return NULL;
case DEMOLITION_VALUE:
return DEMOLITION;
case DISMANTLE_VALUE:
return DISMANTLE;
case ATTENDANCE_VALUE:
return ATTENDANCE;
case USERDEFINED_VALUE:
return USERDEFINED;
case RENOVATION_VALUE:
return RENOVATION;
case MAINTENANCE_VALUE:
return MAINTENANCE;
case NOTDEFINED_VALUE:
return NOTDEFINED;
case REMOVAL_VALUE:
return REMOVAL;
case DISPOSAL_VALUE:
return DISPOSAL;
case MOVE_VALUE:
return MOVE;
case OPERATION_VALUE:
return OPERATION;
case INSTALLATION_VALUE:
return INSTALLATION;
case CONSTRUCTION_VALUE:
return CONSTRUCTION;
case LOGISTIC_VALUE:
return LOGISTIC;
}
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 IfcTaskTypeEnum(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
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;
}
} //IfcTaskTypeEnum
| agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-commons/src/main/java/org/asqatasun/rules/elementchecker/lang/LangDeclarationValidityChecker.java | 3622 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun 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.elementchecker.lang;
import javax.annotation.Nonnull;
import org.jsoup.nodes.Element;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.processor.SSPHandler;
import static org.asqatasun.rules.keystore.RemarkMessageStore.*;
/**
* This class checks whether the lang declaration is valid and relevant
*/
public class LangDeclarationValidityChecker extends LangChecker {
/** check declaration validity */
private final boolean checkDeclarationValidity;
/** check declaration relevancy */
private final boolean checkDeclarationRelevancy;
/**
* Default constructor
* @param checkDeclarationValidity
* @param checkDeclarationRelevancy
*/
public LangDeclarationValidityChecker(
@Nonnull boolean checkDeclarationValidity,
@Nonnull boolean checkDeclarationRelevancy) {
super(null,
IRRELEVANT_LANG_DECL_MSG,
SUSPECTED_IRRELEVANT_LANG_DECL_MSG,
SUSPECTED_RELEVANT_LANG_DECL_MSG);
this.checkDeclarationValidity = checkDeclarationValidity;
this.checkDeclarationRelevancy = checkDeclarationRelevancy;
}
@Override
protected TestSolution doCheckLanguage(Element element, SSPHandler sspHandler) {
return checkLanguageDeclarationValidity(element, sspHandler);
}
/**
*
* @param element
* @param sspHandler
* @return
*/
public TestSolution checkLanguageDeclarationValidity(Element element, SSPHandler sspHandler) {
String langDefinition = extractLangDefinitionFromElement(element, sspHandler);
String effectiveLang = extractEffectiveLang(langDefinition);
TestSolution declarationValidity =
checkLanguageDeclarationValidity(
element,
langDefinition,
effectiveLang,
checkDeclarationValidity);
if (checkDeclarationValidity && declarationValidity.equals(TestSolution.FAILED)) {
return TestSolution.FAILED;
}
if (checkDeclarationRelevancy) {
if (declarationValidity.equals(TestSolution.FAILED)) {
return TestSolution.NOT_APPLICABLE;
}
String extractedText = extractTextFromElement(element, true);
if (isTextTestable(extractedText)) {
return checkLanguageRelevancy(
element,
effectiveLang,
null,
extractedText,
TestSolution.PASSED,
TestSolution.FAILED);
}
}
return TestSolution.PASSED;
}
}
| agpl-3.0 |
martinbaker/euclideanspace | com.euclideanspace.spad/src-gen/com/euclideanspace/spad/editor/IterateStatement.java | 1405 | /**
*/
package com.euclideanspace.spad.editor;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Iterate Statement</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.euclideanspace.spad.editor.IterateStatement#getStname <em>Stname</em>}</li>
* </ul>
* </p>
*
* @see com.euclideanspace.spad.editor.EditorPackage#getIterateStatement()
* @model
* @generated
*/
public interface IterateStatement extends EObject
{
/**
* Returns the value of the '<em><b>Stname</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Stname</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Stname</em>' attribute.
* @see #setStname(String)
* @see com.euclideanspace.spad.editor.EditorPackage#getIterateStatement_Stname()
* @model
* @generated
*/
String getStname();
/**
* Sets the value of the '{@link com.euclideanspace.spad.editor.IterateStatement#getStname <em>Stname</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Stname</em>' attribute.
* @see #getStname()
* @generated
*/
void setStname(String value);
} // IterateStatement
| agpl-3.0 |
geomajas/geomajas-project-server | plugin/layer-geotools/geotools/src/test/java/org/geomajas/layer/geotools/DummyJdbcFactory.java | 1533 | package org.geomajas.layer.geotools;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.geotools.data.AbstractDataStoreFactory;
import org.geotools.data.DataStore;
import org.geotools.data.store.ContentDataStore;
import org.geotools.data.store.ContentEntry;
import org.geotools.data.store.ContentFeatureSource;
import org.opengis.feature.type.Name;
public class DummyJdbcFactory extends AbstractDataStoreFactory implements org.geotools.data.DataStoreFactorySpi {
public class DummyJdbcDataStore extends ContentDataStore {
protected List<Name> createTypeNames() throws IOException {
return null;
}
protected ContentFeatureSource createFeatureSource(ContentEntry entry) throws IOException {
return null;
}
}
public String getDescription() {
return "DummyJdbcFactory";
}
public Param[] getParametersInfo() {
return new Param[] { new Param("testScope", Boolean.class, "Set to true for unit testing", true) };
}
public boolean canProcess(Map params) {
if (!super.canProcess(params)) {
return false; // was not in agreement with getParametersInfo
}
if (!(((String) params.get("testScope")).equalsIgnoreCase("true"))) {
return (false);
} else {
return (true);
}
}
public DataStore createDataStore(Map<String, Serializable> params) throws IOException {
return new DummyJdbcDataStore();
}
public DataStore createNewDataStore(Map<String, Serializable> params) throws IOException {
return new DummyJdbcDataStore();
}
}
| agpl-3.0 |
hltn/opencps | portlets/opencps-portlet/docroot/WEB-INF/service/org/opencps/processmgt/NoSuchProcessStepDossierPartException.java | 1112 | /**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package org.opencps.processmgt;
import com.liferay.portal.NoSuchModelException;
/**
* @author khoavd
*/
public class NoSuchProcessStepDossierPartException extends NoSuchModelException {
public NoSuchProcessStepDossierPartException() {
super();
}
public NoSuchProcessStepDossierPartException(String msg) {
super(msg);
}
public NoSuchProcessStepDossierPartException(String msg, Throwable cause) {
super(msg, cause);
}
public NoSuchProcessStepDossierPartException(Throwable cause) {
super(cause);
}
} | agpl-3.0 |
elki-project/elki | elki-core-util/src/test/java/elki/utilities/datastructures/heap/HeapPerformanceTest.java | 4083 | /*
* 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.heap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import org.junit.Ignore;
import org.junit.Test;
/**
* Unit test to ensure that our heap is not significantly worse than SUN javas
* regular PriorityQueue.
*
* @author Erich Schubert
* @since 0.7.0
*/
public class HeapPerformanceTest {
private final int queueSize = 200000;
private final int preiterations = 20;
private final int iterations = 200;
private final long seed = 123456L;
@Ignore
@Test
public void testRuntime() throws Exception {
// prepare the data set
final List<Integer> elements = new ArrayList<>(queueSize);
{
final Random random = new Random(seed);
for(int i = 0; i < queueSize; i++) {
elements.add(i);
}
Collections.shuffle(elements, random);
}
// Pretest, to trigger hotspot compiler, hopefully.
{
for(int j = 0; j < preiterations; j++) {
ComparableMinHeap<Integer> pq = new ComparableMinHeap<>();
testHeap(elements, pq);
}
for(int j = 0; j < preiterations; j++) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
testQueue(elements, pq);
}
}
long pqstart = System.nanoTime();
{
for(int j = 0; j < iterations; j++) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
testQueue(elements, pq);
}
}
long pqtime = System.nanoTime() - pqstart;
long hstart = System.nanoTime();
{
for(int j = 0; j < iterations; j++) {
ComparableMinHeap<Integer> pq = new ComparableMinHeap<>();
testHeap(elements, pq);
}
}
long htime = System.nanoTime() - hstart;
// System.err.println("Heap performance test: us: " + htime*1E-9 + " java: " + pqtime*1E-9);
assertTrue("Heap performance regression - run test individually, since the hotspot optimizations may make the difference! " + htime + " >>= " + pqtime, htime < 1.1 * pqtime);
// 1.1 allows some difference in measuring, which can occur e.g. due to Jacoco instrumentation
}
private void testHeap(final List<Integer> elements, ComparableMinHeap<Integer> pq) {
// Insert all
for(int i = 0; i < elements.size(); i++) {
pq.add(elements.get(i));
}
// Poll first half.
final int half = elements.size() >> 1;
for(int i = 0; i < half; i++) {
assertEquals((int) pq.poll(), i);
// assertEquals((int) pq.poll(), queueSize - 1 - i);
}
assertEquals("Heap not half-empty?", elements.size() - half, pq.size());
pq.clear();
}
private void testQueue(final List<Integer> elements, Queue<Integer> pq) {
// Insert all
for(int i = 0; i < elements.size(); i++) {
pq.add(elements.get(i));
}
// Poll first half.
final int half = elements.size() >> 1;
for(int i = 0; i < half; i++) {
assertEquals((int) pq.poll(), i);
// assertEquals((int) pq.poll(), queueSize - 1 - i);
}
assertEquals("Heap not half-empty?", elements.size() - half, pq.size());
pq.clear();
}
} | agpl-3.0 |
opensourceBIM/BIMserver | BimServer/src/org/bimserver/database/actions/GetAllUsersDatabaseAction.java | 2879 | package org.bimserver.database.actions;
/******************************************************************************
* 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 java.util.Set;
import org.bimserver.BimserverDatabaseException;
import org.bimserver.database.BimserverLockConflictException;
import org.bimserver.database.DatabaseSession;
import org.bimserver.database.OldQuery;
import org.bimserver.database.query.conditions.AttributeCondition;
import org.bimserver.database.query.conditions.Condition;
import org.bimserver.database.query.conditions.IsOfTypeCondition;
import org.bimserver.database.query.conditions.Not;
import org.bimserver.database.query.literals.EnumLiteral;
import org.bimserver.models.log.AccessMethod;
import org.bimserver.models.store.ObjectState;
import org.bimserver.models.store.StorePackage;
import org.bimserver.models.store.User;
import org.bimserver.models.store.UserType;
import org.bimserver.shared.exceptions.UserException;
import org.bimserver.utils.CollectionUtils;
import org.bimserver.webservices.authorization.Authorization;
public class GetAllUsersDatabaseAction extends BimDatabaseAction<Set<User>> {
private Authorization authorization;
public GetAllUsersDatabaseAction(DatabaseSession databaseSession, AccessMethod accessMethod, Authorization authorization) {
super(databaseSession, accessMethod);
this.authorization = authorization;
}
@Override
public Set<User> execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
User actingUser = getUserByUoid(authorization.getUoid());
Condition condition = new IsOfTypeCondition(StorePackage.eINSTANCE.getUser());
condition = condition.and(new Not(new AttributeCondition(StorePackage.eINSTANCE.getUser_UserType(), new EnumLiteral(UserType.SYSTEM))));
if (actingUser.getUserType() != UserType.ADMIN) {
condition = condition.and(new AttributeCondition(StorePackage.eINSTANCE.getUser_State(), new EnumLiteral(ObjectState.ACTIVE)));
}
return CollectionUtils.mapToSet(getDatabaseSession().query(condition, User.class, OldQuery.getDefault()));
}
} | agpl-3.0 |
gnosygnu/xowa_android | _100_core/src/main/java/gplx/core/stores/DataRdr_.java | 3982 | package gplx.core.stores; import gplx.*; import gplx.core.*;
import gplx.core.strings.*;
public class DataRdr_ {
public static final DataRdr Null = new DataRdr_null();
public static DataRdr as_(Object obj) {return obj instanceof DataRdr ? (DataRdr)obj : null;}
public static DataRdr cast(Object obj) {try {return (DataRdr)obj;} catch(Exception exc) {throw Err_.new_type_mismatch_w_exc(exc, DataRdr.class, obj);}}
public static Object Read_1st_row_and_1st_fld(DataRdr rdr) {
try {return rdr.MoveNextPeer() ? rdr.ReadAt(0) : null;}
finally {rdr.Rls();}
}
}
class DataRdr_null implements DataRdr {
public String NameOfNode() {return To_str();} public String To_str() {return "<< NULL READER >>";}
public boolean Type_rdr() {return true;}
public Hash_adp EnvVars() {return Hash_adp_.Noop;}
public Io_url Uri() {return Io_url_.Empty;} public void Uri_set(Io_url s) {}
public boolean Parse() {return parse;} public void Parse_set(boolean v) {parse = v;} private boolean parse;
public int FieldCount() {return 0;}
public String KeyAt(int i) {return To_str();}
public Object ReadAt(int i) {return null;}
public Keyval KeyValAt(int i) {return Keyval_.new_(this.KeyAt(i), this.ReadAt(i));}
public Object Read(String name) {return null;}
public String ReadStr(String key) {return String_.Empty;} public String ReadStrOr(String key, String or) {return or;}
public byte[] ReadBryByStr(String key) {return Bry_.Empty;} public byte[] ReadBryByStrOr(String key, byte[] or) {return or;}
public byte[] ReadBry(String key) {return Bry_.Empty;} public byte[] ReadBryOr(String key, byte[] or) {return or;}
public char ReadChar(String key) {return Char_.Null;} public char ReadCharOr(String key, char or) {return or;}
public int ReadInt(String key) {return Int_.Min_value;} public int ReadIntOr(String key, int or) {return or;}
public boolean ReadBool(String key) {return false;} public boolean ReadBoolOr(String key, boolean or) {return or;}
public long ReadLong(String key) {return Long_.Min_value;} public long ReadLongOr(String key, long or) {return or;}
public double ReadDouble(String key) {return Double_.NaN;} public double ReadDoubleOr(String key, double or) {return or;}
public float ReadFloat(String key) {return Float_.NaN;} public float ReadFloatOr(String key, float or) {return or;}
public byte ReadByte(String key) {return Byte_.Min_value;} public byte ReadByteOr(String key, byte or) {return or;}
public Decimal_adp ReadDecimal(String key) {return Decimal_adp_.Zero;}public Decimal_adp ReadDecimalOr(String key, Decimal_adp or) {return or;}
public DateAdp ReadDate(String key) {return DateAdp_.MinValue;} public DateAdp ReadDateOr(String key, DateAdp or) {return or;}
public gplx.core.ios.streams.Io_stream_rdr ReadRdr(String key) {return gplx.core.ios.streams.Io_stream_rdr_.Noop;}
public boolean MoveNextPeer() {return false;}
public DataRdr Subs() {return this;}
public DataRdr Subs_byName(String name) {return this;}
public DataRdr Subs_byName_moveFirst(String name) {return this;}
public Object StoreRoot(SrlObj root, String key) {return null;}
public boolean SrlBoolOr(String key, boolean v) {return v;}
public byte SrlByteOr(String key, byte v) {return v;}
public int SrlIntOr(String key, int or) {return or;}
public long SrlLongOr(String key, long or) {return or;}
public String SrlStrOr(String key, String or) {return or;}
public DateAdp SrlDateOr(String key, DateAdp or) {return or;}
public Decimal_adp SrlDecimalOr(String key, Decimal_adp or) {return or;}
public double SrlDoubleOr(String key, double or) {return or;}
public Object SrlObjOr(String key, Object or) {return or;}
public void SrlList(String key, List_adp list, SrlObj proto, String itmKey) {}
public void TypeKey_(String v) {}
public void XtoStr_gfml(String_bldr sb) {sb.Add_str_w_crlf("NULL:;");}
public SrlMgr SrlMgr_new(Object o) {return this;}
public void Rls() {}
}
| agpl-3.0 |
kobronson/cs-voltdb | src/frontend/org/voltdb/BackendTarget.java | 1505 | /* This file is part of VoltDB.
* Copyright (C) 2008-2013 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;
/**
* Specifies whether the system should be run on the native C++
* backend for VoltDB, or if the system should use a JDBC
* wrapper around HSQLDB.
*
* HSQLDB is pure java, making the system very portable, and it
* supports a wide range of SQL. On the other hand, it's not as
* fast and only supports a single partition. It's best used
* for testing.
*
*/
public enum BackendTarget {
NATIVE_EE_JNI("jni", false),
NATIVE_EE_IPC("ipc", true),
NATIVE_EE_VALGRIND_IPC("valgrind_ipc", true),
HSQLDB_BACKEND("hsqldb", false),
NONE("none", false);
private BackendTarget(String display, boolean isIPC) { this.display = display; this.isIPC = isIPC; }
public final String display;
public final boolean isIPC;
}
| agpl-3.0 |
opencadc/ac | cadc-access-control-admin/src/main/java/ca/nrc/cadc/ac/admin/ContextImpl.java | 7999 | /*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2011. (c) 2011.
* 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: 5 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.admin;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* A Simple JNDI context.
*/
public class ContextImpl implements Context
{
private final static ConcurrentMap<String,Object> POOL_MAP =
new ConcurrentHashMap<>(1);
@Override
public Object lookup(String name) throws NamingException
{
return POOL_MAP.get(name);
}
@Override
public void bind(String name, Object value) throws NamingException
{
POOL_MAP.put(name, value);
}
@Override
public Object addToEnvironment(String arg0, Object arg1)
throws NamingException
{
return null;
}
@Override
public void bind(Name arg0, Object arg1) throws NamingException
{
}
@Override
public void close() throws NamingException
{
}
@Override
public Name composeName(Name arg0, Name arg1) throws NamingException
{
return null;
}
@Override
public String composeName(String arg0, String arg1)
throws NamingException
{
return null;
}
@Override
public Context createSubcontext(Name arg0) throws NamingException
{
// TODO Auto-generated method stub
return null;
}
@Override
public Context createSubcontext(String arg0) throws NamingException
{
return null;
}
@Override
public void destroySubcontext(Name arg0) throws NamingException
{
}
@Override
public void destroySubcontext(String arg0) throws NamingException
{
// TODO Auto-generated method stub
}
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException
{
return null;
}
@Override
public String getNameInNamespace() throws NamingException
{
return null;
}
@Override
public NameParser getNameParser(Name arg0) throws NamingException
{
return null;
}
@Override
public NameParser getNameParser(String arg0) throws NamingException
{
return null;
}
@Override
public NamingEnumeration<NameClassPair> list(Name arg0)
throws NamingException
{
return null;
}
@Override
public NamingEnumeration<NameClassPair> list(String arg0)
throws NamingException
{
// TODO Auto-generated method stub
return null;
}
@Override
public NamingEnumeration<Binding> listBindings(Name arg0)
throws NamingException
{
return null;
}
@Override
public NamingEnumeration<Binding> listBindings(String arg0)
throws NamingException
{
return null;
}
@Override
public Object lookup(Name arg0) throws NamingException
{
// TODO Auto-generated method stub
return null;
}
@Override
public Object lookupLink(Name arg0) throws NamingException
{
return null;
}
@Override
public Object lookupLink(String arg0) throws NamingException
{
return null;
}
@Override
public void rebind(Name arg0, Object arg1) throws NamingException
{
}
@Override
public void rebind(String arg0, Object arg1) throws NamingException
{
}
@Override
public Object removeFromEnvironment(String arg0) throws NamingException
{
return null;
}
@Override
public void rename(Name arg0, Name arg1) throws NamingException
{
}
@Override
public void rename(String arg0, String arg1) throws NamingException
{
}
@Override
public void unbind(Name arg0) throws NamingException
{
}
@Override
public void unbind(String arg0) throws NamingException
{
}
} | agpl-3.0 |
JDierberger1/JDierberger | src/jlib/datastream/intraprocess/BackgroundDaemon.java | 6700 | package jlib.datastream.intraprocess;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import jlib.datastream.ezio.LineReaderObject;
import jlib.events.Command;
import jlib.utils.e.event.DuplicateCommandException;
import jlib.utils.e.oop.NonUniqueIdentifierException;
/**
* Background Daemon thread that reads user input into the console in a non-blocking daemon thread and takes actions depending on user input.
*
* Commands and command identifiers must be unique. Case sensitivity param cannot be changed after construction. Commands have arguments passed as an Object[] of Strings.
* Input source cannot be changed and commands cannot be added after the daemon is started
*
* @author J-Dierberger
*/
public class BackgroundDaemon<T extends LineReaderObject & Closeable> implements Closeable{
private ArrayList<Command> commands;
private final boolean caseSensitive;
private T reader;
private Thread daemon;
private boolean daemonStarted;
private boolean daemonClosed;
/**
* Create a BackgroundDaemon with the given case-sensitivity param and the given Commands.
*
* @param caseSensitive If Command input is case sensitive.
* @param inputSource The source of input the daemon reads from.
* @param commands The list of Commands this daemon can execute.
*/
public BackgroundDaemon(boolean caseSensitive, T inputSource, Command...commands){
this.caseSensitive = caseSensitive;
ArrayList<String> commandNames = new ArrayList<String>();
// Check for no duplicate names.
for(int i = 0; i < commands.length; i++){
if(!caseSensitive && commandNames.contains(commands[i].getName())){
throw new NonUniqueIdentifierException("Duplicate command "+commands[i].getName());
}else if(caseSensitive && commandNames.contains(commands[i].getName().toLowerCase())){
throw new NonUniqueIdentifierException("Duplicate command "+commands[i].getName().toLowerCase());
}else{
String name = commands[i].getName();
name = _caseCorrect(name);
commandNames.add(name);
}
}
// If we pass the loop without throwing exceptions then we have a valid list of commands.
this.commands = new ArrayList<Command>();
for(Command c : commands){
this.commands.add(c);
}
daemonStarted = false;
daemonClosed = false;
reader = inputSource;
}
/**
* Create a BackgroundDaemon with the given case-sensitivity param.
*
* @param caseSensitive If Command input is case sensitive.
* @param inputSource The source of input the daemon reads from.
*/
public BackgroundDaemon(boolean caseSensitive, T inputSource){
this(caseSensitive, inputSource, new Command[]{});
}
/**
* Create a BackgroundDaemon with the given list of executable Commands. Case sensitivity turned off by default. This cannot be changed after construction.
*
* @param commands The list of Commands this daemon can execute.
* @param inputSource The source of input the daemon reads from.
*/
public BackgroundDaemon(Command[] commands, T inputSource){
this(false, inputSource, new Command[]{});
}
/**
* Create a BackgroundDaemon with the given input source to read from. Case sensitivity is turned off by default. This cannot be changed after construction.
*
* @param inputSource The source of input the daemon reads from.
*/
public BackgroundDaemon(T inputSource){
this(false, inputSource, new Command[]{});
}
/**
* Start the daemon thread.
*/
public void start(){
daemon = new Thread(){
@Override
public void run(){
while(true){
try{
String in = reader.readLine();
String[] fullCommand = in.split(",");
String inputComm = fullCommand[0];
String[] args = new String[fullCommand.length-1];
for(int i = 1; i < fullCommand.length; i++){
args[i-1] = fullCommand[i].trim();
}
inputComm = _caseCorrect(inputComm);
for(Command c : commands){
String commName = c.getName();
commName = _caseCorrect(commName);
if(inputComm.equals(commName)){
c.execute((Object[])args);
break;
}
}
}catch(Throwable e){
e.printStackTrace();
}
}
}
};
daemon.setDaemon(true);
daemon.start();
daemonStarted = true;
}
/**
* Set the input source of the daemon.
*
* @param T The object to read input from. Reads line-by-line.
*/
public void setLineReaderObject(T inputSource){
_checkStarted();
reader = inputSource;
}
/**
* Add a Command to the list of Commands this daemon can execute.
*
* @param c The Command to add.
*/
public void addCommand(Command c){
_checkStarted();
if(commands.contains(c)){
throw new DuplicateCommandException("Command already exists in this daemon's list of commands.");
}
String commName = c.getName();
commName = _caseCorrect(commName);
for(Command comm : commands){
String cName = comm.getName();
cName = _caseCorrect(cName);
if(commName.equals(cName)){
throw new NonUniqueIdentifierException("Duplicate command "+cName);
}
}
commands.add(c);
}
/**
* Remove the given Command from the list of Commands this daemon can execute.
*
* @param c The Command to remove.
*/
public void removeCommand(Command c){
_checkStarted();
commands.remove(c);
}
/**
* Stop the daemon thread.
*
* @throws IOException If closing fails.
*/
public void close() throws IOException{
_checkClosed();
reader.close();
daemon.interrupt();
daemonClosed = true;
}
/**
* Check if the daemon was started.
*
* @return If the daemon was started.
*/
public boolean started(){
return daemonStarted;
}
/**
* Check if the daemon is alive.
*
* @return If the daemon thread is still alive.
*/
public boolean isAlive(){
return daemon.isAlive();
}
/**
* Check if the daemon is closed.
*
* @return If the daemon is closed.
*/
public boolean isClosed(){
return daemonClosed;
}
private void _checkStarted(){
if(daemonStarted){
throw new IllegalStateException("Illegal modification attempted; daemon already started.");
}
}
private void _checkClosed(){
if(!daemonStarted){
throw new IllegalStateException("Daemon not started; cannot close.");
}else if(daemonClosed){
throw new IllegalStateException("Daemon already closed; cannot close again.");
}
}
private String _caseCorrect(String s){
if(!caseSensitive){
return s.toLowerCase();
}else{
return s;
}
}
}
| agpl-3.0 |
RishiGupta12/serial-communication-manager | modules/usb/src/com/serialpundit/usb/SerialComUSB.java | 25769 | /*
* This file is part of SerialPundit.
*
* Copyright (C) 2014-2020, Rishi Gupta. All rights reserved.
*
* The SerialPundit is DUAL LICENSED. It is made available under the terms of the GNU Affero
* General Public License (AGPL) v3.0 for non-commercial use and under the terms of a commercial
* license for commercial use of this software.
*
* The SerialPundit 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 com.serialpundit.usb;
import java.io.IOException;
import com.serialpundit.core.SerialComException;
import com.serialpundit.core.SerialComPlatform;
import com.serialpundit.core.SerialComSystemProperty;
import com.serialpundit.usb.ISerialComUSBHotPlugListener;
import com.serialpundit.usb.internal.SerialComUSBJNIBridge;
/**
* <p>Encapsulates USB related operations and values.</p>
*
* <p>An end product may be based on dedicated USB-UART bridge IC for providing serial over USB or
* may use general purpose microcontroller like PIC18F4550 from Microchip technology Inc. and
* program appropriate firmware (USB CDC) into it to provide UART communication over USB port.</p>
*
* <p>[1] If your USB-UART converter based design is not working, consider not connecting USB connector
* shield directly to ground. Further, double check if termination resistors in D+/D- lines are
* really required or not.</p>
*
* @author Rishi Gupta
*/
public final class SerialComUSB {
/** <p>Value indicating all vendors (vendor neutral operation).</p>*/
public static final int V_ALL = 0x0000;
/** <p>Value indicating vendor - Future technology devices international, Ltd. It manufactures FT232
* USB-UART bridge IC.</p>*/
public static final int V_FTDI = 0x0403;
/** <p>Value indicating vendor - Silicon Laboratories. It manufactures CP2102 USB-UART bridge IC.</p>*/
public static final int V_SLABS = 0x10C4;
/** <p>Value indicating vendor - Microchip technology Inc. It manufactures MCP2200 USB-UART bridge IC.</p>*/
public static final int V_MCHIP = 0x04D8;
/** <p>Value indicating vendor - Prolific technology Inc. It manufactures PL2303 USB-UART bridge IC.</p>*/
public static final int V_PL = 0x067B;
/** <p>Value indicating vendor - Exar corporation. It manufactures XR21V1410 USB-UART bridge IC.</p>*/
public static final int V_EXAR = 0x04E2;
/** <p>Value indicating vendor - Atmel corporation. It manufactures AT90USxxx and other processors which
* can be used as USB-UART bridge.</p>*/
public static final int V_ATML = 0x03EB;
/** <p>Value indicating vendor - MosChip semiconductor. It manufactures MCS7810 USB-UART bridge IC.</p>*/
public static final int V_MOSCHP = 0x9710;
/** <p>Value indicating vendor - Cypress semiconductor corporation. It manufactures CY7C65213 USB-UART
* bridge IC.</p>*/
public static final int V_CYPRS = 0x04B4;
/** <p>Value indicating vendor - Texas instruments, Inc. It manufactures TUSB3410 USB-UART bridge IC.</p>*/
public static final int V_TI = 0x0451;
/** <p>Value indicating vendor - WinChipHead. It manufactures CH340 USB-UART bridge IC.</p>*/
public static final int V_WCH = 0x4348;
/** <p>Value indicating vendor - QinHeng electronics. It manufactures HL-340 converter product.</p>*/
public static final int V_QHE = 0x1A86;
/** <p>Value indicating vendor - NXP semiconductors. It manufactures LPC134x series of microcontrollers.</p>*/
public static final int V_NXP = 0x1FC9;
/** <p>Value indicating vendor - Renesas electronics (NEC electronics). It manufactures μPD78F0730
* microcontroller which can be used as USB-UART converter.</p>*/
public static final int V_RNSAS = 0x0409;
/** <p>The value indicating that the USB device can have any vendor id and product id. </p>*/
public static final int DEV_ANY = 0x00;
/** <p>The value indicating that a USB device has been added into system. </p>*/
public static final int DEV_ADDED = 0x01;
/** <p>The value indicating that a USB device has been removed from system. </p>*/
public static final int DEV_REMOVED = 0x02;
// private stuff
private SerialComPlatform mSerialComPlatform;
private final SerialComSystemProperty mSerialComSystemProperty;
private final Object lockB = new Object();
private static int osType = SerialComPlatform.OS_UNKNOWN;
private static int cpuArch = SerialComPlatform.ARCH_UNKNOWN;
private static int abiType = SerialComPlatform.ABI_UNKNOWN;
private static final Object lockA = new Object();
private static SerialComUSBJNIBridge mUSBJNIBridge;
/**
* <p>Allocates a new SerialComUSB object and load/link native libraries if required.</p>
*
* @param libDirectory absolute path of directory to be used for native library extraction.
* @param loadedLibName library name without extension (do not append .so, .dll or .dylib etc.).
* @throws IOException if native libraries are not found or can not be loaded/linked. If
* appropriate files/directories can not be read or written, If native library can not
* be initialized.
*/
public SerialComUSB(String libDirectory, String loadedLibName) throws IOException {
mSerialComSystemProperty = new SerialComSystemProperty();
synchronized(lockA) {
if(osType <= 0) {
mSerialComPlatform = new SerialComPlatform(mSerialComSystemProperty);
osType = mSerialComPlatform.getOSType();
if(osType == SerialComPlatform.OS_UNKNOWN) {
throw new SerialComException("Could not identify operating system. Please report to us your environemnt so that we can add support for it !");
}
cpuArch = mSerialComPlatform.getCPUArch(osType);
if(cpuArch == SerialComPlatform.ARCH_UNKNOWN) {
throw new SerialComException("Could not identify CPU architecture. Please report to us your environemnt so that we can add support for it !");
}
if((cpuArch == SerialComPlatform.ARCH_ARMV7) || (cpuArch == SerialComPlatform.ARCH_ARMV6) || (cpuArch == SerialComPlatform.ARCH_ARMV5)) {
if(osType == SerialComPlatform.OS_LINUX) {
abiType = mSerialComPlatform.getABIType();
}
}
}
if(mUSBJNIBridge == null) {
mUSBJNIBridge = new SerialComUSBJNIBridge();
SerialComUSBJNIBridge.loadNativeLibrary(libDirectory, loadedLibName, mSerialComSystemProperty, osType, cpuArch, abiType);
mUSBJNIBridge.initNativeLib();
}
}
}
/**
* <p>Returns an array of SerialComUSBdevice class objects containing information about all the USB devices
* found by this library. Application can call various methods on SerialComUSBdevice object to get specific
* information like vendor id and product id etc. The GUI applications may display a dialogue box asking
* user to connect the end product if the desired product is still not connected to system.</p>
*
* <p>The USB vendor id, USB product id, serial number, product name and manufacturer information is
* encapsulated in the object of class SerialComUSBdevice returned.</p>
*
* <p>Some USB-UART chip manufactures may give some unique USB PID(s) to end product manufactures at minimal
* or no cost. Applications written for these end products may be interested in finding devices only from the
* USB-UART chip manufacturer. For example, an application built for finger print scanner based on FT232 IC
* will like to list only those devices whose VID matches VID of FTDI. Then further application may verify
* PID by calling methods on the USBDevice object. For this purpose argument vendorFilter may be used.</p>
*
* @param vendorFilter vendor whose devices should be listed (one of the constants SerialComUSB.V_xxxxx or
* any valid USB VID).
* @return list of the USB devices with information about them or empty array if no device matching given
* criteria found.
* @throws SerialComException if an I/O error occurs.
* @throws IllegalArgumentException if vendorFilter is negative or invalid number.
*/
public SerialComUSBdevice[] listUSBdevicesWithInfo(int vendorFilter) throws SerialComException {
int i = 0;
int numOfDevices = 0;
SerialComUSBdevice[] usbDevicesFound = null;
if((vendorFilter < 0) || (vendorFilter > 0XFFFF)) {
throw new IllegalArgumentException("Argument vendorFilter can not be negative or greater than 0xFFFF !");
}
String[] usbDevicesInfo = mUSBJNIBridge.listUSBdevicesWithInfo(vendorFilter);
if(usbDevicesInfo != null) {
if(usbDevicesInfo.length < 4) {
return new SerialComUSBdevice[] { };
}
numOfDevices = usbDevicesInfo.length / 6;
usbDevicesFound = new SerialComUSBdevice[numOfDevices];
for(int x=0; x<numOfDevices; x++) {
usbDevicesFound[x] = new SerialComUSBdevice(usbDevicesInfo[i], usbDevicesInfo[i+1], usbDevicesInfo[i+2],
usbDevicesInfo[i+3], usbDevicesInfo[i+4], usbDevicesInfo[i+5]);
i = i + 6;
}
return usbDevicesFound;
}else {
throw new SerialComException("Could not find USB devices. Please retry !");
}
}
/**
* <p>This registers a listener who will be invoked whenever a USB device has been plugged or
* un-plugged in system. This method can be used to write auto discovery applications for example
* when a hardware USB device is added to system, application can automatically detect, identify
* it and launches an appropriate service.</p>
*
* <p>This API can be used for detecting both USB-HID and USB-CDC devices. Essentially this API is
* USB interface agnostic; meaning it would invoke listener for matching USB device irresepective of
* functionality offered by the USB device.</p>
*
* <p>Application must implement ISerialComUSBHotPlugListener interface and override onUSBHotPlugEvent method.
* The event value SerialComUSB.DEV_ADDED indicates USB device has been added to the system. The event
* value SerialComUSB.DEV_REMOVED indicates USB device has been removed from system.</p>
*
* <p>Application can specify the usb device for which callback should be called based on USB VID and
* USB PID. If the value of filterVID is specified however the value of filterPID is constant SerialComUSB.DEV_ANY,
* then callback will be called for USB device which matches given VID and its PID can have any value.
* If the value of filterPID is specified however the value of filterVID is constant SerialComUSB.DEV_ANY,
* then callback will be called for USB device which matches given PID and its VID can have any value.</p>
*
* <p>If both filterVID and filterPID are set to SerialComUSB.DEV_ANY, then callback will be called for
* every USB device. Further in listener, USBVID will be 0, if SerialComUSB.DEV_ANY was passed to registerUSBHotPlugEventListener
* for filterVID argument. USBPID will be 0, if SerialComUSB.DEV_ANY was passed to registerUSBHotPlugEventListener for filterPID
* and serialNumber will be empty string if null was passed to registerUSBHotPlugEventListener for serialNumber argument.</p>
*
* <p>If the application do not know the USB attributes like the VID/PID/Serial of the device use listUSBdevicesWithInfo()
* along with hot plug listener. For example; call listUSBdevicesWithInfo(SerialComUSB.V_ALL) and create and arraylist
* to know what all USB devices are present in system and register this hotplug listener. Now whenever a USB device
* is attached to system, listener will be called. From with this listener call listUSBdevicesWithInfo(SerialComUSB.V_ALL)
* and create arraylist again. Compare these two list to find information about newly added device and take next
* appropriate step<p>
*
* @param hotPlugListener object of class which implements ISerialComUSBHotPlugListener interface.
* @param filterVID USB vendor ID to match.
* @param filterPID USB product ID to match.
* @param serialNumber serial number of USB device (case insensitive, optional, can be null) to match.
* @return opaque handle on success that should be passed to unregisterUSBHotPlugEventListener method
* for unregistering this listener.
* @throws SerialComException if registration fails due to some reason.
* @throws IllegalArgumentException if hotPlugListener is null or if USB VID or USB PID are invalid numbers.
*/
public int registerUSBHotPlugEventListener(final ISerialComUSBHotPlugListener hotPlugListener,
int filterVID, int filterPID, String serialNumber) throws SerialComException {
int opaqueHandle = 0;
if(hotPlugListener == null) {
throw new IllegalArgumentException("Argument hotPlugListener can not be null !");
}
if((filterVID < 0) || (filterPID < 0) || (filterVID > 0XFFFF) || (filterPID > 0XFFFF)) {
throw new IllegalArgumentException("USB VID or PID can not be negative number(s) or greater than 0xFFFF !");
}
synchronized(lockB) {
opaqueHandle = mUSBJNIBridge.registerUSBHotPlugEventListener(hotPlugListener, filterVID, filterPID, serialNumber);
if(opaqueHandle < 0) {
throw new SerialComException("Could not register USB device hotplug listener. Please retry !");
}
}
return opaqueHandle;
}
/**
* <p>This unregisters listener and terminate native thread used for monitoring specified USB device
* insertion or removal.</p>
*
* @param opaqueHandle handle returned by registerUSBHotPlugEventListener method for this listener.
* @return true on success.
* @throws SerialComException if un-registration fails due to some reason.
* @throws IllegalArgumentException if argument opaqueHandle is negative.
*/
public boolean unregisterUSBHotPlugEventListener(final int opaqueHandle) throws SerialComException {
int ret = 0;
if(opaqueHandle < 0) {
throw new IllegalArgumentException("Argument opaqueHandle can not be negative !");
}
synchronized(lockB) {
ret = mUSBJNIBridge.unregisterUSBHotPlugEventListener(opaqueHandle);
if(ret < 0) {
throw new SerialComException("Could not un-register USB device hotplug listener. Please retry !");
}
}
return true;
}
/**
* <p>Gives COM port (COMxx/ttySx) of a connected USB-UART device (CDC/ACM Interface) assigned by operating
* system.</p>
*
* <p>Assume a bar code scanner using FTDI chip FT232R is to be used by application at point of sale.
* First we need to know whether it is connect to system or not. This can be done using
* listUSBdevicesWithInfo() or by using USB hot plug listener depending upon application design.</p>
*
* <p>Once it is known that the device is connected to system, we application need to open it. For this,
* application needs to know the COM port number or device node corresponding to the scanner. It is for
* this purpose this method can be used.</p>
*
* <p>Another use case of this API is to align application design with true spirit of USB hot plugging
* in operating system. When a USB-UART device is connected, OS may assign different COM port number or
* device node to the same device depending upon system scenario. Generally we need to write custom udev
* rules so that device node will be same. Using this API this limitation can be overcome.
*
* <p>The reason why this method returns array instead of string is that two or more USB-UART converters
* connected to system might have exactly same USB attributes. So this will list COM ports assigned to all
* of them.<p>
*
* @param usbVidToMatch USB vendor id of the device to match.
* @param usbPidToMatch USB product id of the device to match.
* @param serialNumber USB serial number (case insensitive, optional) of device to match or null if not
* to be matched.
* @return list of COM port(s) (device node) for given USB device or empty array if no COM port is assigned.
* @throws SerialComException if an I/O error occurs.
* @throws IllegalArgumentException if usbVidToMatch or usbPidToMatch is negative or or invalid number.
*/
public String[] findComPortFromUSBAttributes(int usbVidToMatch, int usbPidToMatch, final String serialNumber) throws SerialComException {
if((usbVidToMatch < 0) || (usbVidToMatch > 0XFFFF)) {
throw new IllegalArgumentException("Argument usbVidToMatch can not be negative or greater than 0xFFFF !");
}
if((usbPidToMatch < 0) || (usbPidToMatch > 0XFFFF)) {
throw new IllegalArgumentException("Argument usbPidToMatch can not be negative or greater than 0xFFFF !");
}
String serialNum = null;
if(serialNumber != null) {
serialNum = serialNumber.toLowerCase();
}
String[] comPortsInfo = mUSBJNIBridge.findComPortFromUSBAttribute(usbVidToMatch, usbPidToMatch, serialNum);
if(comPortsInfo == null) {
throw new SerialComException("Could not find COM port for given device. Please retry !");
}
return comPortsInfo;
}
/**
* <p>Gets the USB device firmware revision number as reported by USB device descriptor in its
* device descriptor using bcdDevice field.</p>
*
* <p>Application can get this firmware revision number and can self adopt to a particular hardware
* device. For example if a particular feature is present in firmware version 1.00 than application
* create a button in GUI, however for revision 1.11 it creates a different button in GUI window.</p>
*
* <p>Embedded system device vendors sometimes use bcdDevice value to indicate the 'embedded bootloader'
* version so that the firmware image flash loader program can identify the bootloader in use and use the
* appropriate protocol to flash firmware in flash memory. Typically, USB Device Firmware Upgrade (DFU)
* which is an official USB device class specification of the USB Implementers Forum is used.</p>
*
* <p>On custom hardware the RTS and DTR pins of USB-UART device can be used to control GPIO or boot mode
* pins to enter a particular boot mode. For example, open the host serial port, make DTR low and RTS high
* and then reset microcontroller board. The microcontroller will see levels at its boot pins and will
* enter into a particular boot mode.</p>
*
* @param usbvid USB vendor ID to match.
* @param usbpid USB product ID to match.
* @param serialNumber serial number of USB device (case insensitive, optional) to match.
* @return firmware number revision string on success.
* @throws SerialComException if an I/O error occurs.
*/
public String[] getFirmwareRevisionNumber(int usbvid, int usbpid, String serialNumber) throws SerialComException {
if((usbvid < 0) || (usbvid > 0XFFFF)) {
throw new IllegalArgumentException("Argument usbvid can not be negative or greater than 0xFFFF !");
}
if((usbpid < 0) || (usbpid > 0XFFFF)) {
throw new IllegalArgumentException("Argument usbpid can not be negative or greater than 0xFFFF !");
}
String serial = null;
if(serialNumber != null) {
serial = serialNumber.trim().toLowerCase();
}
String[] bcdCodedRevNumber = mUSBJNIBridge.getFirmwareRevisionNumber(usbvid, usbpid, serial);
if(bcdCodedRevNumber == null) {
throw new SerialComException("Could not get the bcdDevice field of USB device descriptor. Please retry !");
}
String[] fwver = new String[bcdCodedRevNumber.length];
int firmwareRevisionNum;
for(int x=0; x < bcdCodedRevNumber.length; x++) {
firmwareRevisionNum = Integer.parseInt(bcdCodedRevNumber[x]);
fwver[x] = String.format("%x.%02x", (firmwareRevisionNum & 0xFF00) >> 8, firmwareRevisionNum & 0x00FF);
}
return fwver;
}
/**
* <p>Read all the power management related information about a particular USB device. The returned
* instance of SerialComUSBPowerInfo class contains information about auto suspend, selective suspend,
* current power status etc.</p>
*
*
* @param comPort serial port name/path (COMxx, /dev/ttyUSBx) which is associated with a particular
* USB CDC/ACM interface in the USB device to be analyzed for power management.
* @return an instance of SerialComUSBPowerInfo class containing operating system and device specific
* information about power management or null if given COM port does not belong to a USB
* device.
* @throws SerialComException if an I/O error occurs.
*/
public SerialComUSBPowerInfo getCDCUSBDevPowerInfo(String comPort) throws SerialComException {
if(comPort == null) {
throw new IllegalArgumentException("Argument comPort can not be null !");
}
String portNameVal = comPort.trim();
if(portNameVal.length() == 0) {
throw new IllegalArgumentException("Argument comPort can not be empty string !");
}
String[] usbPowerInfo = mUSBJNIBridge.getCDCUSBDevPowerInfo(portNameVal);
if(usbPowerInfo != null) {
if(usbPowerInfo.length > 2) {
return new SerialComUSBPowerInfo(usbPowerInfo[0], usbPowerInfo[1], usbPowerInfo[2],
usbPowerInfo[3], usbPowerInfo[4], usbPowerInfo[5]);
}
}else {
throw new SerialComException("Could not find USB devices. Please retry !");
}
return null;
}
/**
* <p>Sets the latency timer value for FTDI devices. When using FTDI USB-UART devices, optimal values
* of latency timer and read/write block size may be required to obtain optimal data throughput.</p>
*
* <p>Note that built-in drivers in Linux kernel image may not allow changing timer values as it may have
* been hard-coded. Drivers supplied by FTDI at their website should be used if changing latency timer
* values is required by application.</p>
*
* @return true on success.
* @throws SerialComException if an I/O error occurs.
*/
public boolean setLatencyTimer(String comPort, byte timerValue) throws SerialComException {
int ret = mUSBJNIBridge.setLatencyTimer(comPort, timerValue);
if(ret < 0) {
throw new SerialComException("Could not set the latency timer value. Please retry !");
}
return true;
}
/**
* <p>Gets the current latency timer value for FTDI devices.</p>
*
* @return current latency timer value.
* @throws SerialComException if an I/O error occurs.
*/
public int getLatencyTimer(String comPort) throws SerialComException {
int value = mUSBJNIBridge.getLatencyTimer(comPort);
if(value < 0) {
throw new SerialComException("Could not get the latency timer value. Please retry !");
}
return value;
}
/**
* <p>Checks whether a particular USB device identified by vendor id, product id and serial number is
* connected to the system or not. The connection information is obtained from the operating system.</p>
*
* @param vendorID USB-IF vendor ID of the USB device to match.
* @param productID product ID of the USB device to match.
* @param serialNumber USB device's serial number (case insensitive, optional). If not required it can be null.
* @return true is device is connected otherwise false.
* @throws SerialComException if an I/O error occurs.
* @throws IllegalArgumentException if productID or vendorID is negative or invalid.
*/
public boolean isUSBDevConnected(int vendorID, int productID, String serialNumber) throws SerialComException {
if((vendorID < 0) || (vendorID > 0XFFFF)) {
throw new IllegalArgumentException("Argument vendorID can not be negative or greater than 0xFFFF !");
}
if((productID < 0) || (productID > 0XFFFF)) {
throw new IllegalArgumentException("Argument productID can not be negative or greater than 0xFFFF !");
}
int ret = mUSBJNIBridge.isUSBDevConnected(vendorID, productID, serialNumber);
if(ret < 0) {
throw new SerialComException("Unknown error occurred !");
}else if(ret == 1) {
return true;
}
return false;
}
/**
* <p>Returns an instance of class SerialComUSBHID for HID over USB operations.</p>
*
* @return an instance of SerialComUSBHID.
* @throws SerialComException if operation can not be completed successfully.
*/
public SerialComUSBHID getUSBHIDTransportInstance() throws SerialComException {
return new SerialComUSBHID(mUSBJNIBridge);
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_bbs_assemble_control/src/main/java/com/x/bbs/assemble/control/jaxrs/replyinfo/exception/ExceptionReplySubjectIdEmpty.java | 364 | package com.x.bbs.assemble.control.jaxrs.replyinfo.exception;
import com.x.base.core.project.exception.PromptException;
public class ExceptionReplySubjectIdEmpty extends PromptException {
private static final long serialVersionUID = 1859164370743532895L;
public ExceptionReplySubjectIdEmpty() {
super("主题ID为空,无法继续查询操作。" );
}
}
| agpl-3.0 |
acontes/programming | src/Extensions/org/objectweb/proactive/extensions/mixedlocation/UniversalBodyWrapper.java | 10651 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.extensions.mixedlocation;
import java.io.IOException;
import java.security.AccessControlException;
import java.security.PublicKey;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.UniqueID;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.ft.internalmsg.FTMessage;
import org.objectweb.proactive.core.body.reply.Reply;
import org.objectweb.proactive.core.body.request.Request;
import org.objectweb.proactive.core.component.request.Shortcut;
import org.objectweb.proactive.core.gc.GCMessage;
import org.objectweb.proactive.core.gc.GCResponse;
import org.objectweb.proactive.core.security.PolicyServer;
import org.objectweb.proactive.core.security.ProActiveSecurityManager;
import org.objectweb.proactive.core.security.SecurityContext;
import org.objectweb.proactive.core.security.TypedCertificate;
import org.objectweb.proactive.core.security.crypto.KeyExchangeException;
import org.objectweb.proactive.core.security.crypto.SessionException;
import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException;
import org.objectweb.proactive.core.security.exceptions.SecurityNotAvailableException;
import org.objectweb.proactive.core.security.securityentity.Entities;
import org.objectweb.proactive.core.security.securityentity.Entity;
public class UniversalBodyWrapper implements UniversalBody, Runnable {
/**
*
*/
protected UniversalBody wrappedBody;
protected long time;
protected UniqueID id;
protected boolean stop;
protected long creationTime;
//protected Thread t ;
/**
* Create a time-limited wrapper around a UniversalBody
* @param body the wrapped UniversalBody
* @param time the life expectancy of this wrapper in milliseconds
*/
public UniversalBodyWrapper(UniversalBody body, long time) {
this.wrappedBody = body;
this.time = time;
this.creationTime = System.currentTimeMillis();
// t =new Thread(this);
this.id = this.wrappedBody.getID();
// t.start();
}
public int receiveRequest(Request request) throws IOException, RenegotiateSessionException {
// System.out.println("UniversalBodyWrapper.receiveRequest");
if (this.wrappedBody == null) {
throw new IOException();
}
//the forwarder should be dead
if (System.currentTimeMillis() > (this.creationTime + this.time)) {
// this.updateServer();
// this.wrappedBody = null;
// t.start();
// System.gc();
throw new IOException();
} else {
try {
return this.wrappedBody.receiveRequest(request);
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
// this.stop();
}
public int receiveReply(Reply r) throws IOException {
return this.wrappedBody.receiveReply(r);
}
public String getNodeURL() {
return this.wrappedBody.getNodeURL();
}
public UniqueID getID() {
return this.id;
}
public void updateLocation(UniqueID id, UniversalBody body) throws IOException {
this.wrappedBody.updateLocation(id, body);
}
public UniversalBody getRemoteAdapter() {
return this.wrappedBody.getRemoteAdapter();
}
public String getReifiedClassName() {
return this.wrappedBody.getReifiedClassName();
}
public void enableAC() throws java.io.IOException {
this.wrappedBody.enableAC();
}
public void disableAC() throws java.io.IOException {
this.wrappedBody.disableAC();
}
protected void updateServer() {
// System.out.println("UniversalBodyWrapper.updateServer");
// LocationServer server = LocationServerFactory.getLocationServer();
// try {
// server.updateLocation(id, this.wrappedBody);
// } catch (Exception e) {
// System.out.println("XXXX Error XXXX");
// // e.printStackTrace();
// }
}
//protected synchronized void stop() {
// this.stop=true;
// this.notifyAll();
//}
//
//protected synchronized void waitForStop(long time) {
// if (!this.stop) {
// try {
// wait(time);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
//}
public void run() {
// System.out.println("UniversalBodyWrapper.run life expectancy " + time);
try {
// Thread.currentThread().sleep(time);
// this.waitForStop(time);
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println("UniversalBodyWrapper.run end of life...");
this.updateServer();
this.wrappedBody = null;
// System.gc();
}
// SECURITY
public void terminateSession(long sessionID) throws java.io.IOException, SecurityNotAvailableException {
this.wrappedBody.terminateSession(sessionID);
}
public TypedCertificate getCertificate() throws java.io.IOException, SecurityNotAvailableException {
return this.wrappedBody.getCertificate();
}
public long startNewSession(long distantSessionID, SecurityContext policy,
TypedCertificate distantCertificate) throws IOException, SecurityNotAvailableException,
SessionException {
return this.wrappedBody.startNewSession(distantSessionID, policy, distantCertificate);
}
public PublicKey getPublicKey() throws java.io.IOException, SecurityNotAvailableException {
return this.wrappedBody.getPublicKey();
}
public byte[] randomValue(long sessionID, byte[] cl_rand) throws IOException,
SecurityNotAvailableException, RenegotiateSessionException {
return this.wrappedBody.randomValue(sessionID, cl_rand);
}
public byte[] publicKeyExchange(long sessionID, byte[] sig_code) throws IOException,
SecurityNotAvailableException, RenegotiateSessionException, KeyExchangeException {
return this.wrappedBody.publicKeyExchange(sessionID, sig_code);
}
public byte[][] secretKeyExchange(long sessionID, byte[] tmp, byte[] tmp1, byte[] tmp2, byte[] tmp3,
byte[] tmp4) throws IOException, SecurityNotAvailableException, RenegotiateSessionException {
return this.wrappedBody.secretKeyExchange(sessionID, tmp, tmp1, tmp2, tmp3, tmp4);
}
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.body.UniversalBody#getCertificateEncoded()
// */
// public byte[] getCertificateEncoded()
// throws IOException, SecurityNotAvailableException {
// return this.wrappedBody.getCertificateEncoded();
// }
/* (non-Javadoc)
* @see org.objectweb.proactive.core.body.UniversalBody#getPolicy(org.objectweb.proactive.ext.security.SecurityContext)
*/
public SecurityContext getPolicy(Entities local, Entities distant) throws SecurityNotAvailableException,
IOException {
return this.wrappedBody.getPolicy(local, distant);
}
public Entities getEntities() throws SecurityNotAvailableException, IOException {
return this.wrappedBody.getEntities();
}
/**
* @see org.objectweb.proactive.core.body.UniversalBody#receiveFTMessage(org.objectweb.proactive.core.body.ft.internalmsg.FTMessage)
*/
public Object receiveFTMessage(FTMessage ev) throws IOException {
return this.wrappedBody.receiveFTMessage(ev);
}
public GCResponse receiveGCMessage(GCMessage msg) throws IOException {
return this.wrappedBody.receiveGCMessage(msg);
}
public void setRegistered(boolean registered) throws IOException {
this.wrappedBody.setRegistered(registered);
}
public void createShortcut(Shortcut shortcut) throws IOException {
// TODO implement
throw new ProActiveRuntimeException("create shortcut method not implemented yet");
}
public String registerByName(String name, boolean rebind) throws IOException, ProActiveException {
return this.wrappedBody.registerByName(name, rebind);
}
public String registerByName(String name, boolean rebind, String protocol) throws IOException,
ProActiveException {
return this.wrappedBody.registerByName(name, rebind, protocol);
}
public ProActiveSecurityManager getProActiveSecurityManager(Entity user)
throws SecurityNotAvailableException, AccessControlException, IOException {
return this.wrappedBody.getProActiveSecurityManager(user);
}
public void setProActiveSecurityManager(Entity user, PolicyServer policyServer)
throws SecurityNotAvailableException, AccessControlException, IOException {
this.wrappedBody.setProActiveSecurityManager(user, policyServer);
}
public String getUrl() {
return this.wrappedBody.getUrl();
}
}
| agpl-3.0 |
ik4tekniker/FISTAR-Health-Questionnaire-SE | HQSE_code/HQSE_WebServices_Code_BETA/commons.mng.bo/src/main/java/es/tekniker/framework/ktek/entity/KtekLoginEntity.java | 3255 | /*
*
* Copyright 2015 IK4-Tekniker All Rights Reserved
*
* This file is part of Health Questionnaire SE at FISTAR https://www.fi-star.eu/
*
* Health Questionnaire SE 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.
*
* Health Questionnaire SE 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 Health Questionnaire SE. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* patricia.casla at tekniker dot es
*
* Author: Ignacio Lazaro Llorente
*/
package es.tekniker.framework.ktek.entity;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/*
* Class used as input parameter on login service
*/
@XmlRootElement(name = "KtekLoginEntity")
@XmlType(
namespace = "http://es.tekniker.framework.ktek",
propOrder = {"reference", "password", "coordinates"})
public class KtekLoginEntity implements Serializable{
private String reference;
private String password;
private KtekLoginCoordinatesEntity[] coordinates;
public boolean isRequiredDataDefined(){
boolean boolOK=true;
if(reference.equals(""))
boolOK=false;
if(password.equals(""))
boolOK=false;
if(coordinates == null)
boolOK=false;
if(coordinates.length !=3)
boolOK=false;
if(coordinates[0].getLetter()==null && coordinates[0].getLetter().equals(""))
boolOK=false;
if(coordinates[0].getValue()==null && coordinates[0].getValue().equals(""))
boolOK=false;
if(coordinates[1].getLetter()==null && coordinates[1].getLetter().equals(""))
boolOK=false;
if(coordinates[1].getValue()==null && coordinates[1].getValue().equals(""))
boolOK=false;
if(coordinates[2].getLetter()==null && coordinates[2].getLetter().equals(""))
boolOK=false;
if(coordinates[2].getValue()==null && coordinates[2].getValue().equals(""))
boolOK=false;
return boolOK;
}
/**
* @return the reference
*/
public String getReference() {
return reference;
}
/**
* @param reference the reference to set
*/
public void setReference(String reference) {
this.reference = reference;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the coordinates
*/
public KtekLoginCoordinatesEntity[] getCoordinates() {
return coordinates;
}
/**
* @param coordinates the coordinates to set
*/
public void setCoordinates(KtekLoginCoordinatesEntity[] coordinates) {
this.coordinates = coordinates;
}
public String toString(){
String sData="reference:" + reference + " password:" + password ;
return sData;
}
}
| agpl-3.0 |
perzyje/prog-training-oct2012 | day15/src/main/java/com/codingbat/String2.java | 8849 | package com.codingbat;
public final class String2 {
/*
* http://codingbat.com/prob/p165312
*
* Given a string, return a string where for every char in the original,
* there are two chars.
*
* doubleChar("The") → "TThhee"
*
* doubleChar("AAbb") → "AAAAbbbb"
*
* doubleChar("Hi-There") → "HHii--TThheerree"
*/
public String doubleChar(String str) {
return null;
}
/*
* http://codingbat.com/prob/p147448
*
* Return the number of times that the string "hi" appears anywhere in the
* given string.
*
* countHi("abc hi ho") → 1
*
* countHi("ABChi hi") → 2
*
* countHi("hihi") → 2
*/
public int countHi(String str) {
return 0;
}
/*
* http://codingbat.com/prob/p111624
*
* Return true if the string "cat" and "dog" appear the same number of times
* in the given string.
*
* catDog("catdog") → true
*
* catDog("catcat") → false
*
* catDog("1cat1cadodog") → true
*/
public boolean catDog(String str) {
return false;
}
/*
* http://codingbat.com/prob/p123614
*
* Return the number of times that the string "code" appears anywhere in the
* given string, except we'll accept any letter for the 'd', so "cope" and
* "cooe" count.
*
* countCode("aaacodebbb") → 1
*
* countCode("codexxcode") → 2
*
* countCode("cozexxcope") → 2
*/
public int countCode(String str) {
return 0;
}
/*
* http://codingbat.com/prob/p126880
*
* Given two strings, return true if either of the strings appears at the
* very end of the other string, ignoring upper/lower case differences (in
* other words, the computation should not be "case sensitive"). Note:
* str.toLowerCase() returns the lowercase version of a string.
*
* endOther("Hiabc", "abc") → true
*
* endOther("AbC", "HiaBc") → true
*
* endOther("abc", "abXabc") → true
*/
public boolean endOther(String a, String b) {
return false;
}
/*
* http://codingbat.com/prob/p136594
*
* Return true if the given string contains an appearance of "xyz" where the
* xyz is not directly preceeded by a period (.). So "xxyz" counts but
* "x.xyz" does not.
*
* xyzThere("abcxyz") → true
*
* xyzThere("abc.xyz") → false
*
* xyzThere("xyz.abc") → true
*/
public boolean xyzThere(String str) {
return false;
}
/*
* http://codingbat.com/prob/p175762
*
* Return true if the given string contains a "bob" string, but where the
* middle 'o' char can be any char.
*
* bobThere("abcbob") → true
*
* bobThere("b9b") → true
*
* bobThere("bac") → false
*/
public boolean bobThere(String str) {
return false;
}
/*
* http://codingbat.com/prob/p134250
*
* We'll say that a String is xy-balanced if for all the 'x' chars in the
* string, there exists a 'y' char somewhere later in the string. So "xxy"
* is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return
* true if the given string is xy-balanced.
*
* xyBalance("aaxbby") → true
*
* xyBalance("aaxbb") → false
*
* xyBalance("yaaxbb") → false
*/
public boolean xyBalance(String str) {
return false;
}
/*
* http://codingbat.com/prob/p125185
*
* Given two strings, A and B, create a bigger string made of the first char
* of A, the first char of B, the second char of A, the second char of B,
* and so on. Any leftover chars go at the end of the result.
*
* mixString("abc", "xyz") → "axbycz"
*
* mixString("Hi", "There") → "HTihere"
*
* mixString("xxxx", "There") → "xTxhxexre"
*/
public String mixString(String a, String b) {
return null;
}
/*
* http://codingbat.com/prob/p152339
*
* Given a string and an int N, return a string made of N repetitions of the
* last N characters of the string. You may assume that N is between 0 and
* the length of the string, inclusive.
*
* repeatEnd("Hello", 3) → "llollollo"
*
* repeatEnd("Hello", 2) → "lolo"
*
* repeatEnd("Hello", 1) → "o"
*/
public String repeatEnd(String str, int n) {
return null;
}
/*
* http://codingbat.com/prob/p128796
*
* Given a string and an int n, return a string made of the first n
* characters of the string, followed by the first n-1 characters of the
* string, and so on. You may assume that n is between 0 and the length of
* the string, inclusive (i.e. n >= 0 and n <= str.length()).
*
* repeatFront("Chocolate", 4) → "ChocChoChC"
*
* repeatFront("Chocolate", 3) → "ChoChC"
*
* repeatFront("Ice Cream", 2) → "IcI"
*/
public String repeatFront(String str, int n) {
return null;
}
/*
* http://codingbat.com/prob/p109637
*
* Given two strings, word and a separator, return a big string made of
* count occurences of the word, separated by the separator string.
*
* repeatSeparator("Word", "X", 3) → "WordXWordXWord"
*
* repeatSeparator("This", "And", 2) → "ThisAndThis"
*
* repeatSeparator("This", "And", 1) → "This"
*/
public String repeatSeparator(String word, String sep, int count) {
return null;
}
/*
* http://codingbat.com/prob/p136417
*
* Given a string, consider the prefix string made of the first N chars of
* the string. Does that prefix string appear somewhere else in the string?
* Assume that the string is not empty and that N is in the range
* 1..str.length().
*
* prefixAgai("abXYabc", 1) → true
*
* prefixAgain("abXYabc", 2) → true
*
* prefixAgain("abXYabc", 3) → false
*/
public boolean prefixAgain(String str, int n) {
return false;
}
/*
* http://codingbat.com/prob/p159772
*
* Given a string, does "xyz" appear in the middle of the string? To define
* middle, we'll say that the number of chars to the left and right of the
* "xyz" must differ by at most one. This problem is harder than it looks.
*
* xyzMiddle("AAxyzBB") → true
*
* xyzMiddle("AxyzBB") → true
*
* xyzMiddle("AxyzBBB") → false
*/
public boolean xyzMiddle(String str) {
return false;
}
/*
* http://codingbat.com/prob/p129952
*
* A sandwich is two pieces of bread with something in between. Return the
* string that is between the first and last appearance of "bread" in the
* given string, or return the empty string "" if there are not two pieces
* of bread.
*
* getSandwich("breadjambread") → "jam"
*
* getSandwich("xxbreadjambreadyy") → "jam"
*
* getSandwich("xxbreadyy") → ""
*/
public String getSandwich(String str) {
return null;
}
/*
* http://codingbat.com/prob/p194491
*
* Returns true if for every '*' (star) in the string, if there are chars
* both immediately before and after the star, they are the same.
*
* sameStarChar("xy*yzz") → true
*
* sameStarChar("xy*zzz") → false
*
* sameStarChar("*xa*az") → true
*/
public boolean sameStarChar(String str) {
return false;
}
/*
* http://codingbat.com/prob/p180759
*
* Look for patterns like "zip" and "zap" in the string -- length-3,
* starting with 'z' and ending with 'p'. Return a string where for all such
* words, the middle letter is gone, so "zipXzap" yields "zpXzp".
*
* zipZap("zipXzap") → "zpXzp"
*
* zipZap("zopzop") → "zpzp"
*
* zipZap("zzzopzop") → "zzzpzp"
*/
public String zipZap(String str) {
return null;
}
/*
* http://codingbat.com/prob/p139564
*
* Return a version of the given string, where for every star (*) in the
* string the star and the chars immediately to its left and right are gone.
* So "ab*cd" yields "ad" and "ab**cd" also yields "ad".
*
* starOut("ab*cd") → "ad"
*
* starOut("ab**cd") → "ad"
*
* starOut("sm*eilly") → "silly"
*/
public String starOut(String str) {
return null;
}
/*
* http://codingbat.com/prob/p170829
*
* Given a string and a non-empty word string, return a version of the
* original String where all chars have been replaced by pluses ("+"),
* except for appearances of the word string which are preserved unchanged.
*
* plusOut("12xy34", "xy") → "++xy++"
*
* plusOut("12xy34", "1") → "1+++++"
*
* plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"
*/
public String plusOut(String str, String word) {
return null;
}
/*
* http://codingbat.com/prob/p147538
*
* Given a string and a non-empty word string, return a string made of each
* char just before and just after every appearance of the word in the
* string. Ignore cases where there is no char before or after the word, and
* a char may be included twice if it is between two words.
*
* wordEnds("abcXY123XYijk", "XY") → "c13i"
*
* wordEnds("XY123XY", "XY") → "13"
*
* wordEnds("XY1XY", "XY") → "11"
*/
public String wordEnds(String str, String word) {
return null;
}
}
| agpl-3.0 |
tis-innovation-park/carsharing-ds | src/main/java/it/bz/tis/integreen/carsharingbzit/ConnectorLogic.java | 14481 | /*
carsharing-ds: car sharing datasource for the integreen cloud
Copyright (C) 2015 TIS Innovation Park - Bolzano/Bozen - Italy
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 it.bz.tis.integreen.carsharingbzit;
import it.bz.idm.bdp.dto.DataTypeDto;
import it.bz.idm.bdp.dto.SimpleRecordDto;
import it.bz.idm.bdp.dto.TypeMapDto;
import it.bz.idm.bdp.dto.carsharing.CarsharingStationDto;
import it.bz.idm.bdp.dto.carsharing.CarsharingVehicleDto;
import it.bz.tis.integreen.carsharingbzit.api.ApiClient;
import it.bz.tis.integreen.carsharingbzit.api.BoundingBox;
import it.bz.tis.integreen.carsharingbzit.api.GetStationRequest;
import it.bz.tis.integreen.carsharingbzit.api.GetStationResponse;
import it.bz.tis.integreen.carsharingbzit.api.GetVehicleRequest;
import it.bz.tis.integreen.carsharingbzit.api.GetVehicleResponse;
import it.bz.tis.integreen.carsharingbzit.api.ListStationByBoundingBoxRequest;
import it.bz.tis.integreen.carsharingbzit.api.ListStationsByCityRequest;
import it.bz.tis.integreen.carsharingbzit.api.ListStationsByCityResponse;
import it.bz.tis.integreen.carsharingbzit.api.ListVehicleOccupancyByStationRequest;
import it.bz.tis.integreen.carsharingbzit.api.ListVehicleOccupancyByStationResponse;
import it.bz.tis.integreen.carsharingbzit.api.ListVehicleOccupancyByStationResponse.VehicleAndOccupancies;
import it.bz.tis.integreen.carsharingbzit.api.ListVehiclesByStationsRequest;
import it.bz.tis.integreen.carsharingbzit.api.ListVehiclesByStationsResponse;
import it.bz.tis.integreen.carsharingbzit.api.ListVehiclesByStationsResponse.StationAndVehicles;
import it.bz.tis.integreen.carsharingbzit.tis.IXMLRPCPusher;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import it.bz.idm.bdp.util.IntegreenException;
/**
*
* @author Davide Montesin <d@vide.bz>
*/
public class ConnectorLogic
{
final static long INTERVALL = 10L * 60L * 1000L;
public static final String CARSHARINGSTATION_DATASOURCE = "Carsharingstation";
public static final String CARSHARINGCAR_DATASOURCE = "Carsharingcar";
static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); // 2014-09-15T12:00:00
static HashMap<String, String[]> process(ApiClient apiClient,
String[] cityUIDs,
IXMLRPCPusher xmlrpcPusher,
HashMap<String, String[]> vehicleIdsByStationIds,
long updateTime,
ActivityLog activityLog,
ArrayList<ActivityLog> lock) throws IOException
{
if (vehicleIdsByStationIds == null) // Do a full sync
{
vehicleIdsByStationIds = processSyncStations(apiClient, cityUIDs, xmlrpcPusher, activityLog, lock);
}
processPusDatas(apiClient, xmlrpcPusher, vehicleIdsByStationIds, updateTime, activityLog, lock);
return vehicleIdsByStationIds;
}
static HashMap<String, String[]> processSyncStations(ApiClient apiClient,
String[] cityUIDs,
IXMLRPCPusher xmlrpcPusher,
ActivityLog activityLog,
ArrayList<ActivityLog> lock) throws IOException
{
///////////////////////////////////////////////////////////////
// Stations by city
///////////////////////////////////////////////////////////////
// ListStationsByCityRequest request = new ListStationsByCityRequest(cityUIDs);
// ListStationsByCityResponse response = apiClient.callWebService(request, ListStationsByCityResponse.class);
// CarsharingStationDto[] stations = response.getCityAndStations()[0].getStation();
///////////////////////////////////////////////////////////////
// Stations by Bounding Box
///////////////////////////////////////////////////////////////
List<BoundingBox> boxes = new ArrayList<BoundingBox>();
boxes.add(new BoundingBox(10.375214,46.459147,11.059799,46.86113));
boxes.add(new BoundingBox(11.015081,46.450277,11.555557,46.765265));
boxes.add(new BoundingBox(11.458354,46.533418,11.99883,46.847924));
boxes.add(new BoundingBox(11.166573,46.218327,11.521568,46.455303));
boxes.add(new BoundingBox(11.092758,46.794448,11.797256,47.018653));
boxes.add(new BoundingBox(11.959305,46.598506,12.423477,47.098175));
Set<String> stationSet = new HashSet<String>();
for (BoundingBox box:boxes){
ListStationByBoundingBoxRequest request = new ListStationByBoundingBoxRequest(box);
ListStationsByBoundingBoxResponse response = apiClient.callWebService(request, ListStationsByBoundingBoxResponse.class);
if (response != null){
CarsharingStationDto[] stations = response.getStation();
for (int i = 0; i < stations.length; i++)
{
stationSet.add(stations[i].getId());
}
}
}
///////////////////////////////////////////////////////////////
// Stations details
///////////////////////////////////////////////////////////////
String[] stationIds = stationSet.toArray(new String[stationSet.size()]);
GetStationRequest requestGetStation = new GetStationRequest(stationIds);
GetStationResponse responseGetStation = apiClient.callWebService(requestGetStation, GetStationResponse.class);
///////////////////////////////////////////////////////////////
// Vehicles by stations
///////////////////////////////////////////////////////////////
ListVehiclesByStationsRequest vehicles = new ListVehiclesByStationsRequest(stationIds);
ListVehiclesByStationsResponse responseVehicles = apiClient.callWebService(vehicles,
ListVehiclesByStationsResponse.class);
///////////////////////////////////////////////////////////////
// Vehicles details
///////////////////////////////////////////////////////////////
HashMap<String, String[]> vehicleIdsByStationIds = new HashMap<>();
ArrayList<String> veichleIds = new ArrayList<String>();
for (StationAndVehicles stationVehicles : responseVehicles.getStationAndVehicles())
{
String[] vehicleIds = new String[stationVehicles.getVehicle().length];
vehicleIdsByStationIds.put(stationVehicles.getStation().getId(), vehicleIds);
for (int i = 0; i < stationVehicles.getVehicle().length; i++)
{
CarsharingVehicleDto carsharingVehicleDto = stationVehicles.getVehicle()[i];
veichleIds.add(carsharingVehicleDto.getId());
vehicleIds[i] = carsharingVehicleDto.getId();
}
}
GetVehicleRequest requestVehicleDetails = new GetVehicleRequest(veichleIds.toArray(new String[0]));
GetVehicleResponse responseVehicleDetails = apiClient.callWebService(requestVehicleDetails,
GetVehicleResponse.class);
///////////////////////////////////////////////////////////////
// Write data to integreen
///////////////////////////////////////////////////////////////
Object result = xmlrpcPusher.syncStations(CARSHARINGSTATION_DATASOURCE, responseGetStation.getStation());
if (result instanceof IntegreenException)
{
throw new IOException("IntegreenException");
}
synchronized (lock)
{
activityLog.report += "syncStations("
+ CARSHARINGSTATION_DATASOURCE
+ "): "
+ responseGetStation.getStation().length
+ "\n";
}
result = xmlrpcPusher.syncStations(CARSHARINGCAR_DATASOURCE, responseVehicleDetails.getVehicle());
if (result instanceof IntegreenException)
{
throw new IOException("IntegreenException");
}
synchronized (lock)
{
activityLog.report += "syncStations("
+ CARSHARINGCAR_DATASOURCE
+ "): "
+ responseVehicleDetails.getVehicle().length
+ "\n";
}
return vehicleIdsByStationIds;
}
static void processPusDatas(ApiClient apiClient,
IXMLRPCPusher xmlrpcPusher,
HashMap<String, String[]> vehicleIdsByStationIds,
long updateTime,
ActivityLog activityLog,
ArrayList<ActivityLog> lock) throws IOException
{
///////////////////////////////////////////////////////////////
// Read vehicles occupancy and calculate summaries
///////////////////////////////////////////////////////////////
String created = String.valueOf(updateTime);
// Current and forecast
for (long forecast : new long[] { 0, 30L * 60L * 1000L })
{
String begin = String.valueOf(updateTime + forecast);
// TODO begin buffer depends on car type
String begin_carsharing = SIMPLE_DATE_FORMAT.format(new Date(updateTime - 30L * 60L * 1000L + forecast));
String end = SIMPLE_DATE_FORMAT.format(new Date(updateTime + INTERVALL + forecast));
String[] stationIds = vehicleIdsByStationIds.keySet().toArray(new String[0]);
Arrays.sort(stationIds);
HashMap<String, TypeMapDto> stationData = new HashMap<String, TypeMapDto>();
HashMap<String, TypeMapDto> vehicleData = new HashMap<String, TypeMapDto>();
for (String stationId : stationIds)
{
String[] vehicleIds = vehicleIdsByStationIds.get(stationId);
ListVehicleOccupancyByStationRequest occupancyByStationRequest = new ListVehicleOccupancyByStationRequest(begin_carsharing,
end,
stationId,
vehicleIds);
ListVehicleOccupancyByStationResponse responseOccupancy = apiClient.callWebService(occupancyByStationRequest,
ListVehicleOccupancyByStationResponse.class);
VehicleAndOccupancies[] occupancies = responseOccupancy.getVehicleAndOccupancies();
if (occupancies== null)
continue;
if (occupancies.length != vehicleIds.length) // Same number of responses as the number to requests
{
throw new IllegalStateException();
}
int free = 0;
for (VehicleAndOccupancies vehicleOccupancy : occupancies)
{
if (vehicleOccupancy.getOccupancy().length > 1)
{
throw new IllegalStateException("Why???");
}
int state = 0; // free
if (vehicleOccupancy.getOccupancy().length == 1)
{
state = 1;
}
else
{
free++;
}
TypeMapDto typeMap = new TypeMapDto();
vehicleData.put(vehicleOccupancy.getVehicle().getId(), typeMap);
String type = "unknown";
if (begin.equals(created))
type = DataTypeDto.AVAILABILITY;
else
type = DataTypeDto.FUTURE_AVAILABILITY;
Set<SimpleRecordDto> dtos = typeMap.getRecordsByType().get(type);
if (dtos == null){
dtos = new HashSet<SimpleRecordDto>();
typeMap.getRecordsByType().put(type, dtos);
}
dtos.add(new SimpleRecordDto(updateTime + forecast,state+0.,600));
}
Set<SimpleRecordDto> dtos = new HashSet<SimpleRecordDto>();
TypeMapDto typeMap = new TypeMapDto();
typeMap.getRecordsByType().put(DataTypeDto.NUMBER_AVAILABE, dtos);
if (begin.equals(created))
dtos.add(new SimpleRecordDto(updateTime + forecast, free+0.,600));
stationData.put(stationId, typeMap );
}
///////////////////////////////////////////////////////////////
// Write data to integreen
///////////////////////////////////////////////////////////////
Object result = xmlrpcPusher.pushData(CARSHARINGSTATION_DATASOURCE, new Object[]{stationData});
if (result instanceof IntegreenException)
{
throw new IOException("IntegreenException");
}
synchronized (lock)
{
activityLog.report += "pushData(" + CARSHARINGSTATION_DATASOURCE + "): " + stationData.size()+ "\n";
}
result = xmlrpcPusher.pushData(CARSHARINGCAR_DATASOURCE, new Object[]{vehicleData});
if (result instanceof IntegreenException)
{
throw new IOException("IntegreenException");
}
synchronized (lock)
{
activityLog.report += "pushData(" + CARSHARINGCAR_DATASOURCE + "): " + vehicleData.size() + "\n";
}
}
}
}
| agpl-3.0 |
ging/isabel | components/gateway/GWSIP/mjsip_1.6/src/org/zoolu/sip/provider/SipInterfaceListener.java | 1263 | /*
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This file is part of MjSip (http://www.mjsip.org)
*
* MjSip is free software; you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MjSip 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
* Affero GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with MjSip; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Luca Veltri (luca.veltri@unipr.it)
*/
package org.zoolu.sip.provider;
import org.zoolu.sip.message.Message;
/** A SipInterfaceListener listens for SipInterface onReceivedMessage(SipInterfaceListener,Message) events.
*/
public interface SipInterfaceListener
{
/** When a new Message is received by the SipInterface. */
public void onReceivedMessage(SipInterface sip, Message message);
}
| agpl-3.0 |
WaywardRealms/Wayward | WaywardChat/src/main/java/net/wayward_realms/waywardchat/irc/IrcMessageListener.java | 872 | package net.wayward_realms.waywardchat.irc;
import net.wayward_realms.waywardchat.WaywardChat;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
public class IrcMessageListener extends ListenerAdapter<PircBotX> {
private WaywardChat plugin;
public IrcMessageListener(WaywardChat plugin) {
this.plugin = plugin;
}
@Override
public void onMessage(MessageEvent<PircBotX> event) {
final User user = event.getUser();
final Channel channel = event.getChannel();
final String message = event.getMessage();
if (user != plugin.getIrcBot().getUserBot()) {
if (!message.startsWith("!")) {
plugin.handleChat(user, channel, message);
}
}
}
}
| agpl-3.0 |
dzc34/Asqatasun | rules/rules-rgaa3.0/src/main/java/org/asqatasun/rules/rgaa30/Rgaa30Rule120401.java | 1491 | /*
* 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.rgaa30;
import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 12.4.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/12.Navigation/Rule-12-4-1.html">the rule 12.4.1 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-12-4-1"> 12.4.1 rule specification</a>
*/
public class Rgaa30Rule120401 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Rgaa30Rule120401 () {
super();
}
}
| agpl-3.0 |
jpaoletti/jPOS-Presentation-Manager | modules/pm_struts/src/org/jpos/ee/pm/struts/actions/FieldProcessingActionSupport.java | 5057 | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2010 Alejandro P. Revilla
*
* 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.jpos.ee.pm.struts.actions;
import java.util.ArrayList;
import java.util.List;
import org.jpos.ee.pm.converter.Converter;
import org.jpos.ee.pm.converter.ConverterException;
import org.jpos.ee.pm.converter.IgnoreConvertionException;
import org.jpos.ee.pm.core.EntityInstanceWrapper;
import org.jpos.ee.pm.core.Field;
import org.jpos.ee.pm.core.PMException;
import org.jpos.ee.pm.struts.PMStrutsContext;
import org.jpos.ee.pm.validator.ValidationResult;
import org.jpos.ee.pm.validator.Validator;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;
public abstract class FieldProcessingActionSupport extends EntityActionSupport {
protected void proccessField(PMStrutsContext ctx, Field field, EntityInstanceWrapper wrapper) throws PMException {
LogEvent evt = ctx.getPresentationManager().getLog().createDebug();
evt.addMessage("Field [" + field.getId() + "] ");
final List<String> parameterValues = getParameterValues(ctx,field);
int i = 0;
for (String value : parameterValues) {
evt.addMessage(" Object to convert: " + value);
try {
final Converter converter = field.getConverters().getConverterForOperation(ctx.getOperation().getId());
Object converted = getConvertedValue(ctx, field, value, wrapper, converter);
evt.addMessage(" Object converted: " + converted);
doProcessField(wrapper, i, converter, ctx, field, converted);
} catch (IgnoreConvertionException e) {
//Do nothing, just ignore conversion.
}
i++;
}
Logger.log(evt);
}
protected void doProcessField(EntityInstanceWrapper wrapper, int i, final Converter converter, PMStrutsContext ctx, Field field, Object converted) throws PMException {
final Object o = wrapper.getInstance(i);
if (converter.getValidate()) {
if (validateField(ctx, field, wrapper, converted)) {
ctx.getPresentationManager().set(o, field.getProperty(), converted);
}
} else {
ctx.getPresentationManager().set(o, field.getProperty(), converted);
}
}
protected Object getConvertedValue(PMStrutsContext ctx, Field field, String values, EntityInstanceWrapper wrapper, final Converter converter) throws ConverterException {
ctx.put(PM_FIELD, field);
ctx.put(PM_FIELD_VALUE, values);
ctx.put(PM_ENTITY_INSTANCE_WRAPPER, wrapper);
final Object converted = converter.build(ctx);
return converted;
}
private boolean validateField(PMStrutsContext ctx, Field field, EntityInstanceWrapper wrapper, Object o) throws PMException {
boolean ok = true;
if (field.getValidators() != null) {
for (Validator fv : field.getValidators()) {
ctx.put(PM_ENTITY_INSTANCE, wrapper.getInstance());
ctx.put(PM_FIELD, field);
ctx.put(PM_FIELD_VALUE, o);
ValidationResult vr = fv.validate(ctx);
ctx.getErrors().addAll(vr.getMessages());
ok = ok && vr.isSuccessful();
}
}
return ok;
}
private String getParamValues(PMStrutsContext ctx, String name, String separator) {
String[] ss = ctx.getRequest().getParameterValues(name);
if (ss != null) {
StringBuilder s = new StringBuilder();
if (ss != null && ss.length > 0) {
s.append(ss[0]);
}
//In this case we have a multivalue input
for (int i = 1; i < ss.length; i++) {
s.append(separator);
s.append(ss[i]);
}
return s.toString();
} else {
return null;
}
}
protected List<String> getParameterValues(PMStrutsContext ctx, Field field) {
List<String> result = new ArrayList<String>();
String eid = "f_" + field.getId();
String s = getParamValues(ctx, eid, ";");
int i = 0;
if (s == null) {
s = "";
}
while(s != null){
result.add(s);
i++;
s = getParamValues(ctx, eid + "_" + i, ";");
}
return result;
}
}
| agpl-3.0 |
printedheart/opennars | nars_lab_x/main/java/nars/prolog/VarTestCase.java | 369 | package prolog;
import junit.framework.TestCase;
import nars.tuprolog.Var;
public class VarTestCase extends TestCase {
public void testIsAtomic() {
assertFalse(new Var("X").isAtomic());
}
public void testIsAtom() {
assertFalse(new Var("X").isAtom());
}
public void testIsCompound() {
assertFalse(new Var("X").isCompound());
}
}
| agpl-3.0 |
FullMetal210/milton2 | milton-server/src/main/java/io/milton/http/json/PropPatchJsonResource.java | 5053 | /*
* Copyright 2012 McEvoy Software Ltd.
*
* 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 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 io.milton.http.json;
import io.milton.http.Auth;
import io.milton.http.FileItem;
import io.milton.http.Range;
import io.milton.http.Request;
import io.milton.http.Request.Method;
import io.milton.http.Response.Status;
import io.milton.http.exceptions.BadRequestException;
import io.milton.http.exceptions.ConflictException;
import io.milton.http.exceptions.NotAuthorizedException;
import io.milton.http.webdav.PropFindResponse;
import io.milton.http.webdav.PropFindResponse.NameAndError;
import io.milton.resource.PostableResource;
import io.milton.resource.Resource;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropPatchJsonResource extends JsonResource implements PostableResource {
private static final Logger log = LoggerFactory.getLogger(PropPatchJsonResource.class);
private final Resource wrappedResource;
private final JsonPropPatchHandler patchHandler;
private final String encodedUrl;
private PropFindResponse resp;
public PropPatchJsonResource( Resource wrappedResource, JsonPropPatchHandler patchHandler, String encodedUrl ) {
super( wrappedResource, Request.Method.PROPPATCH.code, null );
this.wrappedResource = wrappedResource;
this.encodedUrl = encodedUrl;
this.patchHandler = patchHandler;
}
public void sendContent( OutputStream out, Range range, Map<String, String> params, String contentType ) throws IOException, NotAuthorizedException {
log.debug( "sendContent");
JsonConfig cfg = new JsonConfig();
cfg.setIgnoreTransientFields( true );
cfg.setCycleDetectionStrategy( CycleDetectionStrategy.LENIENT );
List<FieldError> errors = new ArrayList<FieldError>();
if( resp != null && resp.getErrorProperties() != null ) {
log.debug( "error props: " + resp.getErrorProperties().size());
for( Status stat : resp.getErrorProperties().keySet() ) {
List<NameAndError> props = resp.getErrorProperties().get( stat );
for( NameAndError ne : props ) {
errors.add( new FieldError( ne.getName().getLocalPart(), ne.getError(), stat.code ) );
}
}
}
log.debug( "errors size: " + errors.size());
FieldError[] arr = new FieldError[errors.size()];
arr = errors.toArray( arr );
Writer writer = new PrintWriter( out );
JSON json = JSONSerializer.toJSON( arr, cfg );
json.write( writer );
writer.flush();
}
@Override
public boolean authorise( Request request, Method method, Auth auth ) {
// leave authorisation to the proppatch processing
return true;
}
public String processForm( Map<String, String> parameters, Map<String, FileItem> files ) throws BadRequestException, NotAuthorizedException, ConflictException {
resp = patchHandler.process( wrappedResource, encodedUrl, parameters );
return null;
}
@Override
public Method applicableMethod() {
return Method.PROPPATCH;
}
public class FieldError {
private String name;
private String description;
private int code;
public FieldError( String name, String description, int code ) {
this.name = name;
this.description = description;
this.code = code;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription( String description ) {
this.description = description;
}
public int getCode() {
return code;
}
public void setCode( int code ) {
this.code = code;
}
}
}
| agpl-3.0 |
Asqatasun/Asqatasun | engine/asqatasun-api/src/main/java/org/asqatasun/entity/audit/Content.java | 1871 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun 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.entity.audit;
import java.util.Date;
import org.asqatasun.entity.Entity;
/**
*
* @author jkowalczyk
*/
public interface Content extends Entity {
/**
*
* @return the audit
*/
Audit getAudit();
/**
*
* @return the date of loading
*/
Date getDateOfLoading();
/**
*
* @return the URI
*/
String getURI();
/**
*
* @return the http Status Code
*/
int getHttpStatusCode();
/**
*
* @param audit
* the audit to set
*/
void setAudit(Audit audit);
/**
*
* @param dateOfLoading
* the date of loading to set
*/
void setDateOfLoading(Date dateOfLoading);
/**
*
* @param uri
* the URI to set
*/
void setURI(String uri);
/**
*
* @param httpStatusCode
* the Http Status Code when fetched the content
*/
void setHttpStatusCode(int httpStatusCode);
}
| agpl-3.0 |
kobronson/cs-voltdb | src/frontend/org/voltdb/plannodes/SchemaColumn.java | 8242 | /* This file is part of VoltDB.
* Copyright (C) 2008-2013 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.plannodes;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.json_voltpatches.JSONStringer;
import org.voltdb.VoltType;
import org.voltdb.catalog.Database;
import org.voltdb.expressions.AbstractExpression;
import org.voltdb.expressions.TupleValueExpression;
/**
* This class encapsulates the data and operations needed to track columns
* in the planner.
*
*/
public class SchemaColumn
{
public enum Members {
COLUMN_NAME,
EXPRESSION,
}
/**
* Create a new SchemaColumn
* @param tableName The name of the table where this column originated,
* if any. Currently, internally created columns will be assigned
* the table name "VOLT_TEMP_TABLE" for disambiguation.
* @param columnName The name of this column, if any
* @param columnAlias The alias assigned to this column, if any
* @param expression The input expression which generates this
* column. SchemaColumn needs to have exclusive ownership
* so that it can adjust the index of any TupleValueExpressions
* without affecting other nodes/columns/plan iterations, so
* it clones this expression.
*/
public SchemaColumn(String tableName, String columnName,
String columnAlias, AbstractExpression expression)
{
m_tableName = tableName;
m_columnName = columnName;
m_columnAlias = columnAlias;
try
{
m_expression = (AbstractExpression) expression.clone();
}
catch (CloneNotSupportedException e)
{
throw new RuntimeException(e.getMessage());
}
}
/**
* Clone a schema column
*/
@Override
protected SchemaColumn clone()
{
return new SchemaColumn(m_tableName, m_columnName, m_columnAlias,
m_expression);
}
/**
* Return a copy of this SchemaColumn, but with the input expression
* replaced by an appropriate TupleValueExpression.
*/
public SchemaColumn copyAndReplaceWithTVE()
{
TupleValueExpression new_exp = null;
if (m_expression instanceof TupleValueExpression)
{
try
{
new_exp = (TupleValueExpression) m_expression.clone();
}
catch (CloneNotSupportedException e)
{
throw new RuntimeException(e.getMessage());
}
}
else
{
new_exp = new TupleValueExpression();
// XXX not sure this is right
new_exp.setTableName(m_tableName);
new_exp.setColumnName(m_columnName);
new_exp.setColumnAlias(m_columnAlias);
new_exp.setValueType(m_expression.getValueType());
new_exp.setValueSize(m_expression.getValueSize());
}
return new SchemaColumn(m_tableName, m_columnName, m_columnAlias,
new_exp);
}
public String getTableName()
{
return m_tableName;
}
public String getColumnName()
{
return m_columnName;
}
public String getColumnAlias()
{
return m_columnAlias;
}
public AbstractExpression getExpression()
{
return m_expression;
}
public VoltType getType()
{
return m_expression.getValueType();
}
public int getSize()
{
return m_expression.getValueSize();
}
/**
* Check if this SchemaColumn provides the column specified by the input
* arguments. A match is defined as matching both the table name and
* the column name if it is provided, otherwise matching the provided alias.
* @param tableName
* @param columnName
* @param columnAlias
* @return
*/
public boolean matches(String tableName, String columnName,
String columnAlias)
{
boolean retval = false;
if (tableName.equals(m_tableName))
{
if (columnName != null && !columnName.equals(""))
{
if (columnName.equals(m_columnName))
{
retval = true;
}
}
else if (columnAlias != null && !columnAlias.equals(""))
{
if (columnAlias.equals(m_columnAlias))
{
retval = true;
}
}
else if (tableName.equals("VOLT_TEMP_TABLE"))
{
retval = true;
}
else
{
throw new RuntimeException("Attempted to match a SchemaColumn " +
"but provided no name or alias.");
}
}
return retval;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("SchemaColumn:\n");
sb.append("\tTable Name: ").append(m_tableName).append("\n");
sb.append("\tColumn Name: ").append(m_columnName).append("\n");
sb.append("\tColumn Alias: ").append(m_columnAlias).append("\n");
sb.append("\tColumn Type: ").append(getType()).append("\n");
sb.append("\tColumn Size: ").append(getSize()).append("\n");
sb.append("\tExpression: ").append(m_expression.toString()).append("\n");
return sb.toString();
}
public void toJSONString(JSONStringer stringer) throws JSONException
{
stringer.object();
// Tell the EE that the column name is either a valid column
// alias or the original column name if no alias exists. This is a
// bit hacky, but it's the easiest way for the EE to generate
// a result set that has all the aliases that may have been specified
// by the user (thanks to chains of setOutputTable(getInputTable))
if (getColumnAlias() != null && !getColumnAlias().equals(""))
{
stringer.key(Members.COLUMN_NAME.name()).value(getColumnAlias());
}
else if (getColumnName() != null) {
stringer.key(Members.COLUMN_NAME.name()).value(getColumnName());
}
else
{
stringer.key(Members.COLUMN_NAME.name()).value("");
}
if (m_expression != null) {
stringer.key(Members.EXPRESSION.name());
stringer.object();
m_expression.toJSONString(stringer);
stringer.endObject();
}
else
{
stringer.key(Members.EXPRESSION.name()).value("");
}
stringer.endObject();
}
public static SchemaColumn fromJSONObject( JSONObject jobj, Database db ) throws JSONException {
String tableName = "";
String columnName = "";
String columnAlias = "";
AbstractExpression expression = null;
if( !jobj.isNull( Members.COLUMN_NAME.name() ) ){
columnName = jobj.getString( Members.COLUMN_NAME.name() );
}
if( !jobj.isNull( Members.EXPRESSION.name() ) ) {
expression = AbstractExpression.fromJSONObject( jobj.getJSONObject( Members.EXPRESSION.name() ), db);
}
return new SchemaColumn( tableName, columnName, columnAlias, expression );
}
private String m_tableName;
private String m_columnName;
private String m_columnAlias;
private AbstractExpression m_expression;
}
| agpl-3.0 |
shenan4321/BIMplatform | generated/cn/dlb/bim/models/store/DoubleType.java | 1970 | /**
* 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.store;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Double Type</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link cn.dlb.bim.models.store.DoubleType#getValue <em>Value</em>}</li>
* </ul>
*
* @see cn.dlb.bim.models.store.StorePackage#getDoubleType()
* @model
* @generated
*/
public interface DoubleType extends PrimitiveType {
/**
* Returns the value of the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Value</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(double)
* @see cn.dlb.bim.models.store.StorePackage#getDoubleType_Value()
* @model
* @generated
*/
double getValue();
/**
* Sets the value of the '{@link cn.dlb.bim.models.store.DoubleType#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(double value);
} // DoubleType
| agpl-3.0 |
cdparra/reminiscens-book | placebooks-webapp/src/placebooks/client/parser/EnumParser.java | 314 | package placebooks.client.parser;
import com.google.gwt.core.client.JsonUtils;
public abstract class EnumParser<T extends Enum<?>> implements JSONParser<Enum<?>>
{
@Override
public void write(final StringBuilder builder, final Enum<?> object)
{
builder.append(JsonUtils.escapeValue(object.toString()));
}
} | agpl-3.0 |
hltn/opencps | portlets/opencps-portlet/docroot/WEB-INF/service/org/opencps/dossiermgt/service/persistence/ServiceConfigActionableDynamicQuery.java | 1346 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package org.opencps.dossiermgt.service.persistence;
import com.liferay.portal.kernel.dao.orm.BaseActionableDynamicQuery;
import com.liferay.portal.kernel.exception.SystemException;
import org.opencps.dossiermgt.model.ServiceConfig;
import org.opencps.dossiermgt.service.ServiceConfigLocalServiceUtil;
/**
* @author trungnt
* @generated
*/
public abstract class ServiceConfigActionableDynamicQuery
extends BaseActionableDynamicQuery {
public ServiceConfigActionableDynamicQuery() throws SystemException {
setBaseLocalService(ServiceConfigLocalServiceUtil.getService());
setClass(ServiceConfig.class);
setClassLoader(org.opencps.dossiermgt.service.ClpSerializer.class.getClassLoader());
setPrimaryKeyPropertyName("serviceConfigId");
}
} | agpl-3.0 |
splicemachine/spliceengine | hbase_sql/src/test/java/com/splicemachine/stream/StreamableRDDTest_Failures.java | 19123 | /*
* 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.stream;
import splice.com.google.common.net.HostAndPort;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.sql.execute.ExecRow;
import com.splicemachine.derby.impl.SpliceSpark;
import com.splicemachine.derby.stream.BaseStreamTest;
import org.apache.commons.collections.IteratorUtils;
import org.apache.log4j.Logger;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.Tuple2;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.*;
/**
* Created by dgomezferro on 6/1/16.
*/
public class StreamableRDDTest_Failures extends BaseStreamTest implements Serializable {
private static final Logger LOG = Logger.getLogger(StreamableRDDTest_Failures.class);
private static StreamListenerServer server;
@BeforeClass
public static void setup() throws StandardException {
server = new StreamListenerServer(0);
server.start();
}
@BeforeClass
public static void startSpark() {
SpliceSpark.getContextUnsafe();
}
@AfterClass
public static void stopSpark() {
SpliceSpark.getContextUnsafe().stop();
}
@Before
public void reset() {
FailsFunction.reset();
FailsTwiceFunction.reset();
}
@Test
public void testBasicStream() throws Exception {
StreamListener<ExecRow> sl = new StreamListener<>();
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(tenRows, 2).mapToPair(new FailsFunction(3));
StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort());
srdd.submit();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
while (it.hasNext()) {
ExecRow execRow = it.next();
LOG.trace(execRow);
count++;
assertNotNull(execRow);
assertTrue(execRow.getColumn(1).getInt() < 10);
}
assertEquals(10, count);
}
@Test
public void testFailureBoundary() throws Exception {
StreamListener<ExecRow> sl = new StreamListener<>();
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(tenRows, 20).mapToPair(new FailsFunction(4));
StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort());
srdd.submit();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
while (it.hasNext()) {
ExecRow execRow = it.next();
LOG.trace(execRow);
count++;
assertNotNull(execRow);
assertTrue(execRow.getColumn(1).getInt() < 10);
}
assertEquals(10, count);
}
@Test
public void testBlockingMedium() throws StandardException, FileNotFoundException, UnsupportedEncodingException {
int size = 20000;
int batches = 2;
int batchSize = 512;
StreamListener<ExecRow> sl = new StreamListener<>(-1, 0, batches, batchSize);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < size; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 2).sortByKey().mapToPair(new FailsFunction(5000));
final StreamableRDD srdd = new StreamableRDD(rdd.values(), null, sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort(), batches, batchSize);
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
while (it.hasNext()) {
ExecRow execRow = it.next();
assertNotNull(execRow);
count++;
}
assertEquals(size, count);
}
@Test
public void testBlockingLarge() throws StandardException, FileNotFoundException, UnsupportedEncodingException {
int size = 100000;
int batches = 2;
int batchSize = 512;
StreamListener<ExecRow> sl = new StreamListener<>(-1, 0, batches, batchSize);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < size; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 12).sortByKey().mapToPair(new FailsFunction(10000));
final StreamableRDD srdd = new StreamableRDD(rdd.values(), null, sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort(), batches, batchSize);
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
while (it.hasNext()) {
ExecRow execRow = it.next();
assertNotNull(execRow);
count++;
}
assertEquals(size, count);
}
@Test
public void testFailureBeforeLargeOffset() throws StandardException {
StreamListener<ExecRow> sl = new StreamListener<>(400, 30000);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < 100000; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 13).mapToPair(new FailsFunction(29500));;
final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort());
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
int first = 30000;
while (it.hasNext()) {
ExecRow execRow = it.next();
assertNotNull(execRow);
assertEquals(count+first, execRow.getColumn(1).getInt());
count++;
}
assertEquals(400, count);
}
@Test
public void testFailureBeforeOffset() throws StandardException {
StreamListener<ExecRow> sl = new StreamListener<>(40000, 300);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < 100000; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 13).mapToPair(new FailsFunction(200));;
final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort());
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
int first = 300;
while (it.hasNext()) {
ExecRow execRow = it.next();
assertNotNull(execRow);
assertEquals(count+first, execRow.getColumn(1).getInt());
count++;
}
assertEquals(40000, count);
}
@Test
public void testFailureAfterOffset() throws StandardException {
StreamListener<ExecRow> sl = new StreamListener<>(40000, 300);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < 100000; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 13).mapToPair(new FailsFunction(14000));;
final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort());
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
int first = 300;
while (it.hasNext()) {
ExecRow execRow = it.next();
assertNotNull(execRow);
assertEquals(count+first, execRow.getColumn(1).getInt());
count++;
}
assertEquals(40000, count);
}
@Test
public void testFailureAfterLimit() throws StandardException {
StreamListener<ExecRow> sl = new StreamListener<>(40000, 300);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < 100000; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 13).mapToPair(new FailsFunction(40301));;
final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort());
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
int first = 300;
while (it.hasNext()) {
ExecRow execRow = it.next();
assertNotNull(execRow);
assertEquals(count+first, execRow.getColumn(1).getInt());
count++;
}
assertEquals(40000, count);
}
@Test
public void testFailureDuringRecoveryWarmup() throws StandardException, FileNotFoundException, UnsupportedEncodingException {
int size = 100000;
int batches = 2;
int batchSize = 512;
StreamListener<ExecRow> sl = new StreamListener<>(-1, 0, batches, batchSize);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < size; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 2).sortByKey().mapToPair(new FailsTwiceFunction(10000, 100));
final StreamableRDD srdd = new StreamableRDD(rdd.values(), null, sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort(), batches, batchSize);
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
while (it.hasNext()) {
ExecRow execRow = it.next();
assertNotNull(execRow);
count++;
}
assertEquals(size, count);
}
@Test
public void testFailureAfterRecoveryWarmup() throws StandardException, FileNotFoundException, UnsupportedEncodingException {
int size = 100000;
int batches = 2;
int batchSize = 512;
StreamListener<ExecRow> sl = new StreamListener<>(-1, 0, batches, batchSize);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < size; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 2).sortByKey().mapToPair(new FailsTwiceFunction(10000, 2000));
final StreamableRDD srdd = new StreamableRDD(rdd.values(), null, sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort(), batches, batchSize);
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}.start();
Iterator<ExecRow> it = sl.getIterator();
int count = 0;
while (it.hasNext()) {
ExecRow execRow = it.next();
assertNotNull(execRow);
count++;
}
assertEquals(size, count);
}
@Test
public void testPersistentFailureWithOffset() throws StandardException, FileNotFoundException, UnsupportedEncodingException {
int size = 100000;
int batches = 2;
int batchSize = 512;
StreamListener<ExecRow> sl = new StreamListener<>(-1, 10, batches, batchSize);
HostAndPort hostAndPort = server.getHostAndPort();
server.register(sl);
List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>();
for(int i = 0; i < size; ++i) {
manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2)));
}
JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 2).sortByKey().mapToPair(new FailsForeverFunction(0));
final StreamableRDD srdd = new StreamableRDD(rdd.distinct().values(), null, sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort(), batches, batchSize);
new Thread() {
@Override
public void run() {
try {
srdd.submit();
} catch (Exception e) {
sl.failed(e);
throw new RuntimeException(e);
}
}
}.start();
// This call shoul not raise an exception even though the Spark job fails
Iterator<ExecRow> it = sl.getIterator();
try {
it.hasNext();
fail("Should have raised exception");
} catch (Exception e) {
//expected exception
}
}
}
class FailsFunction implements PairFunction<Tuple2<ExecRow, ExecRow>, ExecRow, ExecRow> {
static AtomicBoolean failed = new AtomicBoolean(false);
final long toFail;
public FailsFunction(long toFail) {
this.toFail = toFail;
}
@Override
public Tuple2<ExecRow, ExecRow> call(Tuple2<ExecRow, ExecRow> element) throws Exception {
if (element._1().getColumn(1).getInt() == toFail && !failed.get()) {
failed.set(true);
throw new RuntimeException("Failure");
}
return element;
}
public static void reset() {
failed.set(false);
}
}
class FailsTwiceFunction implements PairFunction<Tuple2<ExecRow, ExecRow>, ExecRow, ExecRow> {
static AtomicBoolean failed = new AtomicBoolean(false);
static AtomicBoolean failed2 = new AtomicBoolean(false);
final long toFail;
final long toFail2;
public FailsTwiceFunction(long toFail, long toFail2) {
this.toFail = toFail;
this.toFail2 = toFail2;
}
@Override
public Tuple2<ExecRow, ExecRow> call(Tuple2<ExecRow, ExecRow> element) throws Exception {
if (!failed.get()) {
if (element._1().getColumn(1).getInt() == toFail) {
failed.set(true);
throw new RuntimeException("First Failure");
}
} else if (!failed2.get()) {
if (element._1().getColumn(1).getInt() == toFail2) {
failed2.set(true);
throw new RuntimeException("Second Failure");
}
}
return element;
}
public static void reset() {
failed.set(false);
failed2.set(false);
}
}
class FailsForeverFunction implements PairFunction<Tuple2<ExecRow, ExecRow>, ExecRow, ExecRow> {
final long toFail;
public FailsForeverFunction(long toFail) {
this.toFail = toFail;
}
@Override
public Tuple2<ExecRow, ExecRow> call(Tuple2<ExecRow, ExecRow> element) throws Exception {
if (element._1().getColumn(1).getInt() == toFail) {
throw new RuntimeException("Failure");
}
return element;
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_message_assemble_communicate/src/main/java/com/x/message/assemble/communicate/jaxrs/connector/ExceptionZhengwuDingdingMessage.java | 427 | package com.x.message.assemble.communicate.jaxrs.connector;
import com.x.base.core.project.exception.PromptException;
class ExceptionZhengwuDingdingMessage extends PromptException {
private static final long serialVersionUID = 4132300948670472899L;
ExceptionZhengwuDingdingMessage(Integer retCode, String retMessage) {
super("发送政务钉钉消息失败,错误代码:{},错误消息:{}.", retCode, retMessage);
}
}
| agpl-3.0 |
objectundefined/neo4j-extensions | neo4j-extensions-spring/src/main/java/org/neo4j/extensions/spring/indexes/UserIndex.java | 632 | package org.neo4j.extensions.spring.indexes;
import java.util.Map;
/**
* UserIndex indexed properties.
*
*
* @author bradnussbaum
* @version 0.1.0
*
* @since 0.1.0
*
*/
public enum UserIndex {
lastModifiedTime(IndexType.user_exact),
email(IndexType.user_fulltext),
name(IndexType.user_fulltext),
username(IndexType.user_fulltext);
private IndexType type;
private UserIndex(IndexType type) {
this.type = type;
}
public Map<String, String> getIndexType() {
return type.getIndexType();
}
public String getIndexName() {
return type.name();
}
}
| agpl-3.0 |
hogi/kunagi | src/main/java/scrum/server/files/File.java | 989 | package scrum.server.files;
import ilarkesto.io.IO;
import scrum.server.admin.User;
public class File extends GFile {
// --- dependencies ---
// --- ---
public void deleteFile() {
IO.delete(getJavaFile());
}
public java.io.File getJavaFile() {
return new java.io.File(getProject().getFileRepositoryPath() + "/" + getFilename());
}
public void updateNumber() {
if (isNumber(0)) setNumber(getProject().generateFileNumber());
}
public boolean isVisibleFor(User user) {
return getProject().isVisibleFor(user);
}
public String getReferenceAndLabel() {
return getReference() + " (" + getLabel() + ")";
}
public String getReference() {
return scrum.client.files.File.REFERENCE_PREFIX + getNumber();
}
public boolean isEditableBy(User user) {
return getProject().isEditableBy(user);
}
@Override
public String toString() {
return getReferenceAndLabel();
}
@Override
public void ensureIntegrity() {
super.ensureIntegrity();
updateNumber();
}
} | agpl-3.0 |
TheLanguageArchive/Arbil | arbil-commons/src/main/java/nl/mpi/arbil/userstorage/CommonsSessionStorage.java | 10338 | /**
* Copyright (C) 2016 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.arbil.userstorage;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import nl.mpi.flap.plugin.PluginDialogHandler;
import nl.mpi.flap.plugin.PluginSessionStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created on : Nov 8, 2012, 4:25:54 PM
*
* @author Peter Withers <peter.withers@mpi.nl>
*/
public abstract class CommonsSessionStorage implements PluginSessionStorage {
private final static Logger logger = LoggerFactory.getLogger(CommonsSessionStorage.class);
protected File localCacheDirectory = null;
private File storageDirectory = null;
protected PluginDialogHandler messageDialogHandler;
protected abstract String[] getAppDirectoryAlternatives();
protected abstract String getProjectDirectoryName();
protected abstract void logError(Exception exception);
protected abstract void logError(String message, Exception exception);
public abstract Object loadObject(String filename) throws Exception;
private void checkForMultipleStorageDirectories(String[] locationOptions) {
// look for any additional storage directories
int foundDirectoryCount = 0;
StringBuilder storageDirectoryMessageString = new StringBuilder();
for (String currentStorageDirectory : locationOptions) {
File storageFile = new File(currentStorageDirectory);
if (storageFile.exists()) {
foundDirectoryCount++;
storageDirectoryMessageString.append(currentStorageDirectory).append("\n");
}
}
if (foundDirectoryCount > 1) {
String errorMessage = "More than one storage directory has been found.\nIt is recommended to remove any unused directories in this list.\nNote that the first occurrence is currently in use:\n" + storageDirectoryMessageString;
logError(new Exception(errorMessage));
try {
if (!GraphicsEnvironment.isHeadless()) {
JOptionPane.showMessageDialog(null,
"More than one storage directory has been found.\nIt is recommended to remove any unused directories in this list.\nNote that the first occurrence is currently in use:\n" + storageDirectoryMessageString, "Multiple storage directories",
JOptionPane.WARNING_MESSAGE);
}
} catch (HeadlessException hEx) {
// Should never occur since we're checking whether headless
throw new AssertionError(hEx);
}
}
}
protected String[] getLocationOptions() {
List<String> locationOptions = new ArrayList<String>();
for (String appDir : getAppDirectoryAlternatives()) {
locationOptions.add(System.getProperty("user.home") + File.separatorChar + "Local Settings" + File.separatorChar + "Application Data" + File.separatorChar + appDir + File.separatorChar);
locationOptions.add(System.getenv("APPDATA") + File.separatorChar + appDir + File.separatorChar);
locationOptions.add(System.getProperty("user.home") + File.separatorChar + appDir + File.separatorChar);
locationOptions.add(System.getenv("USERPROFILE") + File.separatorChar + appDir + File.separatorChar);
locationOptions.add(System.getProperty("user.dir") + File.separatorChar + appDir + File.separatorChar);
}
List<String> uniqueArray = new ArrayList<String>();
for (String location : locationOptions) {
if (location != null
&& !location.startsWith("null")
&& !uniqueArray.contains(location)) {
uniqueArray.add(location);
}
}
locationOptions = uniqueArray;
for (String currentLocationOption : locationOptions) {
logger.debug("LocationOption: " + currentLocationOption);
}
return locationOptions.toArray(new String[]{});
}
private File determineStorageDirectory() throws RuntimeException {
File storageDirectoryFile = null;
String storageDirectoryArray[] = getLocationOptions();
// look for an existing storage directory
for (String currentStorageDirectory : storageDirectoryArray) {
File storageFile = new File(currentStorageDirectory);
if (storageFile.exists()) {
logger.debug("existing storage directory found: " + currentStorageDirectory);
storageDirectoryFile = storageFile;
break;
}
}
String testedStorageDirectories = "";
if (storageDirectoryFile == null) {
for (String currentStorageDirectory : storageDirectoryArray) {
if (!currentStorageDirectory.startsWith("null")) {
File storageFile = new File(currentStorageDirectory);
if (!storageFile.exists()) {
if (!storageFile.mkdir()) {
testedStorageDirectories = testedStorageDirectories + currentStorageDirectory + "\n";
logError("failed to create: " + currentStorageDirectory, null);
} else {
logger.debug("created new storage directory: " + currentStorageDirectory);
storageDirectoryFile = storageFile;
break;
}
}
}
}
}
if (storageDirectoryFile == null) {
logError("Could not create a working directory in any of the potential location:\n" + testedStorageDirectories + "Please check that you have write permissions in at least one of these locations.\nThe application will now exit.", null);
System.exit(-1);
} else {
try {
File testFile = File.createTempFile("testfile", ".tmp", storageDirectoryFile);
boolean success = testFile.exists();
if (!success) {
success = testFile.createNewFile();
}
if (success) {
testFile.deleteOnExit();
success = testFile.exists();
if (success) {
success = testFile.delete();
}
}
if (!success) {
// test the storage directory is writable and add a warning message box here if not
logError("Could not write to the working directory.\nThere will be issues creating, editing and saving any file.", null);
}
} catch (IOException exception) {
logger.debug("Sending exception to logger", exception);
logError(exception);
messageDialogHandler.addMessageDialogToQueue("Could not create a test file in the working directory.", "Arbil Critical Error");
throw new RuntimeException("Exception while testing working directory writability", exception);
}
}
logger.debug("storageDirectory: " + storageDirectoryFile);
checkForMultipleStorageDirectories(storageDirectoryArray);
return storageDirectoryFile;
}
/**
* @return the storageDirectory
*/
public synchronized File getApplicationSettingsDirectory() {
if (storageDirectory == null) {
storageDirectory = determineStorageDirectory();
}
return storageDirectory;
}
/**
* @return the project directory
*/
public File getProjectDirectory() {
return getProjectWorkingDirectory().getParentFile();
}
/**
* Tests that the project directory exists and creates it if it does not.
*
* @return the project working files directory
*/
public File getProjectWorkingDirectory() {
if (localCacheDirectory == null) {
// load from the text based properties file
String localCacheDirectoryPathString = loadString("cacheDirectory");
if (localCacheDirectoryPathString != null) {
localCacheDirectory = new File(localCacheDirectoryPathString);
} else {
// otherwise load from the to be replaced binary based storage file
try {
File localWorkingDirectory = (File) loadObject("cacheDirectory");
localCacheDirectory = localWorkingDirectory;
} catch (Exception exception) {
if (new File(getApplicationSettingsDirectory(), "imdicache").exists()) {
localCacheDirectory = new File(getApplicationSettingsDirectory(), "imdicache");
} else {
localCacheDirectory = new File(getApplicationSettingsDirectory(), getProjectDirectoryName());
}
}
saveString("cacheDirectory", localCacheDirectory.getAbsolutePath());
}
boolean cacheDirExists = localCacheDirectory.exists();
if (!cacheDirExists) {
if (!localCacheDirectory.mkdirs()) {
logError("Could not create cache directory", null);
return null;
}
}
}
return localCacheDirectory;
}
}
| agpl-3.0 |
dirkriehle/wahlzeit | src/main/java/org/wahlzeit/servlets/NullServlet.java | 786 | /*
* SPDX-FileCopyrightText: 2006-2009 Dirk Riehle <dirk@riehle.org> https://dirkriehle.com
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package org.wahlzeit.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* A null servlet.
*/
public class NullServlet extends AbstractServlet {
/**
*
*/
private static final long serialVersionUID = 42L; // any one does; class never serialized
/**
*
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
displayNullPage(request, response);
}
/**
*
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
displayNullPage(request, response);
}
}
| agpl-3.0 |
aborg0/rapidminer-vega | src/com/rapidminer/gui/flow/ProcessPanel.java | 6427 | /*
* 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.gui.flow;
import java.awt.BorderLayout;
import java.awt.Component;
import java.util.List;
import javax.swing.Action;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import com.rapidminer.Process;
import com.rapidminer.gui.MainFrame;
import com.rapidminer.gui.actions.AutoWireAction;
import com.rapidminer.gui.processeditor.ProcessEditor;
import com.rapidminer.gui.tools.PrintingTools;
import com.rapidminer.gui.tools.ResourceDockKey;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.gui.tools.ViewToolBar;
import com.rapidminer.gui.tools.components.DropDownButton;
import com.rapidminer.operator.ExecutionUnit;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorChain;
import com.rapidminer.operator.ports.metadata.CompatibilityLevel;
import com.vlsolutions.swing.docking.DockKey;
import com.vlsolutions.swing.docking.Dockable;
/**
* Contains the main {@link ProcessRenderer} and a {@link ProcessButtonBar}
* to navigate through the process.
*
* @author Simon Fischer, Tobias Malbrecht
*/
public class ProcessPanel extends JPanel implements Dockable, ProcessEditor {
private static final long serialVersionUID = -4419160224916991497L;
private final ProcessRenderer renderer;
private final ProcessButtonBar processButtonBar;
private OperatorChain operatorChain;
public ProcessPanel(final MainFrame mainFrame) {
processButtonBar = new ProcessButtonBar(mainFrame);
renderer = new ProcessRenderer(this, mainFrame);
renderer.setBackground(SwingTools.LIGHTEST_BLUE);
ViewToolBar toolBar = new ViewToolBar();
toolBar.add(processButtonBar);
final Action autoWireAction = new AutoWireAction(mainFrame, "wire", CompatibilityLevel.PRE_VERSION_5, false, true);
DropDownButton autoWireDropDownButton = DropDownButton.makeDropDownButton(autoWireAction);
autoWireDropDownButton.add(autoWireAction);
autoWireDropDownButton.add(new AutoWireAction(mainFrame, "wire_recursive", CompatibilityLevel.PRE_VERSION_5, true, true));
autoWireDropDownButton.add(new AutoWireAction(mainFrame, "rewire", CompatibilityLevel.PRE_VERSION_5, false, false));
autoWireDropDownButton.add(new AutoWireAction(mainFrame, "rewire_recursive", CompatibilityLevel.PRE_VERSION_5, true, false));
autoWireDropDownButton.addToToolBar(toolBar, ViewToolBar.RIGHT);
toolBar.add(renderer.getFlowVisualizer().SHOW_ORDER_TOGGLEBUTTON, ViewToolBar.RIGHT);
toolBar.add(renderer.ARRANGE_OPERATORS_ACTION, ViewToolBar.RIGHT);
toolBar.add(renderer.AUTO_FIT_ACTION, ViewToolBar.RIGHT);
String name = "process";
if (mainFrame.getActions().getProcess() != null &&
mainFrame.getActions().getProcess().getProcessLocation() != null) {
name = mainFrame.getActions().getProcess().getProcessLocation().getShortName();
}
DropDownButton exportDropDownButton = PrintingTools.makeExportPrintDropDownButton(renderer, name);
exportDropDownButton.addToToolBar(toolBar, ViewToolBar.RIGHT);
setLayout(new BorderLayout());
add(toolBar, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane(renderer);
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
scrollPane.setBorder(null);
add(scrollPane, BorderLayout.CENTER);
}
public void showOperatorChain(OperatorChain operatorChain) {
this.operatorChain = operatorChain;
if (operatorChain == null) {
processButtonBar.setSelectedNode(null);
renderer.showOperatorChain(null);
} else {
renderer.showOperatorChain(operatorChain);
processButtonBar.setSelectedNode(operatorChain);
StringBuilder b = new StringBuilder("<html><strong>");
b.append(operatorChain.getName());
b.append("</strong> <emph>(");
b.append(operatorChain.getOperatorDescription().getName());
b.append(")</emph><br/>");
b.append("Subprocesses: ");
boolean first = true;
for (ExecutionUnit executionUnit : operatorChain.getSubprocesses()) {
if (first) {
first = false;
} else {
b.append(", ");
}
b.append("<em>");
b.append(executionUnit.getName());
b.append("</em> (");
b.append(executionUnit.getOperators().size());
b.append(" operators)");
}
b.append("</html>");
}
}
public void setSelection(List<Operator> selection) {
Operator first = selection.isEmpty() ? null : selection.get(0);
if (first != null) {
processButtonBar.addToHistory(first);
}
if (renderer.getSelection().equals(selection)) {
return;
}
if (first == null) {
showOperatorChain(null);
} else {
OperatorChain target;
if (first instanceof OperatorChain) {
target = (OperatorChain) first;
} else {
target = first.getParent();
}
showOperatorChain(target);
renderer.setSelection(selection);
}
}
@Override
public void processChanged(Process process) {
processButtonBar.clearHistory();
}
@Override
public void processUpdated(Process process) {
renderer.processUpdated();
processButtonBar.setSelectedNode(this.operatorChain);
}
public ProcessRenderer getProcessRenderer() {
return renderer;
}
public static final String PROCESS_PANEL_DOCK_KEY = "process_panel";
private final DockKey DOCK_KEY = new ResourceDockKey(PROCESS_PANEL_DOCK_KEY);
{
DOCK_KEY.setDockGroup(MainFrame.DOCK_GROUP_ROOT);
}
@Override
public Component getComponent() {
return this;
}
@Override
public DockKey getDockKey() {
return DOCK_KEY;
}
}
| agpl-3.0 |
NicolasEYSSERIC/Silverpeas-Core | ejb-core/formtemplate/src/main/java/com/silverpeas/workflow/api/TimeoutManager.java | 1384 | /**
* 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/>.
*/
package com.silverpeas.workflow.api;
/**
* The workflow engine services related to timeout (on active states) management.
*/
public interface TimeoutManager {
/**
* Initialize the timeout manager
*/
public void initialize();
} | agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/repository/gui/actions/PasteEntryRepositoryAction.java | 1862 | /**
* 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.repository.gui.actions;
import com.rapidminer.repository.Entry;
import com.rapidminer.repository.gui.RepositoryTree;
import java.awt.event.ActionEvent;
import javax.swing.Action;
/**
* This action is the standard paste action.
*
* @author Simon Fischer
*/
public class PasteEntryRepositoryAction extends AbstractRepositoryAction<Entry> {
private static final long serialVersionUID = 1L;
public PasteEntryRepositoryAction(RepositoryTree tree) {
super(tree, Entry.class, false, "repository_paste");
putValue(ACTION_COMMAND_KEY, "paste");
}
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
Action a = tree.getActionMap().get(action);
if (a != null) {
a.actionPerformed(new ActionEvent(tree, ActionEvent.ACTION_PERFORMED, null));
}
}
@Override
public void actionPerformed(Entry cast) {
// not needed because we override actionPerformed(ActionEvent e) which is the only caller
}
}
| agpl-3.0 |
JanMarvin/rstudio | src/gwt/src/org/rstudio/studio/client/workbench/views/source/events/EditPresentationSourceEvent.java | 1714 | /*
* EditPresentationSourceEvent.java
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* 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.events;
import org.rstudio.core.client.files.FileSystemItem;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
public class EditPresentationSourceEvent extends GwtEvent<EditPresentationSourceEvent.Handler>
{
public interface Handler extends EventHandler
{
void onEditPresentationSource(EditPresentationSourceEvent e);
}
public EditPresentationSourceEvent(FileSystemItem sourceFile,
int slideIndex)
{
sourceFile_ = sourceFile;
slideIndex_ = slideIndex;
}
public FileSystemItem getSourceFile()
{
return sourceFile_;
}
public int getSlideIndex()
{
return slideIndex_;
}
@Override
public Type<Handler> getAssociatedType()
{
return TYPE;
}
@Override
protected void dispatch(Handler handler)
{
handler.onEditPresentationSource(this);
}
private final FileSystemItem sourceFile_;
private final int slideIndex_;
public static final Type<Handler> TYPE = new Type<>();
}
| agpl-3.0 |
jerolba/torodb | engine/mongodb/repl/src/main/java/com/torodb/mongodb/repl/topology/TopologyGuiceModule.java | 2693 | /*
* ToroDB
* Copyright © 2014 8Kdata Technology (www.8kdata.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.torodb.mongodb.repl.topology;
import com.google.inject.Exposed;
import com.google.inject.PrivateModule;
import com.google.inject.Provides;
import com.torodb.core.concurrent.ConcurrentToolsFactory;
import com.torodb.core.supervision.Supervisor;
import com.torodb.mongodb.repl.SyncSourceProvider;
import com.torodb.mongodb.repl.guice.MongoDbRepl;
import java.time.Clock;
import java.time.Duration;
import java.util.concurrent.ThreadFactory;
import javax.inject.Singleton;
/**
*
*/
public class TopologyGuiceModule extends PrivateModule {
@Override
protected void configure() {
bind(HeartbeatNetworkHandler.class)
.to(MongoClientHeartbeatNetworkHandler.class)
.in(Singleton.class);
bind(SyncSourceProvider.class)
.to(RetrierTopologySyncSourceProvider.class)
.in(Singleton.class);
expose(SyncSourceProvider.class);
bind(TopologyErrorHandler.class)
.to(DefaultTopologyErrorHandler.class)
.in(Singleton.class);
bind(SyncSourceRetrier.class)
.in(Singleton.class);
bind(TopologyHeartbeatHandler.class)
.in(Singleton.class);
bind(TopologySyncSourceProvider.class)
.in(Singleton.class);
}
@Provides
@Topology
Supervisor getTopologySupervisor(@MongoDbRepl Supervisor replSupervisor) {
return replSupervisor;
}
@Provides
@Singleton
@Exposed
public TopologyService createTopologyService(ThreadFactory threadFactory,
TopologyHeartbeatHandler heartbeatHandler, TopologyExecutor executor,
Clock clock) {
return new TopologyService(heartbeatHandler, threadFactory, executor, clock);
}
@Provides
@Singleton
TopologyExecutor createTopologyExecutor(
ConcurrentToolsFactory concurrentToolsFactory) {
//TODO: Being able to configure max sync source lag and replication delay
return new TopologyExecutor(concurrentToolsFactory, Duration.ofMinutes(1),
Duration.ZERO);
}
}
| agpl-3.0 |
splicemachine/spliceengine | db-engine/src/main/java/com/splicemachine/db/iapi/sql/compile/RequiredRowOrdering.java | 5820 | /*
* 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/>.
*
* Some parts of this source code are based on Apache Derby, and the following notices apply to
* Apache Derby:
*
* Apache Derby is a subproject of the Apache DB project, and is licensed under
* the Apache License, Version 2.0 (the "License"); you may not use these files
* 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.
*
* Splice Machine, Inc. has modified the Apache Derby code in this file.
*
* All such Splice Machine modifications are Copyright 2012 - 2020 Splice Machine, Inc.,
* and are licensed to you under the GNU Affero General Public License.
*/
package com.splicemachine.db.iapi.sql.compile;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.util.JBitSet;
/**
* This interface provides a representation of the required ordering of rows
* from a ResultSet. Different operations can require ordering: ORDER BY,
* DISTINCT, GROUP BY. Some operations, like ORDER BY, require that the
* columns be ordered a particular way, while others, like DISTINCT and
* GROUP BY, reuire only that there be no duplicates in the result.
*/
public interface RequiredRowOrdering
{
int SORT_REQUIRED = 1;
int ELIMINATE_DUPS = 2;
int NOTHING_REQUIRED = 3;
/**
* Tell whether sorting is required for this RequiredRowOrdering,
* given a RowOrdering.
*
* @param rowOrdering The order of rows in question
* @param optimizableList The current join order being considered by
* the optimizer. We need to look into this to determine if the outer
* optimizables are single row resultset if the order by column is
* on an inner optimizable and that inner optimizable is not a one
* row resultset. DERBY-3926
*
* @return SORT_REQUIRED if sorting is required,
* ELIMINATE_DUPS if no sorting is required but duplicates
* must be eliminated (i.e. the rows are in
* the right order but there may be duplicates),
* NOTHING_REQUIRED is no operation is required
*
* @exception StandardException Thrown on error
*/
int sortRequired(RowOrdering rowOrdering, OptimizableList optimizableList) throws StandardException;
/**
* Tell whether sorting is required for this RequiredRowOrdering,
* given a RowOrdering representing a partial join order, and
* a bit map telling what tables are represented in the join order.
* This is useful for reducing the number of cases the optimizer
* has to consider.
*
* @param rowOrdering The order of rows in the partial join order
* @param tableMap A bit map of the tables in the partial join order
* @param optimizableList The current join order being considered by
* the optimizer. We need to look into this to determine if the outer
* optimizables are single row resultset if the order by column is
* on an inner optimizable and that inner optimizable is not a one
* row resultset. DERBY-3926
*
* @return SORT_REQUIRED if sorting is required,
* ELIMINATE_DUPS if no sorting is required by duplicates
* must be eliminated (i.e. the rows are in
* the right order but there may be duplicates),
* NOTHING_REQUIRED is no operation is required
*
* @exception StandardException Thrown on error
*/
int sortRequired(RowOrdering rowOrdering, JBitSet tableMap, OptimizableList optimizableList) throws StandardException;
/**
* Estimate the cost of doing a sort for this row ordering, given
* the number of rows to be sorted. This does not take into account
* whether the sort is really needed. It also estimates the number of
* result rows.
*
* @param rowOrdering The ordering of the input rows
*
* @exception StandardException Thrown on error
*/
void estimateCost(Optimizer optimizer,
RowOrdering rowOrdering,
CostEstimate baseCost,
CostEstimate sortCost)
throws StandardException;
/**
* Indicate that a sort is necessary to fulfill this required ordering.
* This method may be called many times during a single optimization.
*/
void sortNeeded();
/**
* Indicate that a sort is *NOT* necessary to fulfill this required
* ordering. This method may be called many times during a single
* optimization.
*/
void sortNotNeeded();
/**
* @return Whether or not a sort is needed.
*/
boolean isSortNeeded();
}
| agpl-3.0 |
ColostateResearchServices/kc | coeus-impl/src/main/java/org/kuali/kra/negotiations/lookup/IUNegotiationLookupableHelperServiceImpl.java | 19905 | package org.kuali.kra.negotiations.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.kuali.coeus.common.framework.custom.attr.CustomAttribute;
import org.kuali.coeus.common.framework.person.KcPerson;
import org.kuali.kra.negotiations.bo.Negotiation;
import org.kuali.kra.negotiations.customdata.NegotiationCustomData;
import org.kuali.rice.kns.lookup.HtmlData.AnchorHtmlData;
import org.kuali.rice.kns.web.struts.form.LookupForm;
import org.kuali.rice.kns.web.ui.Column;
import org.kuali.rice.kns.web.ui.Field;
import org.kuali.rice.kns.web.ui.ResultRow;
import org.kuali.rice.kns.web.ui.Row;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.lookup.CollectionIncomplete;
import org.kuali.rice.krad.util.BeanPropertyComparator;
import org.kuali.coeus.common.framework.person.KcPersonService;
import org.kuali.coeus.sys.framework.util.CollectionUtils;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import edu.iu.uits.kra.negotiations.lookup.IUNegotiationDaoOjb;
/**
* Negotiation Lookup Helper Service
*/
public class IUNegotiationLookupableHelperServiceImpl extends NegotiationLookupableHelperServiceImpl {
private static final long serialVersionUID = -7144337780492481726L;
private static final String USER_ID = "userId";
private NegotiationDao negotiationDao;
private KcPersonService kcPersonService;
@SuppressWarnings("unchecked")
@Override
public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) {
super.setBackLocationDocFormKey(fieldValues);
if (this.getParameters().containsKey(USER_ID)) {
fieldValues.put("associatedNegotiable.piId", ((String[]) this.getParameters().get(USER_ID))[0]);
fieldValues.put("negotiatorPersonId", ((String[]) this.getParameters().get(USER_ID))[0]);
}
List<Long> ids = null;
/* Begin IU Customization */
//UITSRA-2543
Map<String, String> formProps = new HashMap<String, String>();
if (!StringUtils.isEmpty(fieldValues.get("sponsorAwardNumber"))
&& !StringUtils.equals("*", fieldValues.get("sponsorAwardNumber").trim())) {
formProps.put("value", fieldValues.get("sponsorAwardNumber"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "SPON_AWD_ID"));
ids = getCustomDataIds(formProps, null);
}
fieldValues.remove("sponsorAwardNumber");
//UITSRA-2893, UITSRA-2894
if (!StringUtils.isEmpty(fieldValues.get("gsTeam")) && !StringUtils.equals("*", fieldValues.get("gsTeam").trim())) {
formProps.put("value", fieldValues.get("gsTeam"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "gsTeam"));
ids = getCustomDataIds(formProps, ids);
}
if (!StringUtils.isEmpty(fieldValues.get("recordResidesWith")) && !StringUtils.equals("*", fieldValues.get("recordResidesWith").trim())) {
formProps.put("value", fieldValues.get("recordResidesWith"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "recordLocation"));
ids = getCustomDataIds(formProps, ids);
}
if (!StringUtils.isEmpty(fieldValues.get("accountId")) && !StringUtils.equals("*", fieldValues.get("accountId").trim())) {
formProps.put("value", fieldValues.get("accountId"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "accountID"));
ids = getCustomDataIds(formProps, ids);
}
fieldValues.remove("recordResidesWith");
fieldValues.remove("gsTeam");
fieldValues.remove("accountId");
//End of UITSRA-2893, UITSRA-2894
// UITSRA-4218
if (!StringUtils.isEmpty(fieldValues.get("contractDate")) && !StringUtils.equals("*", fieldValues.get("contractDate").trim())) {
formProps.put("value", fieldValues.get("contractDate"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "contractDate"));
ids = getCustomDataIds(formProps, ids);
}
fieldValues.remove("contractDate");
// End of UITSRA-4218
// UITSRA-3190 -Add Person Lookup capability to Search screens
List<Long> piNegotiationIds = null;
if (fieldValues.containsKey("associatedNegotiable.principalInvestigatorUserName")) {
String piUserName = fieldValues.get("associatedNegotiable.principalInvestigatorUserName");
if (StringUtils.isNotBlank(piUserName)) {
// UITSRA-3477
if (StringUtils.contains(piUserName, "*")) {
piUserName = StringUtils.remove(piUserName, '*');
}
// End of UITSRA-3477
KcPerson person = getKcPersonService().getKcPersonByUserName(piUserName);
if (person != null && person.getPersonId() != null) {
piNegotiationIds = new ArrayList<Long>(((IUNegotiationDaoOjb) getNegotiationDao()).getNegotiationIdsByPI(person.getPersonId()));
if (piNegotiationIds.size() > 0) {
if (fieldValues.containsKey("negotiationId") && StringUtils.isNotBlank(fieldValues.get("negotiationId"))) {
String regex = "[0-9]+";
String negotiationId = fieldValues.get("negotiationId");
if (negotiationId.matches(regex)) {
if (!piNegotiationIds.contains(new Long(negotiationId))) {
return new ArrayList<Negotiation>();
}
}
}
else {
fieldValues.put("negotiationId", StringUtils.join(piNegotiationIds, '|'));
}
}
else {
fieldValues.put("associatedDocumentId", "Invalid PI Id");
}
}
else {
fieldValues.put("associatedDocumentId", "Invalid PI Id");
}
}
fieldValues.remove("associatedNegotiable.principalInvestigatorUserName");
}
// End of UITSRA-3190
// UITSRA-3191 - Change Negotiator Lookup field in Negotiation search options
KcPerson negotiator = null;
if (fieldValues.containsKey("negotiatorUserName") && StringUtils.isNotBlank(fieldValues.get("negotiatorUserName")) ) {
negotiator = getKcPersonService().getKcPersonByUserName(fieldValues.get("negotiatorUserName"));
if (negotiator != null && StringUtils.isNotBlank(negotiator.getPersonId())) {
fieldValues.put("negotiatorPersonId", negotiator.getPersonId());
}
else {
fieldValues.put("negotiatorPersonId", "Invalid Negotiator Person Id");
}
fieldValues.remove("negotiatorUserName");
}
// End of UITSRA-3191
// UITSRA-3761 - Update Negotiation Search Options and Results
List<Long> subAwardNegotiationIds = null;
if (fieldValues.containsKey("associatedNegotiable.requisitionerUserName")) {
String requisitionerUserName = fieldValues.get("associatedNegotiable.requisitionerUserName");
if (StringUtils.isNotBlank(requisitionerUserName)) {
if (StringUtils.contains(requisitionerUserName, "*")) {
requisitionerUserName = StringUtils.remove(requisitionerUserName, '*');
}
KcPerson person = getKcPersonService().getKcPersonByUserName(requisitionerUserName);
if (person != null && person.getPersonId() != null) {
subAwardNegotiationIds = new ArrayList<Long>(((IUNegotiationDaoOjb) getNegotiationDao()).getNegotiationIdsByRequisitioner(person.getPersonId()));
if (subAwardNegotiationIds.size() > 0) {
if (fieldValues.containsKey("negotiationId") && StringUtils.isNotBlank(fieldValues.get("negotiationId"))) {
String regex = "[0-9]+";
String negotiationId = fieldValues.get("negotiationId");
if (negotiationId.matches(regex)) {
if (!subAwardNegotiationIds.contains(new Long(negotiationId))) {
return new ArrayList<Negotiation>();
}
}
}
else {
fieldValues.put("negotiationId", StringUtils.join(subAwardNegotiationIds, '|'));
}
}
else {
fieldValues.put("associatedDocumentId", "Invalid PI Id");
}
}
else {
fieldValues.put("associatedDocumentId", "Invalid PI Id");
}
}
fieldValues.remove("associatedNegotiable.requisitionerUserName");
fieldValues.remove("associatedNegotiable.subAwardRequisitionerId");
}
if (!StringUtils.isEmpty(fieldValues.get("modification_id")) && !StringUtils.equals("*", fieldValues.get("modification_id").trim())) {
formProps.put("value", fieldValues.get("modification_id"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "MOD_NUM"));
ids = getCustomDataIds(formProps, ids);
}
if (!StringUtils.isEmpty(fieldValues.get("proposalDocID")) && !StringUtils.equals("*", fieldValues.get("proposalDocID").trim())) {
formProps.put("value", fieldValues.get("proposalDocID"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "proposalDocID"));
ids = getCustomDataIds(formProps, ids);
}
if (!StringUtils.isEmpty(fieldValues.get("ipid")) && !StringUtils.equals("*", fieldValues.get("ipid").trim())) {
formProps.put("value", fieldValues.get("ipid"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "CSU_REF_NUM"));
ids = getCustomDataIds(formProps, ids);
}
if (!StringUtils.isEmpty(fieldValues.get("proposalType")) && !StringUtils.equals("*", fieldValues.get("proposalType").trim())) {
formProps.put("value", fieldValues.get("proposalType"));
formProps.put("customAttributeId", getCustomAttributeId("Grant Services Negotiations", "proposalType"));
ids = getCustomDataIds(formProps, ids);
}
fieldValues.remove("modification_id");
fieldValues.remove("proposalDocID");
fieldValues.remove("ipid");
fieldValues.remove("proposalType");
// End of UITSRA-3761
if (!StringUtils.isEmpty(fieldValues.get("ricroCleared")) ) {
formProps.put("value", fieldValues.get("ricroCleared"));
formProps.put("customAttributeId", getCustomAttributeId("SP Office Negotiations", "RICRO_CLEARED"));
ids = getCustomDataIds(formProps, ids);
}
fieldValues.remove("ricroCleared");
if (!StringUtils.isEmpty(fieldValues.get("coiCleared")) ) {
formProps.put("value", fieldValues.get("coiCleared"));
formProps.put("customAttributeId", getCustomAttributeId("SP Office Negotiations", "COI_CLEARED"));
ids = getCustomDataIds(formProps, ids);
}
fieldValues.remove("coiCleared");
if (!StringUtils.isEmpty(fieldValues.get("proposalActionType")) ) {
formProps.put("value", fieldValues.get("proposalActionType"));
formProps.put("customAttributeId", getCustomAttributeId("SP Office Negotiations", "PROP_ACTION_TYPE"));
ids = getCustomDataIds(formProps, ids);
}
fieldValues.remove("proposalActionType");
if (!StringUtils.isEmpty(fieldValues.get("csuRefNum")) && !StringUtils.equals("*", fieldValues.get("csuRefNum").trim())) {
formProps.put("value", fieldValues.get("csuRefNum"));
formProps.put("customAttributeId", getCustomAttributeId("All Negotiations", "CSU_REF_NUM"));
ids = getCustomDataIds(formProps, ids);
}
fieldValues.remove("csuRefNum");
/* CSU customization custom data arg search fix */
fieldValues.put("negotiationCustomDataList.negotiationCustomDataId", StringUtils.join(ids, '|'));
/* End IU Customization */
// UITSRA-3138
// In class LookupDaoOjb.java (method addCriteria()), a String data type is required in order to create the
// search criteria for a Negotiation Id wild card search. Currently negotiationId is Long rather than String,
// which is not consistent with other KC modules like Award, IP etc. The ideal fix is to change the Negotiation Id's
// data type from Long to String, but it requires a major design change on the foundation side.
List<Long> wildcardNegotiationIds = null;
if (fieldValues.containsKey("negotiationId") && fieldValues.get("negotiationId").contains("*")) {
wildcardNegotiationIds = new ArrayList<Long>(((IUNegotiationDaoOjb) getNegotiationDao()).getNegotiationIdsWithWildcard(fieldValues.get("negotiationId")));
fieldValues.put("negotiationId", StringUtils.join(wildcardNegotiationIds, '|'));
}
List<Negotiation> searchResults = new ArrayList<Negotiation>();
CollectionIncomplete<Negotiation> limitedSearchResults;
// UITSRA-3138
if (wildcardNegotiationIds == null || wildcardNegotiationIds.size() != 0 ||
piNegotiationIds == null || piNegotiationIds.size() != 0) {
// UITSRA-4033
limitedSearchResults = (CollectionIncomplete<Negotiation>) getNegotiationDao().getNegotiationResults(fieldValues);
searchResults.addAll(limitedSearchResults);
List defaultSortColumns = getDefaultSortColumns();
if (defaultSortColumns.size() > 0) {
org.kuali.coeus.sys.framework.util.CollectionUtils.sort(searchResults, new BeanPropertyComparator(defaultSortColumns, true)); //UITSRA-4320
return new CollectionIncomplete<Negotiation>(searchResults, limitedSearchResults.getActualSizeIfTruncated());
}
return limitedSearchResults;
}
return searchResults;
}
/**
* @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#getRows()
*/
@Override
public List<Row> getRows() {
List<Row> rows = super.getRows();
for (Row row : rows) {
for (Field field : row.getFields()) {
if (field.getPropertyName().equals("negotiatorUserName")) {
field.setFieldConversions("principalName:negotiatorUserName,principalId:negotiatorPersonId");
}
if (field.getPropertyName().equals("associatedNegotiable.principalInvestigatorUserName")) {
field.setFieldConversions("principalName:associatedNegotiable.principalInvestigatorUserName,principalId:associatedNegotiable.principalInvestigatorPersonId");
}
if (field.getPropertyName().equals("associatedNegotiable.requisitionerUserName")) {
field.setFieldConversions("principalName:associatedNegotiable.requisitionerUserName,principalId:associatedNegotiable.subAwardRequisitionerId");
}
}
}
return rows;
}
public KcPersonService getKcPersonService() {
if (this.kcPersonService == null) {
this.kcPersonService = KcServiceLocator.getService(KcPersonService.class);
}
return this.kcPersonService;
}
/* Begin IU Customization */
public String getCustomAttributeId(String groupName, String attributeName) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put("groupName", groupName);
fieldValues.put("name", attributeName);
List<CustomAttribute> customAttributes = (List<CustomAttribute>) getBusinessObjectService().findMatching(CustomAttribute.class, fieldValues);
if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(customAttributes)) {
return customAttributes.get(0).getId().toString();
}
else {
return null;
}
}
/**
* Call's the super class's performLookup function and edits the URLs for the unit name, unit number, sponsor name, subAwardOrganization name, and pi name.
* @see org.kuali.kra.lookup.KraLookupableHelperServiceImpl#performLookup(LookupForm, Collection, boolean)
*/
@Override
public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) {
final String leadUnitName = "associatedNegotiable.leadUnitName";
final String leadUnitNumber = "associatedNegotiable.leadUnitNumber";
final String sponsorName = "associatedNegotiable.sponsorName";
final String piName = "associatedNegotiable.piName";
final String subAwardOrganizationName = "associatedNegotiable.subAwardOrganizationName";
Collection lookupStuff = super.performLookup(lookupForm, resultTable, bounded);
Iterator i = resultTable.iterator();
while (i.hasNext()) {
ResultRow row = (ResultRow) i.next();
for (Column column : row.getColumns()) {
//the Subaward Organization name, unit name, pi Name and sponsor name don't need to generate links.
if (StringUtils.equalsIgnoreCase(column.getPropertyName(), leadUnitName)
|| StringUtils.equalsIgnoreCase(column.getPropertyName(), sponsorName)
|| StringUtils.equalsIgnoreCase(column.getPropertyName(), subAwardOrganizationName)
|| StringUtils.equalsIgnoreCase(column.getPropertyName(), piName)) {
column.setPropertyURL("");
for (AnchorHtmlData data : column.getColumnAnchors()) {
if (data != null) {
data.setHref("");
}
}
}
if (StringUtils.equalsIgnoreCase(column.getPropertyName(), leadUnitNumber)){
String unitNumber = column.getPropertyValue();
//String newUrl = "http://127.0.0.1:8080/kc-dev/kr/inquiry.do?businessObjectClassName=org.kuali.kra.bo.Unit&unitNumber=" + unitNumber + "&methodToCall=start";
String newUrl = "inquiry.do?businessObjectClassName=org.kuali.kra.bo.Unit&unitNumber=" + unitNumber + "&methodToCall=start";
column.setPropertyURL(newUrl);
for (AnchorHtmlData data : column.getColumnAnchors()) {
if (data != null) {
data.setHref(newUrl);
}
}
}
}
}
return lookupStuff;
}
/* End IU Customization */
protected List<Long> getCustomDataIds(Map<String, String> formProps, List<Long> commonIds) {
List<Long> ids = null;
// UITSRA-3138
Collection<NegotiationCustomData> customDatas = getLookupService().findCollectionBySearchUnbounded(NegotiationCustomData.class, formProps);
if (!customDatas.isEmpty()) {
ids = new ArrayList<Long>();
for (NegotiationCustomData customData : customDatas) {
ids.add(customData.getNegotiationCustomDataId());
}
}
if (commonIds != null && ids !=null ) {
ids.retainAll(commonIds);
}
return ids;
}
}
| agpl-3.0 |
othmanelmoulat/jbilling-2.2-Extentions | src/build/jsp-classes/com/sapienter/jbilling/client/jspc/user/listSubAccountsTop_jsp.java | 16631 | package com.sapienter.jbilling.client.jspc.user;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.sapienter.jbilling.client.util.Constants;;
public final class listSubAccountsTop_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.release();
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.release();
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.release();
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.release();
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<p class=\"title\">\r\n");
if (_jspx_meth_bean_005fmessage_005f0(_jspx_page_context))
return;
out.write("\r\n</p>\r\n<p class=\"instr\">\r\n");
if (_jspx_meth_bean_005fmessage_005f1(_jspx_page_context))
return;
out.write("\r\n</p>\r\n\r\n");
// html:messages
org.apache.struts.taglib.html.MessagesTag _jspx_th_html_005fmessages_005f0 = (org.apache.struts.taglib.html.MessagesTag) _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.get(org.apache.struts.taglib.html.MessagesTag.class);
_jspx_th_html_005fmessages_005f0.setPageContext(_jspx_page_context);
_jspx_th_html_005fmessages_005f0.setParent(null);
// /user/listSubAccountsTop.jsp(36,0) name = message type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_html_005fmessages_005f0.setMessage("true");
// /user/listSubAccountsTop.jsp(36,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_html_005fmessages_005f0.setId("myMessage");
int _jspx_eval_html_005fmessages_005f0 = _jspx_th_html_005fmessages_005f0.doStartTag();
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
java.lang.String myMessage = null;
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_html_005fmessages_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_html_005fmessages_005f0.doInitBody();
}
myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage");
do {
out.write("\r\n\t<p>");
if (_jspx_meth_bean_005fwrite_005f0(_jspx_th_html_005fmessages_005f0, _jspx_page_context))
return;
out.write("</p>\r\n");
int evalDoAfterBody = _jspx_th_html_005fmessages_005f0.doAfterBody();
myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage");
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_html_005fmessages_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0);
return;
}
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0);
out.write("\r\n\r\n");
out.write('\r');
out.write('\n');
// bean:define
org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f0 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class);
_jspx_th_bean_005fdefine_005f0.setPageContext(_jspx_page_context);
_jspx_th_bean_005fdefine_005f0.setParent(null);
// /user/listSubAccountsTop.jsp(42,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setId("forward_from");
// /user/listSubAccountsTop.jsp(42,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setValue(Constants.FORWARD_USER_MAINTAIN);
// /user/listSubAccountsTop.jsp(42,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setToScope("session");
int _jspx_eval_bean_005fdefine_005f0 = _jspx_th_bean_005fdefine_005f0.doStartTag();
if (_jspx_th_bean_005fdefine_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0);
return;
}
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0);
java.lang.String forward_from = null;
forward_from = (java.lang.String) _jspx_page_context.findAttribute("forward_from");
out.write("\r\n\r\n");
// bean:define
org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f1 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class);
_jspx_th_bean_005fdefine_005f1.setPageContext(_jspx_page_context);
_jspx_th_bean_005fdefine_005f1.setParent(null);
// /user/listSubAccountsTop.jsp(46,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setId("forward_to");
// /user/listSubAccountsTop.jsp(46,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setValue(Constants.FORWARD_USER_VIEW);
// /user/listSubAccountsTop.jsp(46,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setToScope("session");
int _jspx_eval_bean_005fdefine_005f1 = _jspx_th_bean_005fdefine_005f1.doStartTag();
if (_jspx_th_bean_005fdefine_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1);
return;
}
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1);
java.lang.String forward_to = null;
forward_to = (java.lang.String) _jspx_page_context.findAttribute("forward_to");
out.write("\r\n\r\n");
// jbilling:genericList
com.sapienter.jbilling.client.list.GenericListTag _jspx_th_jbilling_005fgenericList_005f0 = (com.sapienter.jbilling.client.list.GenericListTag) _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.get(com.sapienter.jbilling.client.list.GenericListTag.class);
_jspx_th_jbilling_005fgenericList_005f0.setPageContext(_jspx_page_context);
_jspx_th_jbilling_005fgenericList_005f0.setParent(null);
// /user/listSubAccountsTop.jsp(50,0) name = setup type = java.lang.Boolean reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_jbilling_005fgenericList_005f0.setSetup(new Boolean(true));
// /user/listSubAccountsTop.jsp(50,0) name = type type = java.lang.String reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_jbilling_005fgenericList_005f0.setType(Constants.LIST_TYPE_SUB_ACCOUNTS);
int _jspx_eval_jbilling_005fgenericList_005f0 = _jspx_th_jbilling_005fgenericList_005f0.doStartTag();
if (_jspx_th_jbilling_005fgenericList_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0);
return;
}
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0);
out.write('\r');
out.write('\n');
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_bean_005fmessage_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// bean:message
org.apache.struts.taglib.bean.MessageTag _jspx_th_bean_005fmessage_005f0 = (org.apache.struts.taglib.bean.MessageTag) _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.get(org.apache.struts.taglib.bean.MessageTag.class);
_jspx_th_bean_005fmessage_005f0.setPageContext(_jspx_page_context);
_jspx_th_bean_005fmessage_005f0.setParent(null);
// /user/listSubAccountsTop.jsp(30,0) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fmessage_005f0.setKey("user.subaccount.title");
int _jspx_eval_bean_005fmessage_005f0 = _jspx_th_bean_005fmessage_005f0.doStartTag();
if (_jspx_th_bean_005fmessage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_bean_005fmessage_005f0);
return true;
}
_005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_bean_005fmessage_005f0);
return false;
}
private boolean _jspx_meth_bean_005fmessage_005f1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// bean:message
org.apache.struts.taglib.bean.MessageTag _jspx_th_bean_005fmessage_005f1 = (org.apache.struts.taglib.bean.MessageTag) _005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.get(org.apache.struts.taglib.bean.MessageTag.class);
_jspx_th_bean_005fmessage_005f1.setPageContext(_jspx_page_context);
_jspx_th_bean_005fmessage_005f1.setParent(null);
// /user/listSubAccountsTop.jsp(33,0) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fmessage_005f1.setKey("customer.list.instr");
int _jspx_eval_bean_005fmessage_005f1 = _jspx_th_bean_005fmessage_005f1.doStartTag();
if (_jspx_th_bean_005fmessage_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_bean_005fmessage_005f1);
return true;
}
_005fjspx_005ftagPool_005fbean_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_bean_005fmessage_005f1);
return false;
}
private boolean _jspx_meth_bean_005fwrite_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_005fmessages_005f0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// bean:write
org.apache.struts.taglib.bean.WriteTag _jspx_th_bean_005fwrite_005f0 = (org.apache.struts.taglib.bean.WriteTag) _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.get(org.apache.struts.taglib.bean.WriteTag.class);
_jspx_th_bean_005fwrite_005f0.setPageContext(_jspx_page_context);
_jspx_th_bean_005fwrite_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_005fmessages_005f0);
// /user/listSubAccountsTop.jsp(37,4) name = name type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fwrite_005f0.setName("myMessage");
int _jspx_eval_bean_005fwrite_005f0 = _jspx_th_bean_005fwrite_005f0.doStartTag();
if (_jspx_th_bean_005fwrite_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0);
return true;
}
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0);
return false;
}
}
| agpl-3.0 |
Periapsis/aphelion | src/main/java/aphelion/shared/event/promise/PromiseRejected.java | 2044 | /*
* Aphelion
* Copyright (c) 2013 Joris van der Wel
*
* This file is part of Aphelion
*
* Aphelion 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.
*
* Aphelion 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 Aphelion. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, the following supplemental terms apply, based on section 7 of
* the GNU Affero General Public License (version 3):
* a) Preservation of all legal notices and author attributions
* b) Prohibition of misrepresentation of the origin of this material, and
* modified versions are required to be marked in reasonable ways as
* different from the original version (for example by appending a copyright notice).
*
* Linking this library statically or dynamically with other modules is making a
* combined work based on this library. Thus, the terms and conditions of the
* GNU Affero General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library.
*/
package aphelion.shared.event.promise;
/**
*
* @author Joris
*/
public interface PromiseRejected
{
void rejected(PromiseException error);
}
| agpl-3.0 |
Tesora/tesora-dve-pub | tesora-dve-core/src/main/java/com/tesora/dve/sql/statement/CacheableStatement.java | 1022 | package com.tesora.dve.sql.statement;
/*
* #%L
* Tesora Inc.
* Database Virtualization Engine
* %%
* Copyright (C) 2011 - 2014 Tesora 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.
*
* 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/>.
* #L%
*/
import com.tesora.dve.lockmanager.LockType;
import com.tesora.dve.sql.expression.TableKey;
import com.tesora.dve.sql.util.ListSet;
public interface CacheableStatement {
public LockType getLockType();
public ListSet<TableKey> getAllTableKeys();
}
| agpl-3.0 |
aborg0/rapidminer-studio | src/main/java/com/rapidminer/gui/viewer/ConfusionMatrixViewer.java | 7016 | /**
* Copyright (C) 2001-2019 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.viewer;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import com.rapidminer.datatable.SimpleDataTable;
import com.rapidminer.datatable.SimpleDataTableRow;
import com.rapidminer.gui.actions.export.PrintableComponent;
import com.rapidminer.gui.look.Colors;
import com.rapidminer.gui.plotter.PlotterConfigurationModel;
import com.rapidminer.gui.tools.ExtendedJScrollPane;
import com.rapidminer.report.Tableable;
import com.rapidminer.tools.I18N;
/**
* This viewer class can be used to display performance criteria based on a multi class confusion
* matrix. The viewer consists of two parts, first a part containing the general performance info
* string and second a table with the complete confusion matrix.
*
* @author Ingo Mierswa
*/
public class ConfusionMatrixViewer extends JPanel implements Tableable, PrintableComponent {
private static final long serialVersionUID = 3448880915145528006L;
private ConfusionMatrixViewerTable table;
private JComponent plotter;
private String performanceName;
public ConfusionMatrixViewer(String performanceName, String performanceString, String[] classNames, double[][] counter) {
this.performanceName = performanceName;
setLayout(new BorderLayout());
final JPanel mainPanel = new JPanel();
mainPanel.setOpaque(true);
mainPanel.setBackground(Colors.WHITE);
final CardLayout cardLayout = new CardLayout();
mainPanel.setLayout(cardLayout);
add(mainPanel, BorderLayout.CENTER);
// *** table panel ***
JPanel tablePanel = new JPanel(new BorderLayout());
tablePanel.setOpaque(true);
tablePanel.setBackground(Colors.WHITE);
tablePanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
// info string
JPanel infoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
infoPanel.setOpaque(true);
infoPanel.setBackground(Colors.WHITE);
JTextPane infoText = new JTextPane();
infoText.setEditable(false);
infoText.setBackground(infoPanel.getBackground());
infoText.setFont(infoText.getFont().deriveFont(Font.BOLD));
infoText.setText(performanceString);
infoPanel.add(infoText);
tablePanel.add(infoPanel, BorderLayout.NORTH);
// table
table = new ConfusionMatrixViewerTable(classNames, counter);
table.setBorder(BorderFactory.createLineBorder(Colors.TABLE_CELL_BORDER));
JScrollPane scrollPane = new ExtendedJScrollPane(table);
scrollPane.setBorder(null);
scrollPane.setBackground(Colors.WHITE);
scrollPane.getViewport().setBackground(Colors.WHITE);
tablePanel.add(scrollPane, BorderLayout.CENTER);
table.setTableHeader(null);
// *** plot panel ***
SimpleDataTable dataTable = new SimpleDataTable("Confusion Matrix", new String[] { "True Class", "Predicted Class",
"Confusion Matrix (x: true class, y: pred. class, z: counters)" });
for (int row = 0; row < classNames.length; row++) {
for (int column = 0; column < classNames.length; column++) {
dataTable.add(new SimpleDataTableRow(new double[] { row, column, counter[row][column] }));
}
}
PlotterConfigurationModel settings = new PlotterConfigurationModel(PlotterConfigurationModel.STICK_CHART_3D,
dataTable);
settings.setAxis(0, 0);
settings.setAxis(1, 1);
settings.enablePlotColumn(2);
mainPanel.add(tablePanel, "table");
plotter = settings.getPlotter().getPlotter();
mainPanel.add(plotter, "plot");
// toggle radio button for views
final JRadioButton metaDataButton = new JRadioButton("Table View", true);
metaDataButton.setToolTipText("Changes to a table showing the confusion matrix.");
metaDataButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (metaDataButton.isSelected()) {
cardLayout.show(mainPanel, "table");
}
}
});
final JRadioButton plotButton = new JRadioButton("Plot View", false);
plotButton.setToolTipText("Changes to a plot view of the confusion matrix.");
plotButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (plotButton.isSelected()) {
cardLayout.show(mainPanel, "plot");
}
}
});
ButtonGroup group = new ButtonGroup();
group.add(metaDataButton);
group.add(plotButton);
JPanel togglePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
togglePanel.setOpaque(true);
togglePanel.setBackground(Colors.WHITE);
togglePanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
togglePanel.add(metaDataButton);
togglePanel.add(plotButton);
add(togglePanel, BorderLayout.NORTH);
}
@Override
public void prepareReporting() {
table.prepareReporting();
}
@Override
public void finishReporting() {
table.finishReporting();
}
@Override
public boolean isFirstLineHeader() {
return true;
}
@Override
public boolean isFirstColumnHeader() {
return true;
}
@Override
public String getColumnName(int columnIndex) {
return table.getColumnName(columnIndex);
}
@Override
public String getCell(int row, int column) {
return table.getCell(row, column);
}
@Override
public int getColumnNumber() {
return table.getColumnNumber();
}
@Override
public int getRowNumber() {
return table.getRowNumber();
}
@Override
public Component getExportComponent() {
return plotter;
}
@Override
public String getExportName() {
return I18N.getGUIMessage("gui.cards.result_view.confusion_matrix.title");
}
@Override
public String getIdentifier() {
return performanceName;
}
@Override
public String getExportIconName() {
return I18N.getGUIMessage("gui.cards.result_view.confusion_matrix.icon");
}
}
| agpl-3.0 |
WenbinHou/PKUAutoGateway.Android | Reference/IPGWAndroid/android/support/v7/a/ad.java | 390 | package android.support.v7.a;
final class ad implements Runnable {
final /* synthetic */ ac a;
ad(ac acVar) {
this.a = acVar;
}
public final void run() {
if ((this.a.I & 1) != 0) {
ac.a(this.a, 0);
}
if ((this.a.I & 4096) != 0) {
ac.a(this.a, 108);
}
this.a.H = false;
this.a.I = 0;
}
}
| agpl-3.0 |
shenan4321/BIMplatform | generated/cn/dlb/bim/models/ifc4/impl/IfcSlabTypeImpl.java | 2127 | /**
* 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.impl;
import org.eclipse.emf.ecore.EClass;
import cn.dlb.bim.models.ifc4.Ifc4Package;
import cn.dlb.bim.models.ifc4.IfcSlabType;
import cn.dlb.bim.models.ifc4.IfcSlabTypeEnum;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ifc Slab Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link cn.dlb.bim.models.ifc4.impl.IfcSlabTypeImpl#getPredefinedType <em>Predefined Type</em>}</li>
* </ul>
*
* @generated
*/
public class IfcSlabTypeImpl extends IfcBuildingElementTypeImpl implements IfcSlabType {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IfcSlabTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Ifc4Package.Literals.IFC_SLAB_TYPE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IfcSlabTypeEnum getPredefinedType() {
return (IfcSlabTypeEnum) eGet(Ifc4Package.Literals.IFC_SLAB_TYPE__PREDEFINED_TYPE, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPredefinedType(IfcSlabTypeEnum newPredefinedType) {
eSet(Ifc4Package.Literals.IFC_SLAB_TYPE__PREDEFINED_TYPE, newPredefinedType);
}
} //IfcSlabTypeImpl
| agpl-3.0 |
spectrumauctions/sats-core | src/main/java/org/spectrumauctions/sats/core/util/random/UniformJavaUtilRandomWrapper.java | 2952 | /**
* Copyright by Michael Weiss, weiss.michael@gmx.ch
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.spectrumauctions.sats.core.util.random;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;
public class UniformJavaUtilRandomWrapper implements UniformDistributionRNG {
/**
*
*/
private static final long serialVersionUID = 4285241684660761136L;
private Random rng;
public UniformJavaUtilRandomWrapper() {
this(new Date().getTime());
}
public UniformJavaUtilRandomWrapper(long seed) {
this.rng = new Random(seed);
}
@Override
public int nextInt() {
return rng.nextInt();
}
@Override
public int nextInt(int lowerLimit, int upperLimit) {
if (upperLimit == Integer.MAX_VALUE)
upperLimit--;
return rng.nextInt((upperLimit - lowerLimit) + 1) + lowerLimit;
}
@Override
public int nextInt(IntegerInterval interval) {
return nextInt(interval.getMinValue(), interval.getMaxValue());
}
@Override
public double nextDouble() {
return rng.nextDouble();
}
@Override
public double nextDouble(double lowerLimit, double upperLimit) {
return rng.nextDouble() * (upperLimit - lowerLimit) + lowerLimit;
}
@Override
public long nextLong() {
return rng.nextLong();
}
@Override
public double nextDouble(DoubleInterval interval) {
return nextDouble(interval.getMinValue(), interval.getMaxValue());
}
/*
* (non-Javadoc)
*
* @see UniformDistributionRNG#nextBigDecimal()
*/
@Override
public BigDecimal nextBigDecimal() {
return new BigDecimal(nextDouble());
}
/*
* (non-Javadoc)
*
* @see UniformDistributionRNG#nextBigDecimal(double, double)
*/
@Override
public BigDecimal nextBigDecimal(double lowerLimit, double upperLimit) {
return new BigDecimal(nextDouble(lowerLimit, upperLimit));
}
/*
* (non-Javadoc)
*
* @see
* UniformDistributionRNG#nextBigDecimal(org.spectrumauctions.sats.core.util
* .random.DoubleInterval)
*/
@Override
public BigDecimal nextBigDecimal(DoubleInterval interval) {
return new BigDecimal(nextDouble(interval));
}
/*
* (non-Javadoc)
*
* @see UniformDistributionRNG#nextInt(int)
*/
@Override
public int nextInt(int upperLimit) {
return rng.nextInt(upperLimit);
}
}
| agpl-3.0 |
opencadc/tap | cadc-adql/src/test/java/ca/nrc/cadc/tap/parser/RegionFinderTest.java | 7944 | /*
************************************************************************
******************* 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.tap.parser;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import ca.nrc.cadc.tap.AdqlQuery;
import ca.nrc.cadc.tap.TapQuery;
import ca.nrc.cadc.tap.parser.navigator.ExpressionNavigator;
import ca.nrc.cadc.tap.parser.navigator.FromItemNavigator;
import ca.nrc.cadc.tap.parser.navigator.ReferenceNavigator;
import ca.nrc.cadc.tap.parser.schema.BlobClobColumnValidator;
import ca.nrc.cadc.tap.parser.schema.ExpressionValidator;
import ca.nrc.cadc.tap.parser.schema.TapSchemaTableValidator;
import ca.nrc.cadc.tap.schema.TapSchema;
import ca.nrc.cadc.util.Log4jInit;
import ca.nrc.cadc.uws.Job;
import ca.nrc.cadc.uws.Parameter;
import junit.framework.Assert;
import org.apache.log4j.Logger;
/**
* general test of ADQL function finder
*
* @author Sailor Zhang
*
*/
public class RegionFinderTest
{
private static Logger log = Logger.getLogger(RegionFinderTest.class);
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
Log4jInit.setLevel("ca.nrc.cadc", org.apache.log4j.Level.INFO);
}
/**
* @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
{
}
Job job = new Job()
{
@Override
public String getID() { return "abcdefg"; }
};
private void doit(String query)
{
try
{
log.debug("IN: " + query);
Parameter para = new Parameter("QUERY", query);
job.getParameterList().add(para);
TapQuery tapQuery = new TestQuery();
tapQuery.setJob(job);
String sql = tapQuery.getSQL();
//List<TapSelectItem> selectList = tapQuery.getSelectList();
log.debug("OUT: " + sql);
//log.debug("select-list: " + selectList);
}
finally
{
job.getParameterList().clear();
}
}
@Test
public void testAll()
{
String query = "select COORDSYS(a), COORD1(a), COORD2(a) from someTable as a"
+ " where 0 = CONTAINS(POINT('ICRS GEOCENTER', 25.0, -19.5), someRegionColumn) "
+ " and INTERSECTS(a.someShape, CIRCLE('ICRS', 12, 34, 5))=1 "
+ " and DISTANCE(a.someShape, POINT('ICRS', 12, 34)) < 1 ";
try
{
doit(query);
Assert.fail("expected UnsupportedOperationException, got nothing");
}
catch(UnsupportedOperationException expected)
{
}
catch(Throwable unexpected)
{
Assert.fail("expected exception: " + unexpected);
}
}
@Test
public void testCountStar()
{
String query = "select count(*) from SomeTable";
doit(query);
}
// TODO: re-instate fake TapSchema and test select list processing carefully
static class TestQuery extends AdqlQuery
{
@Override
protected void init()
{
//super.init();
TapSchema tapSchema = TestUtil.mockTapSchema();
ExpressionNavigator en = new ExpressionValidator(tapSchema);
ReferenceNavigator rn = new BlobClobColumnValidator(tapSchema);
FromItemNavigator fn = new TapSchemaTableValidator(tapSchema);
super.navigatorList.add(new RegionFinder(en, rn, fn));
}
}
}
| agpl-3.0 |
ungerik/ephesoft | Ephesoft_Community_Release_4.0.2.0/source/gxt/gxt-review-validate/src/main/java/com/ephesoft/gxt/rv/client/event/DocumentSplitStartEvent.java | 3107 | /*********************************************************************************
* Ephesoft is a Intelligent Document Capture and Mailroom Automation program
* developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft 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 EPHESOFT, EPHESOFT 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.
*
* You can contact Ephesoft, Inc. headquarters at 111 Academy Way,
* Irvine, CA 92617, USA. or at email address info@ephesoft.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 "Ephesoft" logo.
* If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by Ephesoft".
********************************************************************************/
package com.ephesoft.gxt.rv.client.event;
import com.ephesoft.dcma.batch.schema.Document;
import com.ephesoft.dcma.batch.schema.Page;
import com.google.web.bindery.event.shared.binder.GenericEvent;
public class DocumentSplitStartEvent extends GenericEvent {
private Document bindedDocument;
private Page fromPage;
private boolean stickFields;
private boolean stickTables;
public DocumentSplitStartEvent(Document bindedDocument, Page fromPage, boolean stickFields, boolean stickTables) {
this.bindedDocument = bindedDocument;
this.fromPage = fromPage;
this.stickFields = stickFields;
this.stickTables = stickTables;
}
/**
* @return the bindedDocument
*/
public Document getBindedDocument() {
return bindedDocument;
}
/**
* @return the fromPage
*/
public Page getFromPage() {
return fromPage;
}
public boolean isStickFields() {
return stickFields;
}
public void setStickFields(boolean stickFields) {
this.stickFields = stickFields;
}
public boolean isStickTables() {
return stickTables;
}
public void setStickTables(boolean stickTables) {
this.stickTables = stickTables;
}
}
| agpl-3.0 |
simplyianm/SuperPlots | src/main/java/com/simplyian/superplots/EconHook.java | 1693 | package com.simplyian.superplots;
import java.util.logging.Level;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.plugin.RegisteredServiceProvider;
public class EconHook {
private final SuperPlotsPlugin main;
private Economy economy = null;
public EconHook(SuperPlotsPlugin main) {
this.main = main;
}
public void setupEconomy() {
RegisteredServiceProvider<Economy> economyProvider = main.getServer()
.getServicesManager().getRegistration(Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
if (economy == null) {
main.getLogger()
.log(Level.SEVERE,
"No supported economy by Vault detected! Things WILL go wrong!");
}
}
/**
* Gets the balance of a player.
*
* @param player
* @return
*/
public double getBalance(String player) {
return economy.getBalance(player);
}
/**
* Sets the balance of a player.
*
* @param player
* @param amt
*/
public void setBalance(String player, double amt) {
economy.depositPlayer(player, amt);
}
/**
* Adds money to a player's account.
*
* @param player
* @param cost
*/
public void addBalance(String name, int cost) {
setBalance(name, getBalance(name) + cost);
}
/**
* Subtracts an amount of money from a player's account.
*
* @param name
* @param cost
*/
public void subtractBalance(String name, int cost) {
setBalance(name, getBalance(name) - cost);
}
}
| agpl-3.0 |
tyatsumi/hareka | server/src/main/java/org/kareha/hareka/server/game/item/NoticeItem.java | 1439 | package org.kareha.hareka.server.game.item;
import org.kareha.hareka.field.TileType;
import org.kareha.hareka.game.ItemType;
import org.kareha.hareka.server.game.entity.CharacterEntity;
import org.kareha.hareka.server.game.entity.FieldEntity;
import org.kareha.hareka.server.game.entity.ItemEntity;
import org.kareha.hareka.util.Name;
import org.kareha.hareka.wait.WaitType;
public class NoticeItem implements Item {
private final Name name;
public NoticeItem() {
name = new Name("Notice");
name.put("ja", "掲示板");
}
@Override
public ItemType getType() {
return ItemType.NOTICE;
}
@Override
public Name getName() {
return name;
}
@Override
public String getShape() {
return "Notice";
}
@Override
public boolean isExclusive() {
return true;
}
@Override
public boolean isStackable() {
return false;
}
@Override
public boolean isConsumable() {
return false;
}
@Override
public int getWeight() {
return 8192;
}
@Override
public int getReach() {
return 1;
}
@Override
public WaitType getWaitType() {
return WaitType.ATTACK;
}
@Override
public int getWait(final CharacterEntity entity, final TileType tileType) {
return entity.getStat().getAttackWait(tileType);
}
@Override
public void use(final CharacterEntity characterEntity, final ItemEntity itemEntity, final FieldEntity target) {
// TODO item function
characterEntity.sendMessage("not implemented");
}
}
| agpl-3.0 |
WenbinHou/PKUAutoGateway.Android | Reference/IPGWAndroid/com/google/gson/LongSerializationPolicy.java | 392 | package com.google.gson;
public enum LongSerializationPolicy {
DEFAULT {
public final JsonElement serialize(Long l) {
return new JsonPrimitive((Number) l);
}
},
STRING {
public final JsonElement serialize(Long l) {
return new JsonPrimitive(String.valueOf(l));
}
};
public abstract JsonElement serialize(Long l);
}
| agpl-3.0 |
sozialemedienprojekt/ces-game | src/main/java/de/hub/cses/ces/jsf/bean/game/play/ProductionPanel.java | 3632 | package de.hub.cses.ces.jsf.bean.game.play;
/*
* #%L
* CES-Game
* %%
* Copyright (C) 2015 Humboldt-Universität zu Berlin,
* Department of Computer Science,
* Research Group "Computer Science Education / Computer Science and Society"
* Sebastian Gross <sebastian.gross@hu-berlin.de>
* Sven Strickroth <sven.strickroth@hu-berlin.de>
* %%
* 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 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/>.
* #L%
*/
import de.hub.cses.ces.entity.production.Production;
import de.hub.cses.ces.entity.production.ProductionPlan;
import de.hub.cses.ces.jsf.bean.game.PlayBean;
import de.hub.cses.ces.jsf.config.GamePlayComponent;
import de.hub.cses.ces.service.persistence.production.ProductionFacade;
import de.hub.cses.ces.service.persistence.production.ProductionPlanFacade;
import de.hub.cses.ces.util.ComponentUpdateUtil;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
/**
*
* @author Sebastian Gross <sebastian.gross@hu-berlin.de>
*/
@Named("ProductionPanel")
@ViewScoped
public class ProductionPanel implements Serializable {
@Inject
@SuppressWarnings("NonConstantLogger")
private transient Logger logger;
@Inject
private PlayBean gamePlay;
@Inject
private ComponentUpdateUtil componentUpdateUtil;
@EJB
private ProductionFacade productionFacade;
@EJB
private ProductionPlanFacade productionPlanFacade;
/**
*
*/
@PostConstruct
public void init() {
}
/**
*
* @return
*/
public Production getProduction() {
return gamePlay.getCooperator().getCompany().getProduction();
}
/**
*
* @param event
* @throws Exception
*/
public void edit(org.primefaces.event.RowEditEvent event) throws Exception {
ProductionPlan productionPlan = (ProductionPlan) event.getObject();
try {
logger.log(Level.INFO, "edit production plan {0}", (productionPlan != null) ? productionPlan.getId() : null);
logger.log(Level.INFO, "workforce {0}", (productionPlan != null) ? productionPlan.getWorkforce() : null);
productionPlanFacade.edit(productionPlan);
} catch (Exception ex) {
Exception ne = (Exception) ex.getCause();
if ("org.eclipse.persistence.exceptions.OptimisticLockException".equals(ne.getClass().getName())
|| "javax.persistence.OptimisticLockException".equals(ne.getClass().getName())) {
throw new javax.persistence.OptimisticLockException("fehler...");
}
} finally {
componentUpdateUtil.companyUpdate(gamePlay.getCooperator().getCompany().getId(), GamePlayComponent.PRODUCTION);
}
}
/**
*
* @param event
*/
public void cancel(org.primefaces.event.RowEditEvent event) {
//gamePlay.updateData();
}
}
| agpl-3.0 |
CecileBONIN/Silverpeas-Components | scheduleevent/scheduleevent-war/src/main/java/com/silverpeas/scheduleevent/servlets/handlers/ScheduleEventAddOptionsNextRequestHandler.java | 1773 | /**
* 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.silverpeas.scheduleevent.servlets.handlers;
import javax.servlet.http.HttpServletRequest;
import com.silverpeas.scheduleevent.control.ScheduleEventSessionController;
public class ScheduleEventAddOptionsNextRequestHandler implements ScheduleEventRequestHandler {
@Override
public String getDestination(String function, ScheduleEventSessionController scheduleeventSC,
HttpServletRequest request) throws Exception {
// keep session object identical -> nothing to do
request.setAttribute(CURRENT_SCHEDULE_EVENT, scheduleeventSC.getCurrentScheduleEvent());
return "form/optionshour.jsp";
}
}
| agpl-3.0 |
vimsvarcode/elmis | modules/report/src/main/java/org/openlmis/report/model/params/StockImbalanceReportParam.java | 2440 | /*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla 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 Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
package org.openlmis.report.model.params;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.openlmis.report.model.ReportData;
import org.openlmis.report.model.ReportParameter;
@Data
@EqualsAndHashCode(callSuper=false)
@NoArgsConstructor
@AllArgsConstructor
public class StockImbalanceReportParam
extends BaseParam implements ReportParameter {
private int facilityTypeId;
private String facilityType;
// private int productId;
private String productId;
private String product;
// private int productCategoryId;
private String productCategoryId;
private String productCategory;
private String facility;
private int programId;
private String program;
private int scheduleId;
private String schedule;
private int periodId;
private Long zoneId;
private String period;
private Integer year;
@Override
public String toString() {
StringBuilder filtersValue = new StringBuilder("");
filtersValue.append("Period : ").append(this.period).append("\n").
append("Schedule : ").append(this.schedule).append("\n").
append("Program : ").append(this.program).append("\n").
append("Product Category : ").append(this.productCategory).append("\n").
append("Product : ").append(this.product).append("\n").
append("Facility Types : ").append(this.getFacilityType()).append("\n");
return filtersValue.toString();
}
}
| agpl-3.0 |
dmontag/graphdb-traversal-context | lucene-index/src/test/java/org/neo4j/index/impl/lucene/TestIndexDeletion.java | 8144 | /**
* 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.index.impl.lucene;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.index.Neo4jTestCase;
import org.neo4j.kernel.AbstractGraphDatabase;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.neo4j.index.Neo4jTestCase.assertContains;
import static org.neo4j.index.impl.lucene.Contains.contains;
import static org.neo4j.index.impl.lucene.HasThrownException.hasThrownException;
public class TestIndexDeletion
{
private static final String INDEX_NAME = "index";
private static GraphDatabaseService graphDb;
private Index<Node> index;
private Transaction tx;
private String key;
private Node node;
private String value;
private List<WorkThread> workers;
@BeforeClass
public static void setUpStuff()
{
String storeDir = "target/var/freshindex";
Neo4jTestCase.deleteFileOrDirectory( new File( storeDir ) );
graphDb = new EmbeddedGraphDatabase( storeDir, MapUtil.stringMap( "index", "lucene" ) );
}
@AfterClass
public static void tearDownStuff()
{
graphDb.shutdown();
}
@After
public void commitTx()
{
finishTx( true );
for ( WorkThread worker : workers )
{
worker.rollback();
worker.die();
}
}
public void rollbackTx()
{
finishTx( false );
}
public void finishTx( boolean success )
{
if ( tx != null )
{
if ( success )
{
tx.success();
}
tx.finish();
tx = null;
}
}
@Before
public void createInitialData()
{
beginTx();
index = graphDb.index().forNodes( INDEX_NAME );
index.delete();
restartTx();
index = graphDb.index().forNodes( INDEX_NAME );
key = "key";
value = "my own value";
node = graphDb.createNode();
index.add( node, key, value );
workers = new ArrayList<WorkThread>();
}
public void beginTx()
{
if ( tx == null )
{
tx = graphDb.beginTx();
}
}
void restartTx()
{
finishTx( true );
beginTx();
}
@Test
public void shouldBeAbleToDeleteAndRecreateIndex()
{
restartTx();
assertContains( index.query( key, "own" ) );
index.delete();
restartTx();
Index<Node> recreatedIndex = graphDb.index().forNodes( INDEX_NAME, LuceneIndexProvider.FULLTEXT_CONFIG );
assertNull( recreatedIndex.get( key, value ).getSingle() );
recreatedIndex.add( node, key, value );
restartTx();
assertContains( recreatedIndex.query( key, "own" ), node );
recreatedIndex.delete();
}
@Test
public void shouldNotBeDeletedWhenDeletionRolledBack()
{
restartTx();
index.delete();
rollbackTx();
index.get( key, value );
}
@Test( expected = IllegalStateException.class )
public void shouldThrowIllegalStateForActionsAfterDeletedOnIndex()
{
restartTx();
index.delete();
restartTx();
index.query( key, "own" );
}
@Test( expected = IllegalStateException.class )
public void shouldThrowIllegalStateForActionsAfterDeletedOnIndex2()
{
restartTx();
index.delete();
restartTx();
index.add( node, key, value );
}
@Test( expected = IllegalStateException.class )
public void shouldThrowIllegalStateForActionsAfterDeletedOnIndex3()
{
restartTx();
index.delete();
index.query( key, "own" );
}
@Test( expected = IllegalStateException.class )
public void shouldThrowIllegalStateForActionsAfterDeletedOnIndex4()
{
restartTx();
index.delete();
Index<Node> newIndex = graphDb.index().forNodes( INDEX_NAME );
newIndex.query( key, "own" );
}
@Test
public void deleteInOneTxShouldNotAffectTheOther() throws InterruptedException
{
index.delete();
WorkThread firstTx = createWorker();
firstTx.createNodeAndIndexBy( key, "another value" );
firstTx.commit();
}
@Test
public void deleteAndCommitShouldBePublishedToOtherTransaction2() throws InterruptedException
{
WorkThread firstTx = createWorker();
WorkThread secondTx = createWorker();
firstTx.beginTransaction();
secondTx.beginTransaction();
firstTx.createNodeAndIndexBy( key, "some value" );
secondTx.createNodeAndIndexBy( key, "some other value" );
firstTx.deleteIndex();
firstTx.commit();
secondTx.queryIndex( key, "some other value" );
assertThat( secondTx, hasThrownException() );
secondTx.rollback();
// Since $Before will start a tx, add a value and keep tx open and workers will
// delete the index so this test will fail in @After if we don't rollback this tx
rollbackTx();
}
@Test
public void indexDeletesShouldNotByVisibleUntilCommit()
{
commitTx();
WorkThread firstTx = createWorker();
WorkThread secondTx = createWorker();
firstTx.beginTransaction();
firstTx.removeFromIndex( key, value );
assertThat( secondTx.queryIndex( key, value ), contains( node ) );
firstTx.rollback();
}
@Test
public void indexDeleteShouldDeleteDirectory()
{
String otherIndexName = "other-index";
File pathToLuceneIndex = new File( ((AbstractGraphDatabase)graphDb).getStoreDir() + "/index/lucene/node/" + INDEX_NAME );
File pathToOtherLuceneIndex = new File( ((AbstractGraphDatabase)graphDb).getStoreDir() + "/index/lucene/node/" + otherIndexName );
Index<Node> otherIndex = graphDb.index().forNodes( otherIndexName );
Node node = graphDb.createNode();
otherIndex.add( node, "someKey", "someValue" );
assertFalse( pathToLuceneIndex.exists() );
assertFalse( pathToOtherLuceneIndex.exists() );
restartTx();
// Here "index" and "other-index" indexes should exist
assertTrue( pathToLuceneIndex.exists() );
assertTrue( pathToOtherLuceneIndex.exists() );
index.delete();
assertTrue( pathToLuceneIndex.exists() );
assertTrue( pathToOtherLuceneIndex.exists() );
restartTx();
// Here only "other-index" should exist
assertFalse( pathToLuceneIndex.exists() );
assertTrue( pathToOtherLuceneIndex.exists() );
}
private WorkThread createWorker()
{
WorkThread workThread = new WorkThread( index, graphDb );
workers.add( workThread );
return workThread;
}
}
| agpl-3.0 |
cacheonix/cacheonix-core | annotations/core/src/org/cacheonix/impl/transformer/ETransformationState.java | 1806 | /**
*
*/
/*
* Cacheonix Systems licenses this file to You under the LGPL 2.1
* (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.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm
*
* 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.cacheonix.impl.transformer;
/**
* Enum used for maintaing the state of the reader while reading the bytes in the class file
*/
public enum ETransformationState {
// States ENUMs
INITIAL_STATE {
/*
* (non-Javadoc)
*
* @see java.lang.Objectr#toString()
*/
public String toString() {
return "INITIAL_STATE";
}
},
READING_CONFIG_ANNOTATION // Found Configuration Annotation - Class level
{
/*
* (non-Javadoc)
*
* @see java.lang.Objectr#toString()
*/
public String toString() {
return "READING_CONFIG_ANNOTATION";
}
},
READING_METHOD_ANNOTATION // Found Method Annotation
{
/*
* (non-Javadoc)
*
* @see java.lang.Objectr#toString()
*/
public String toString() {
return "READING_METHOD_ANNOTATION";
}
};
/*
* (non-Javadoc)
*
* @see java.lang.Objectr#toString()
*/
public String toString() {
return "UNKNOWN";
}
}
| lgpl-2.1 |