repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
usersource/anno | usersource-profile/usersource-profile-war/src/main/java/io/usersource/profile/endpoint/AppIconServlet.java | 1997 | package io.usersource.profile.endpoint;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
public class AppIconServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 4377969290784958121L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
String appName = req.getParameter("appName");
if (appName == null || appName.isEmpty()) {
resp.setStatus(400);
resp.getOutputStream().print("appName parameter is missing.");
return;
}
String appVersion = req.getParameter("appVersion");
Query query = new Query("AppInfo");
Filter appNameFilter = new FilterPredicate("appName",
FilterOperator.EQUAL, appName);
if (appVersion == null || appVersion.isEmpty()) {
query = query.setFilter(appNameFilter);
} else {
Filter appVersionFilter = new FilterPredicate("appVersion",
FilterOperator.EQUAL, appVersion);
Filter compositeFilter = CompositeFilterOperator.and(appNameFilter,
appVersionFilter);
query = query.setFilter(compositeFilter);
}
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Entity appInfo = datastore.prepare(query).asSingleEntity();
byte[] data = (byte[]) appInfo.getProperty("appIcon");
resp.getOutputStream().write(data);
}
}
| mpl-2.0 |
Skelril/Skree | src/main/java/com/skelril/nitro/droptable/resolver/SimpleDropResolver.java | 975 | /*
* 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.skelril.nitro.droptable.resolver;
import org.spongepowered.api.item.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
public class SimpleDropResolver implements DropResolver {
private Collection<ItemStack> queue = getBaseCollection();
private Collection<ItemStack> itemStacks;
public SimpleDropResolver(Collection<ItemStack> itemStacks) {
this.itemStacks = itemStacks;
}
public Collection<ItemStack> getBaseCollection() {
return new ArrayList<>();
}
@Override
public void enqueue(double modifier) {
queue.addAll(itemStacks);
}
@Override
public Collection<ItemStack> flush() {
Collection<ItemStack> itemStacks = queue;
queue = getBaseCollection();
return itemStacks;
}
}
| mpl-2.0 |
WebDataConsulting/billing | src/java/com/sapienter/jbilling/server/util/csv/Exportable.java | 1444 | /*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling 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.
jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>.
This source was modified by Web Data Technologies LLP (www.webdatatechnologies.in) since 15 Nov 2015.
You may download the latest source from webdataconsulting.github.io.
*/
package com.sapienter.jbilling.server.util.csv;
import java.util.ArrayList;
import java.util.List;
/**
* Marks a class as being exportable in a simple format (such as CSV).
*
* @author Brian Cowdery
* @since 03/03/11
*/
public interface Exportable {
public List<String> metaFieldsNames = new ArrayList<>();
public List<String> customerMetaFieldsNames = new ArrayList<>();
public String[] getFieldNames();
public Object[][] getFieldValues();
}
| agpl-3.0 |
bitblit11/yamcs | yamcs-core/src/main/java/org/yamcs/yarch/rocksdb/StringColumnFamilySerializer.java | 562 | package org.yamcs.yarch.rocksdb;
import java.nio.charset.StandardCharsets;
public class StringColumnFamilySerializer implements ColumnFamilySerializer {
@Override
public byte[] objectToByteArray(Object value) {
if(value instanceof String) {
return ((String)value).getBytes(StandardCharsets.US_ASCII);
}
throw new RuntimeException("Cannot encode objects of type "+value.getClass());
}
@Override
public Object byteArrayToObject(byte[] b) {
return new String(b, StandardCharsets.US_ASCII);
}
} | agpl-3.0 |
jwillia/kc-old1 | coeus-impl/src/main/java/org/kuali/kra/award/web/struts/action/AwardTimeAndMoneyAction.java | 3303 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kra.award.web.struts.action;
/**
*
* This class represents the Struts Action for Time & Money page(AwardTimeAndMoney.jsp)
*/
public class AwardTimeAndMoneyAction extends AwardAction {
// private AwardDirectFandADistributionBean awardDirectFandADistributionBean;
//
// public AwardTimeAndMoneyAction(){
// awardDirectFandADistributionBean = new AwardDirectFandADistributionBean();
// }
//
// /**
// *
// * This method adds a new AwardDirectFandADistribution to the list.
// * @param mapping
// * @param form
// * @param request
// * @param response
// * @return
// * @throws Exception
// */
// public ActionForward addAwardDirectFandADistribution(ActionMapping mapping, ActionForm form, HttpServletRequest request,
// HttpServletResponse response) throws Exception {
// awardDirectFandADistributionBean.addAwardDirectFandADistribution(((AwardForm) form).getAwardDirectFandADistributionBean());
// return mapping.findForward(Constants.MAPPING_BASIC);
// }
//
// /**
// *
// * This method removes an AwardDirectFandADistribution from the list.
// * @param mapping
// * @param form
// * @param request
// * @param response
// * @return
// * @throws Exception
// */
// public ActionForward deleteAwardDirectFandADistribution(ActionMapping mapping, ActionForm form, HttpServletRequest request,
// HttpServletResponse response) throws Exception {
// AwardForm awardForm = (AwardForm) form;
// awardForm.getAwardDocument().getAward().getAwardDirectFandADistributions().remove(getLineToDelete(request));
// awardDirectFandADistributionBean.updateBudgetPeriodsAfterDelete(awardForm.getAwardDocument().getAward().getAwardDirectFandADistributions());
// return mapping.findForward(Constants.MAPPING_BASIC);
// }
//
// /**
// * This method is used to recalculate the Total amounts in the Direct F and A Distribution panel.
// *
// * @param mapping
// * @param form
// * @param request
// * @param response
// * @return mapping forward
// * @throws Exception
// */
// public ActionForward recalculateDirectFandADistributionTotals(ActionMapping mapping, ActionForm form, HttpServletRequest request,
// HttpServletResponse response) throws Exception {
//
// return mapping.findForward(Constants.MAPPING_BASIC);
// }
}
| agpl-3.0 |
Xenoage/Zong | layout/src/com/xenoage/zong/musiclayout/notator/chord/stem/beam/BeamedStemDirector.java | 1584 | package com.xenoage.zong.musiclayout.notator.chord.stem.beam;
import static com.xenoage.utils.collections.ArrayUtils.setValues;
import static com.xenoage.zong.core.music.beam.Beam.VerticalSpan.SingleStaff;
import static com.xenoage.zong.musiclayout.notator.chord.stem.beam.range.OneMeasureOneStaff.oneMeasureOneStaff;
import static com.xenoage.zong.musiclayout.notator.chord.stem.beam.range.OneMeasureTwoStaves.oneMeasureTwoStaves;
import com.xenoage.zong.core.Score;
import com.xenoage.zong.core.music.beam.Beam;
import com.xenoage.zong.core.music.beam.Beam.VerticalSpan;
import com.xenoage.zong.core.music.chord.StemDirection;
import com.xenoage.zong.musiclayout.notator.chord.stem.beam.range.Strategy;
/**
* Computes the {@link StemDirection} of beamed chords.
*
* @author Andreas Wenger
*/
public class BeamedStemDirector {
public static final BeamedStemDirector beamedStemDirector = new BeamedStemDirector();
public StemDirection[] compute(Beam beam, Score score) {
//choose appropriate strategy
Strategy strategy;
if (beam.getVerticalSpan() == SingleStaff)
strategy = oneMeasureOneStaff;
else if (beam.getVerticalSpan() == VerticalSpan.CrossStaff)
strategy = oneMeasureTwoStaves;
else
//no strategy for more than two or non-adjacent staves
return fallback(beam.size());
return strategy.compute(beam, score);
}
/**
* Fallback for unsupported beams: All stems up.
*/
private StemDirection[] fallback(int stemsCount) {
StemDirection[] ret = new StemDirection[stemsCount];
setValues(ret, StemDirection.Up);
return ret;
}
}
| agpl-3.0 |
Smartupz/tigase-muc | src/main/java/tigase/muc/Ghostbuster.java | 8559 | /*
* Tigase Jabber/XMPP Multi-User Chat Component
* Copyright (C) 2008 "Bartosz M. Małkowski" <bartosz.malkowski@tigase.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.
*
* 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. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package tigase.muc;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.muc.modules.PresenceModule;
import tigase.server.Packet;
import tigase.server.ReceiverTimeoutHandler;
import tigase.util.TigaseStringprepException;
import tigase.xml.Element;
import tigase.xmpp.JID;
/**
* @author bmalkow
*
*/
public class Ghostbuster {
private static class JIDDomain {
private String cacheKey;
private final String domain;
private final JID source;
/**
*
*/
public JIDDomain(JID source, String domain) {
this.source = source;
this.domain = domain;
cacheKey = (this.source == null ? "-" : this.source.toString()) + ":"
+ (this.domain == null ? "-" : this.domain.toString());
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof JIDDomain))
return false;
return cacheKey.equals(((JIDDomain) obj).cacheKey);
}
@Override
public int hashCode() {
return cacheKey.hashCode();
}
@Override
public String toString() {
return cacheKey;
}
}
private static final Set<String> intReasons = new HashSet<String>() {
private static final long serialVersionUID = 1L;
{
add("gone");
add("item-not-found");
add("recipient-unavailable");
add("redirect");
add("remote-server-not-found");
add("remote-server-timeout");
}
};
public static final Set<String> R = Collections.unmodifiableSet(intReasons);
private long idCounter;
private final Map<JIDDomain, Long> lastActivity = new ConcurrentHashMap<JIDDomain, Long>();
protected Logger log = Logger.getLogger(this.getClass().getName());
private final MUCComponent mucComponent;
private final ReceiverTimeoutHandler pingHandler;
private PresenceModule presenceModule;
/**
* @param mucComponent
* @param config2
* @param mucRepository2
* @param writer
*/
public Ghostbuster(MUCComponent mucComponent) {
this.mucComponent = mucComponent;
this.pingHandler = new ReceiverTimeoutHandler() {
@Override
public void responseReceived(Packet data, Packet response) {
try {
onPingReceived(response);
} catch (Exception e) {
if (log.isLoggable(Level.WARNING))
log.log(Level.WARNING, "Problem on handling ping response", e);
}
}
@Override
public void timeOutExpired(Packet data) {
try {
if (log.isLoggable(Level.FINEST))
log.finest("Received ping timeout for ping " + data.getElement().getAttribute("id"));
onPingTimeout(data.getStanzaFrom().getDomain(), data.getStanzaTo());
} catch (Exception e) {
if (log.isLoggable(Level.WARNING))
log.log(Level.WARNING, "Problem on handling ping timeout", e);
}
}
};
}
/**
* @param packet
*/
private String checkError(final Packet packet) {
final String type = packet.getElement().getAttribute("type");
if (type == null || !type.equals("error"))
return null;
final Element errorElement = packet.getElement().getChild("error");
if (errorElement == null)
return null;
for (Element reason : errorElement.getChildren()) {
if (reason.getXMLNS() == null || !reason.getXMLNS().equals("urn:ietf:params:xml:ns:xmpp-stanzas"))
continue;
if (Ghostbuster.R.contains(reason.getName())) {
return reason.getName();
}
}
return null;
}
public PresenceModule getPresenceModule() {
return presenceModule;
}
/**
* @param stanzaFrom
* @throws TigaseStringprepException
*/
protected void onPingReceived(final Packet response) throws TigaseStringprepException {
final JIDDomain k = new JIDDomain(response.getStanzaFrom(), response.getStanzaTo().getDomain());
if (lastActivity.containsKey(k)) {
final String errorCause = checkError(response);
if (errorCause != null) {
if (log.isLoggable(Level.FINEST))
log.finest("Received error response for ping " + response.getElement().getAttribute("id") + "("
+ checkError(response) + ") of" + k);
processError(k);
} else {
if (log.isLoggable(Level.FINEST))
log.finest("Update last activity for " + k);
lastActivity.put(k, System.currentTimeMillis());
}
}
}
/**
* @param domain
* @param stanzaTo
*/
protected void onPingTimeout(String domain, final JID jid) {
try {
processError(new JIDDomain(jid, domain));
} catch (TigaseStringprepException e) {
if (log.isLoggable(Level.WARNING))
log.log(Level.WARNING, "Invalid jid?", e);
}
}
/**
* @throws TigaseStringprepException
*
*/
public void ping() throws TigaseStringprepException {
if (log.isLoggable(Level.FINE))
log.log(Level.FINE, "Pinging 1000 known jids");
int c = 0;
final long now = System.currentTimeMillis();
final long border = now - 1000 * 60 * 60;
Iterator<Entry<JIDDomain, Long>> it = lastActivity.entrySet().iterator();
while (it.hasNext() && c < 1000) {
Entry<JIDDomain, Long> entry = it.next();
if (entry.getValue() < border) {
++c;
ping(entry.getKey().domain, entry.getKey().source);
}
}
}
private void ping(String fromDomain, JID jid) throws TigaseStringprepException {
final String id = "png-" + (++idCounter);
if (log.isLoggable(Level.FINER))
log.log(Level.FINER, "Pinging " + jid + ". id=" + id);
Element ping = new Element("iq", new String[] { "type", "id", "from", "to" }, new String[] { "get", id, fromDomain,
jid.toString() });
ping.addChild(new Element("ping", new String[] { "xmlns" }, new String[] { "urn:xmpp:ping" }));
Packet packet = Packet.packetInstance(ping);
mucComponent.addOutPacket(packet, pingHandler, 1, TimeUnit.MINUTES);
}
/**
* @param packet
* @throws TigaseStringprepException
*/
private void processError(JIDDomain k) throws TigaseStringprepException {
if (presenceModule == null || mucComponent.getMucRepository() == null)
return;
if (log.isLoggable(Level.FINEST))
log.finest("Forced removal last activity of " + k);
this.lastActivity.remove(k);
for (Room r : mucComponent.getMucRepository().getActiveRooms().values()) {
if (r.getRoomJID().getDomain().equals(k.domain) && r.isOccupantInRoom(k.source)) {
presenceModule.doQuit(r, k.source);
}
}
}
public void setPresenceModule(PresenceModule presenceModule) {
this.presenceModule = presenceModule;
}
public void update(Packet packet) throws TigaseStringprepException {
if (packet.getStanzaFrom() == null || packet.getStanzaFrom().getResource() == null)
return;
final JIDDomain k = new JIDDomain(packet.getStanzaFrom(), packet.getStanzaTo().getDomain());
final String type = packet.getElement().getAttribute("type");
if (checkError(packet) != null) {
if (log.isLoggable(Level.FINEST))
log.finest("Received presence error: " + packet.getElement().toString());
processError(k);
} else if ("presence".equals(packet.getElemName()) && type != null && type.equals("unavailable")) {
if (log.isLoggable(Level.FINEST))
log.finest("Removal last activity of " + k);
this.lastActivity.remove(k);
} else if (!lastActivity.containsKey(k) && "presence".equals(packet.getElemName())
&& (type == null || !type.equals("error"))) {
if (log.isLoggable(Level.FINEST))
log.finest("Creation last activity entry for " + k);
lastActivity.put(k, System.currentTimeMillis());
return;
}
if (lastActivity.containsKey(k)) {
if (log.isLoggable(Level.FINEST))
log.finest("Update last activity for " + k);
lastActivity.put(k, System.currentTimeMillis());
}
}
}
| agpl-3.0 |
MusesProject/MusesServer | src/main/java/eu/musesproject/server/connectionmanager/ComMainServlet.java | 10807 | package eu.musesproject.server.connectionmanager;
/*
* #%L
* MUSES Server
* %%
* Copyright (C) 2013 - 2015 Sweden Connectivity
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Queue;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import eu.musesproject.server.contextdatareceiver.ConnectionCallbacksImpl;
/**
* Class ComMainServlet
*
* @author Yasir Ali
* @version Jan 27, 2014
*/
public class ComMainServlet extends HttpServlet {
// a servlet has to be thread safe so no instance variables are allowed (this is not optional, it is a rule)
// read this for more info http://www.javaworld.com/article/2072798/java-web-development/write-thread-safe-servlets.html
// there is no issue with those that are final int, final long or final string because they are read-only
// the rest needs to fulfill one of these options: become local variables or be thread safe or be stateless
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(ComMainServlet.class.getName());
private Helper helper; // became stateless
//private SessionHandler sessionHandler; // tomcat handles sessions for us
private ConnectionManager connectionManager; // removing this requires going from pull to push
//private String dataAttachedInCurrentReuqest; // became local variable
//private String dataToSendBackInResponse=""; // became local variable
private static final String CONNECTION_TYPE = "connection-type";
private static final String DATA = "data";
private static final int INTERVAL_TO_WAIT = 5;
private static final long SLEEP_INTERVAL = 1000;
private static final String MUSES_TAG = "MUSES_TAG";
//private static String connectionType = "connect"; // became local variable
/**
*
* @param sessionHandler
* @param helper
* @param communicationManager
*/
public ComMainServlet(SessionHandler sessionHandler, Helper helper, ConnectionManager communicationManager){
//this.sessionHandler=sessionHandler;
this.helper=helper;
this.connectionManager=communicationManager;
}
public ComMainServlet() {
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.log(Level.INFO, MUSES_TAG + " init");
helper = new Helper();
connectionManager = ConnectionManager.getInstance();
//sessionHandler = SessionHandler.getInstance(getServletContext());
ConnectionCallbacksImpl.getInstance(); // register callback
// the connection manager should be moved to ApplicationScope like this
//ConnectionManager connectionManager = ConnectionManager.getInstance();
//config.getServletContext().setAttribute("ConnectionManager.instance", connectionManager);
// the retrieval in doPost() would look like this. bear in mind that objects in application
// scope like ConnectionManager will be accessed by many threads so they must be thread-safe
//connectionManager = (ConnectionManager) this.getServletContext().getAttribute("ConnectionManager.instance");
}
/**
* Handle POST http/https requests
* @param HttpServletRequest request
* @param com.swedenconnectivity.comserverHttpServletResponse response
* @throws ServletException, IOException
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// by calling getSession() we send a signal to tomcat that we want a session created if there
// isn't any already. bear in mind that tomcat will put the JSESSIONID as a cookie in the
// response for us so we don't have to do it ourselves. btw every jsp file already contains this
// method call.
HttpSession session = request.getSession();
String dataAttachedInCurrentReuqest;
String dataToSendBackInResponse="";
String connectionType = "connect";
// create cookie if not in the request
//Cookie cookie = helper.extractCookie(request);
//String currentJSessionID = cookie.getValue();
String currentJSessionID = session.getId();
// Retrieve data in the request
if (request.getMethod().equalsIgnoreCase("POST")) {
// Retrieve connection-type from request header
connectionType = request.getHeader(CONNECTION_TYPE);
dataAttachedInCurrentReuqest = Helper.getRequestData(request);
}else {
// Retrieve connection-type from request parameter
connectionType = DATA;
dataAttachedInCurrentReuqest = request.getParameter(DATA);
}
// if "connect" request
if (connectionType!=null && connectionType.equalsIgnoreCase(RequestType.CONNECT)) {
logger.log(Level.INFO, MUSES_TAG + " Request type:"+connectionType+" with *ID*: "+currentJSessionID+ " with **dataInRequest**: "+dataAttachedInCurrentReuqest);
}
// if "send-data" request
if (connectionType!=null && connectionType.equalsIgnoreCase(RequestType.DATA)) {
// Callback the FL to receive data from the client and get the response data back into string
dataToSendBackInResponse="";
if (dataAttachedInCurrentReuqest != null){
dataToSendBackInResponse = ConnectionManager.toReceive(currentJSessionID, dataAttachedInCurrentReuqest); // FIXME needs to be tested properly
if (dataToSendBackInResponse == null) {
dataToSendBackInResponse = "";
}
}
if (dataToSendBackInResponse.equals("")) {
dataToSendBackInResponse = waitForDataIfAvailable(INTERVAL_TO_WAIT, currentJSessionID);
}
response.setContentType("application/json");
response.setHeader("Cache-Control", "nocache");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
writer.write(dataToSendBackInResponse);
//response.addHeader(DATA,dataToSendBackInResponse); // Now data is added in the body instead
logger.log(Level.INFO, MUSES_TAG + " Data avaialble Request type:"+connectionType+" with *ID*: "+currentJSessionID+ " with **dataInResponse**: "+dataToSendBackInResponse);
}
// if "poll" request
if (connectionType!= null && connectionType.equalsIgnoreCase(RequestType.POLL)) {
for (DataHandler dataHandler : connectionManager.getDataHandlerQueue()){ // FIXME concurrent thread
if (dataHandler.getSessionId().equalsIgnoreCase(currentJSessionID)){
dataToSendBackInResponse = dataHandler.getData();
response.setHeader("Content-Type", "text/plain");
PrintWriter writer = response.getWriter();
writer.write(dataToSendBackInResponse);
//response.addHeader(DATA,dataToSendBackInResponse); // Now data is added in the body instead
connectionManager.removeDataHandler(dataHandler);
Queue<DataHandler> dQueue = connectionManager.getDataHandlerQueue();
if (dQueue.size() > 1) {
response.addHeader("more-packets", "YES");
}else {
response.addHeader("more-packets", "NO");
}
logger.log(Level.INFO, "Data avaialble Request type:"+connectionType+" with *ID*: "+currentJSessionID+ " with **dataInResponse**: "+dataToSendBackInResponse);
break; // FIXME temporary as multiple same session ids are in the list right now
}
}
}
// if "ack" request
if (connectionType!=null && connectionType.equalsIgnoreCase(RequestType.ACK)) {
logger.log(Level.INFO, "Request type:"+connectionType+" with *ID*: "+currentJSessionID);
// Clean up the data handler object from the list
connectionManager.removeDataHandler(connectionManager.getDataHandlerObject(currentJSessionID));
ConnectionManager.toSessionCb(currentJSessionID, Statuses.DATA_SENT_SUCCESFULLY);
}
// if disconnect request
// invalidate session from Servlet
// remove it from the session id list
// Callback the Functional layer about the disconnect
if (connectionType!= null && connectionType.equalsIgnoreCase(RequestType.DISCONNECT)) {
logger.log(Level.INFO, "Request type:"+connectionType+" with *ID*: "+currentJSessionID);
Helper.disconnect(request);
//sessionHandler.removeCookieToList(cookie);
ConnectionManager.toSessionCb(currentJSessionID, Statuses.DISCONNECTED);
}
// Add session id to the List
// if (currentJSessionID != null && !connectionType.equalsIgnoreCase(RequestType.DISCONNECT) ) {
// //sessionHandler.addCookieToList(cookie);
// }
// the cookie should only be set by tomcat once when the session has been created.
// after that the client will include the cookie inside every request until the cookie
// expires. btw this is the correct mime type for json (Source: RFC 4627)
// should already be in response because we called the getSession above
//response.addCookie(cookie);
response.setContentType("application/json");
}
// we don't have any instance variable so we can not have a getter either. this method is called
// by some unit test assert methods. those methods should instead extract the payload from httpsresponse
//public String getResponseData(){
// return dataToSendBackInResponse;
//}
public String waitForDataIfAvailable(int timeout, String currentJSessionID){
int i=1;
while(i<=timeout){
Queue<DataHandler> dQueue = connectionManager.getDataHandlerQueue();
if (dQueue.size()>=1) {
for (DataHandler dataHandler : connectionManager.getDataHandlerQueue()){ // FIXME concurrent thread
if (dataHandler.getSessionId().equalsIgnoreCase(currentJSessionID)){
connectionManager.removeDataHandler(dataHandler);
return dataHandler.getData();
}
}
}
sleep(SLEEP_INTERVAL);
i++;
}
return "";
}
private void sleep(long millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
logger.log(Level.INFO, e);
}
}
/**
* Handle GET http/https requests // Muses will not use this method
* @param HttpServletRequest request
* @param HttpServletResponse response
* @throws ServletException, IOException
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/operator/validation/clustering/exampledistribution/SumOfSquares.java | 1465 | /**
* 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.operator.validation.clustering.exampledistribution;
/**
* Calculates an item distribution measure by summing up the squares of the fraction of items in
* each cluster. The result is inverted, thus the higher the value, the better the items are
* distributed.
*
* @author Michael Wurst
*
*/
public class SumOfSquares implements ExampleDistributionMeasure {
@Override
public double evaluate(int[] x, int n) {
double result = 0;
for (int i = 0; i < x.length; i++) {
result = result + (((double) x[i]) / n) * (((double) x[i]) / n);
}
return result;
}
}
| agpl-3.0 |
quikkian-ua-devops/will-financials | kfs-core/src/main/java/org/kuali/kfs/fp/document/validation/impl/IndirectCostAdjustmentDocumentRuleConstants.java | 1522 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.fp.document.validation.impl;
/**
* Holds constants for <code>{@link org.kuali.kfs.fp.document.IndirectCostAdjustmentDocument}</code> business rules.
*/
public interface IndirectCostAdjustmentDocumentRuleConstants {
public static final String INDIRECT_COST_ADJUSTMENT_DOCUMENT_SECURITY_GROUPING = "Kuali.FinancialTransactionProcessing.IndirectCostAdjustmentDocument";
public static final String RESTRICTED_SUB_TYPE_GROUP_CODES = "OBJECT_SUB_TYPES";
public static final String RESTRICTED_OBJECT_TYPE_CODES = "OBJECT_TYPES";
public static final String GRANT_OBJECT_CODE = "GRANT_OBJECT_CODE";
public static final String RECEIPT_OBJECT_CODE = "RECEIPT_OBJECT_CODE";
}
| agpl-3.0 |
WoutDev/Mega-Walls | Mega Walls Plugin/src/main/java/be/woutdev/megawalls/plugin/handler/game/BasicGameHandler.java | 2578 | package be.woutdev.megawalls.plugin.handler.game;
import be.woutdev.megawalls.api.MWAPI;
import be.woutdev.megawalls.api.enums.GameState;
import be.woutdev.megawalls.api.handler.GameHandler;
import be.woutdev.megawalls.api.model.Game;
import be.woutdev.megawalls.api.model.Map;
import be.woutdev.megawalls.plugin.model.BasicGame;
import be.woutdev.megawalls.plugin.wither.NMSWither;
import be.woutdev.megawalls.plugin.wither.v1_9_R1.Wither191;
import org.bukkit.Bukkit;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Created by Wout on 20/08/2016.
*/
public class BasicGameHandler implements GameHandler
{
private final Set<Game> games;
private NMSWither witherType;
public BasicGameHandler()
{
this.games = new HashSet<Game>();
String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
switch (version)
{
case "v1_9_R1":
witherType = new Wither191(null, Bukkit.getWorlds().get(0).getSpawnLocation());
break;
}
if (witherType == null)
{
MWAPI.getPlugin().getLogger().severe("Failed to initialize custom wither. Disabling plugin...");
Bukkit.getServer().getPluginManager().disablePlugin(MWAPI.getPlugin());
return;
}
witherType.register();
}
@Override
public Game createGame(Map map)
{
Game game = null;
if (map.isConfigured() && map.isActive())
{
game = new BasicGame(map);
games.add(game);
MWAPI.getOfflineGameHandler().insert(game);
}
return game;
}
@Override
public Set<Game> findAll()
{
return games;
}
@Override
public Set<Game> findByState(GameState state)
{
return games.stream().filter(g -> g.getState().equals(state)).collect(Collectors.toSet());
}
@Override
public Set<Game> findActive()
{
return games.stream()
.filter(g -> g.getState().equals(GameState.LOBBY) || g.getState().equals(GameState.PRE_GAME) ||
g.getState().equals(GameState.MAIN_GAME) || g.getState().equals(GameState.END_GAME))
.collect(Collectors.toSet());
}
@Override
public Game findById(int id)
{
return games.stream().filter(g -> g.getId() == id).findAny().orElse(null);
}
public Class getWitherType()
{
return witherType.getClass();
}
}
| agpl-3.0 |
automenta/java_dann | src/syncleus/dann/solve/threedee/Point.java | 2523 | package syncleus.dann.solve.threedee;
//package org.simbrain.world.threedee;
//
//import com.jme.math.Vector3f;
//
//public class Point {
// private final Vector3f internal;
//
// private Point(Vector3f vector3f, boolean clone) {
// if (vector3f == null)
// throw new IllegalArgumentException("Vector cannot be null.");
//
// if (clone) {
// this.internal = (Vector3f) vector3f.clone();
// } else {
// this.internal = vector3f;
// }
// }
//
// public Point(Vector3f vector3f) {
// this(vector3f, true);
// }
//
// public Point(float x, float y, float z) {
// this.internal = new Vector3f(x, y, z);
// }
//
// public float getX() {
// return internal.x;
// }
//
// public float getY() {
// return internal.y;
// }
//
// public float getZ() {
// return internal.z;
// }
//
// public Point add(Vector vector) {
// return new Point(internal.add(vector.toVector3f()), false);
// }
//
// public Point setX(float x) {
// Vector3f vec = (Vector3f) internal.clone();
// vec.x = x;
// return new Point(vec, false);
// }
//
// public Point setY(float y) {
// Vector3f vec = (Vector3f) internal.clone();
// vec.y = y;
// return new Point(vec, false);
// }
//
// public Point setZ(float z) {
// Vector3f vec = (Vector3f) internal.clone();
// vec.z = z;
// return new Point(vec, false);
// }
//
// public float distance(Point other) {
// return internal.distance(other.internal);
// }
//
// public Vector3f toVector3f() {
// return new Vector3f(getX(), getY(), getZ());
// }
//
// public String toString() {
// return "point: (" + internal.getX() + ", " + internal.getY() + ", "
// + internal.getZ() + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result
// + ((internal == null) ? 0 : internal.hashCode());
// return result;
// }
//
// @Override
// public final boolean equals(Object obj) {
// if (this == obj)
// return true;
//
// if (!(obj instanceof Point))
// return false;
//
// final Point other = (Point) obj;
//
// return internal.equals(other.internal);
// }
//}
| agpl-3.0 |
SilverDav/Silverpeas-Core | core-war/src/main/java/org/silverpeas/web/silverstatistics/servlets/SilverStatisticsPeasRequestRouter.java | 35268 | /*
* 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.web.silverstatistics.servlets;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.web.mvc.controller.ComponentContext;
import org.silverpeas.core.web.mvc.controller.MainSessionController;
import org.silverpeas.core.web.mvc.route.ComponentRequestRouter;
import org.silverpeas.web.silverstatistics.control.SilverStatisticsPeasSessionController;
import org.silverpeas.web.silverstatistics.vo.AxisStatsFilter;
import org.silverpeas.web.silverstatistics.vo.CrossAxisStatsFilter;
import org.silverpeas.web.silverstatistics.vo.CrossStatisticVO;
import org.silverpeas.web.silverstatistics.vo.StatisticVO;
import org.apache.commons.lang3.math.NumberUtils;
import org.silverpeas.core.admin.user.constant.UserAccessLevel;
import org.silverpeas.core.chart.period.PeriodChart;
import org.silverpeas.core.chart.pie.PieChart;
import org.silverpeas.core.web.http.HttpRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;
/**
* Class declaration
* @author
*/
public class SilverStatisticsPeasRequestRouter extends
ComponentRequestRouter<SilverStatisticsPeasSessionController> {
private static final long serialVersionUID = -7422373100761515806L;
private final SilverStatisticsActionAccessController actionAccessController =
new SilverStatisticsActionAccessController();
/**
* Method declaration
* @param mainSessionCtrl
* @param componentContext
* @return
*
*/
@Override
public SilverStatisticsPeasSessionController createComponentSessionController(
MainSessionController mainSessionCtrl, ComponentContext componentContext) {
return new SilverStatisticsPeasSessionController(mainSessionCtrl,
componentContext);
}
/**
* This method has to be implemented in the component request rooter class. returns the session
* control bean name to be put in the request object ex : for almanach, returns "almanach"
*/
@Override
public String getSessionControlBeanName() {
return "SilverStatisticsPeas";
}
/**
* This method has to be implemented by the component request router it has to compute a
* destination page
*
* @param function The entering request function (ex : "Main.jsp")
* @param statsSC The component Session Control, build and initialised.
* @param request
* @return The complete destination URL for a forward (ex :
* "/almanach/jsp/almanach.jsp?flag=user")
*/
@Override
public String getDestination(String function, SilverStatisticsPeasSessionController statsSC,
HttpRequest request) {
String destination = "";
UserAccessLevel userProfile = statsSC.getUserProfile();
if (UserAccessLevel.ADMINISTRATOR.equals(userProfile)
|| UserAccessLevel.SPACE_ADMINISTRATOR.equals(userProfile)) {
request.setAttribute("UserProfile", userProfile);
} else {
return null;
}
Calendar calendar = Calendar.getInstance();
String monthOfCurrentYear = String.valueOf(calendar.get(Calendar.MONTH));
String currentYear = String.valueOf(calendar.get(Calendar.YEAR));
calendar.add(Calendar.YEAR, -1);
String monthOfLastYear = String.valueOf(calendar.get(Calendar.MONTH));
String lastYear = String.valueOf(calendar.get(Calendar.YEAR));
try {
if (function.startsWith("Main")) {
// We only enter in the main case on the first access to the
// silverStatistics pages
request.setAttribute("ConnectedUsersList", statsSC
.getConnectedUsersList());
destination = "/silverStatisticsPeas/jsp/connections.jsp";
} else if (function.equals("KickSession")) {
statsSC.kickSession(request.getParameter("theSessionId"));
request.setAttribute("ConnectedUsersList", statsSC.getConnectedUsersList());
destination = "/silverStatisticsPeas/jsp/connections.jsp";
} else if (function.startsWith("ViewConnections")) {
statsSC.setMonthBegin(monthOfLastYear);
statsSC.setYearBegin(statsSC.checkYearConnection(lastYear));
statsSC.setMonthEnd(monthOfCurrentYear);
statsSC.setYearEnd(statsSC.checkYearConnection(currentYear));
statsSC.setActorDetail("0");
statsSC.setFilterType("");
statsSC.setFilterLib("");
statsSC.setFilterId("");
// init formulaire
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearConnection(statsSC.getYearBegin()));
request.setAttribute("MonthEnd", statsSC.getFormMonth(statsSC.getMonthEnd()));
request.setAttribute("YearEnd", statsSC.getFormYearConnection(statsSC.getYearEnd()));
request.setAttribute("ActorDetail", statsSC.getDetail("0"));
request.setAttribute("FilterType", "");
request.setAttribute("FilterLib", "");
request.setAttribute("FilterId", "");
destination = getDestination("ValidateViewConnection", statsSC, request);
} else if (function.startsWith("ValidateViewConnection")) {
// save request param
saveConnectionParam(request, statsSC);
String hostMonthBegin = statsSC.getMonthBegin();
String hostYearBegin = statsSC.getYearBegin();
String hostMonthEnd = statsSC.getMonthEnd();
String hostYearEnd = statsSC.getYearEnd();
String hostDateBegin = getRequestDate(hostYearBegin, hostMonthBegin);
String hostDateEnd = getRequestDate(hostYearEnd, hostMonthEnd);
String hostStatDetail = statsSC.getActorDetail();
String filterType = statsSC.getFilterType();
String filterId = statsSC.getFilterId();
// compute result
if ("0".equals(hostStatDetail))// All
{
if (!StringUtil.isDefined(filterType)) // no filter
{
request.setAttribute("ResultData", statsSC.getStatsConnexionAllAll(hostDateBegin,
hostDateEnd));
// graphiques
PeriodChart loginChart =
statsSC.getDistinctUserConnectionsChart(hostDateBegin, hostDateEnd);
request.setAttribute("DistinctUsersChart", loginChart);
PeriodChart userChart = statsSC.getUserConnectionsChart(hostDateBegin, hostDateEnd);
request.setAttribute("ConnectionsChart", userChart);
} else if ("0".equals(filterType)) // filter group
{
request.setAttribute("ResultData",
statsSC.getStatsConnexionAllGroup(hostDateBegin,
hostDateEnd, filterId));
// graphiques
PeriodChart userChart = statsSC.getUserConnectionsGroupChart(
hostDateBegin, hostDateEnd, filterId);
request.setAttribute("ConnectionsChart", userChart);
} else if ("1".equals(filterType)) // filter user
{
request.setAttribute("ResultData", statsSC.getStatsConnexionUser(hostDateBegin,
hostDateEnd, filterId));
// graphiques
PeriodChart userChart =
statsSC.getUserConnectionsUserChart(hostDateBegin, hostDateEnd, filterId);
request.setAttribute("ConnectionsChart", userChart);
}
} else if ("1".equals(hostStatDetail))// Groups
{
if (filterType.equals("")) // no filter
{
request.setAttribute("ResultData", statsSC
.getStatsConnexionGroupAll(hostDateBegin, hostDateEnd));
String entiteId = request.getParameter("EntiteId");
PeriodChart userChart = null;
if (entiteId != null) {
// graphiques
userChart =
statsSC.getUserConnectionsGroupChart(hostDateBegin, hostDateEnd, entiteId);
} else {
// graphiques
userChart = statsSC.getUserConnectionsChart(hostDateBegin, hostDateEnd);
}
request.setAttribute("ConnectionsChart", userChart);
} else if ("0".equals(filterType)) // filter group
{
request.setAttribute("ResultData", statsSC.getStatsConnexionGroupUser(hostDateBegin,
hostDateEnd, filterId));
// graphiques
PeriodChart userChart =
statsSC.getUserConnectionsGroupChart(hostDateBegin, hostDateEnd, filterId);
request.setAttribute("ConnectionsChart", userChart);
}
} else if (hostStatDetail.equals("2"))// Users
{
if (!StringUtil.isDefined(filterType)) // no filter
{
request.setAttribute("ResultData", statsSC.getStatsConnexionUserAll(hostDateBegin,
hostDateEnd));
String entiteId = request.getParameter("EntiteId");
PeriodChart userChart = null;
if (entiteId != null) {
// graphiques
userChart = statsSC.getUserConnectionsUserChart(hostDateBegin, hostDateEnd, entiteId);
} else {
// graphiques
userChart = statsSC.getUserConnectionsChart(hostDateBegin, hostDateEnd);
}
request.setAttribute("ConnectionsChart", userChart);
} else if (filterType.equals("1")) // filter user
{
request.setAttribute("ResultData", statsSC.getStatsConnexionUser(hostDateBegin,
hostDateEnd, filterId));
// graphiques
PeriodChart userChart =
statsSC.getUserConnectionsUserChart(hostDateBegin, hostDateEnd, filterId);
request.setAttribute("ConnectionsChart", userChart);
}
}
restoreConnectionParam(request, statsSC);
destination = "/silverStatisticsPeas/jsp/viewConnection.jsp";
} else if (function.startsWith("CallUserPanel")) {
// save request param
saveConnectionParam(request, statsSC);
// init user panel
destination = statsSC.initUserPanel();
} else if (function.startsWith("ReturnFromUserPanel")) {
// get user panel data (update FilterType and FilterLib, FilterId)
statsSC.retourUserPanel();
// restore request param
restoreConnectionParam(request, statsSC);
destination = getDestination("ValidateViewConnection", statsSC, request);
} else if (function.startsWith("ViewFrequence")) {
statsSC.setMonthBegin(monthOfLastYear);
statsSC.setYearBegin(statsSC.checkYearConnection(lastYear));
statsSC.setMonthEnd(monthOfCurrentYear);
statsSC.setYearEnd(statsSC.checkYearConnection(currentYear));
statsSC.setFrequenceDetail("0");
// init formulaire
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearConnection(statsSC.getYearBegin()));
request.setAttribute("MonthEnd", statsSC.getFormMonth(statsSC.getMonthEnd()));
request.setAttribute("YearEnd", statsSC.getFormYearConnection(statsSC.getYearEnd()));
request.setAttribute("FrequenceDetail", statsSC.getFrequenceDetail("0"));
destination = getDestination("ValidateViewFrequence", statsSC, request);
} else if (function.startsWith("ValidateViewFrequence")) {
// save request param
String hostMonthBegin = request.getParameter("MonthBegin");
if (hostMonthBegin != null && !hostMonthBegin.equals("")) {
statsSC.setMonthBegin(request.getParameter("MonthBegin"));
statsSC.setYearBegin(request.getParameter("YearBegin"));
statsSC.setMonthEnd(request.getParameter("MonthEnd"));
statsSC.setYearEnd(request.getParameter("YearEnd"));
statsSC.setFrequenceDetail(request.getParameter("FrequenceDetail"));
}
hostMonthBegin = statsSC.getMonthBegin();
String hostYearBegin = statsSC.getYearBegin();
String hostMonthEnd = statsSC.getMonthEnd();
String hostYearEnd = statsSC.getYearEnd();
String hostDateBegin = getRequestDate(hostYearBegin, hostMonthBegin);
String hostDateEnd = getRequestDate(hostYearEnd, hostMonthEnd);
String hostStatDetail = statsSC.getFrequenceDetail();
// graphiques
PeriodChart userFqChart =
statsSC.getUserConnectionsFqChart(hostDateBegin, hostDateEnd, hostStatDetail);
request.setAttribute("Chart", userFqChart);
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearConnection(statsSC.getYearBegin()));
request.setAttribute("MonthEnd", statsSC.getFormMonth(statsSC.getMonthEnd()));
request.setAttribute("YearEnd", statsSC.getFormYearConnection(statsSC.getYearEnd()));
request.setAttribute("FrequenceDetail", statsSC.getFrequenceDetail(statsSC
.getFrequenceDetail()));
destination = "/silverStatisticsPeas/jsp/viewFrequence.jsp";
} else if (function.startsWith("ViewAccess")) {
// Onglet Acces
statsSC.setAccessMonthBegin(monthOfCurrentYear);
statsSC.setAccessYearBegin(statsSC.checkYearAccess(currentYear));
statsSC.setAccessFilterLibGroup("");
statsSC.setAccessFilterIdGroup("");
statsSC.setAccessFilterLibUser("");
statsSC.setAccessFilterIdUser("");
statsSC.setAccessSpaceId("");
statsSC.clearCurrentStats();
// init formulaire access
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getAccessMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearAccess(statsSC.getAccessYearBegin()));
request.setAttribute("FilterLibGroup", statsSC.getAccessFilterLibGroup());
request.setAttribute("FilterIdGroup", statsSC.getAccessFilterIdGroup());
request.setAttribute("FilterLibUser", statsSC.getAccessFilterLibUser());
request.setAttribute("FilterIdUser", statsSC.getAccessFilterIdUser());
request.setAttribute("SpaceId", statsSC.getAccessSpaceId());
request.setAttribute("Path", statsSC.getPath());
destination = getDestination("ValidateViewAccess", statsSC, request);
} else if (function.startsWith("ValidateViewAccess")) {
// save request param
saveAccessVolumeParam(request, statsSC);
String hostMonthBegin = statsSC.getAccessMonthBegin();
String hostYearBegin = statsSC.getAccessYearBegin();
String filterIdGroup = statsSC.getAccessFilterIdGroup();
String filterIdUser = statsSC.getAccessFilterIdUser();
String spaceId = statsSC.getAccessSpaceId();
// compute result
PieChart chart = statsSC
.getUserVentilChart(getRequestDate(hostYearBegin, hostMonthBegin), filterIdGroup,
filterIdUser, spaceId);
request.setAttribute("Chart", chart);
request.setAttribute("StatsData", statsSC.getCurrentStats());
// restore request param
restoreAccessParam(request, statsSC);
destination = "/silverStatisticsPeas/jsp/viewAccess.jsp";
} else if (function.startsWith("AccessCallUserPanelGroup")) {
// save request param
saveAccessVolumeParam(request, statsSC);
// init user panel
destination = statsSC.initAccessUserPanelGroup();
} else if (function.startsWith("AccessReturnFromUserPanelGroup")) {
// get user panel data (update FilterLib, FilterId)
statsSC.retourAccessUserPanelGroup();
// restore request param
restoreAccessParam(request, statsSC);
destination = "/silverStatisticsPeas/jsp/viewAccess.jsp";
} else if (function.startsWith("AccessCallUserPanelUser")) {
// save request param
saveAccessVolumeParam(request, statsSC);
// init user panel
destination = statsSC.initAccessUserPanelUser();
} else if (function.startsWith("AccessReturnFromUserPanelUser")) {
// get user panel data (update FilterLib, FilterId)
statsSC.retourAccessUserPanelUser();
// restore request param
restoreAccessParam(request, statsSC);
destination = "/silverStatisticsPeas/jsp/viewAccess.jsp";
} else if (function.startsWith("ExportAccess.txt")) {
// compute result
request.setAttribute("FilterIdGroup", statsSC.getAccessFilterIdGroup());
request.setAttribute("FilterIdUser", statsSC.getAccessFilterIdUser());
request.setAttribute("StatsData", statsSC.getCurrentStats());
destination = "/silverStatisticsPeas/jsp/exportDataAccess.jsp";
} else if (function.startsWith("ViewEvolutionAccess")) {
String entite = request.getParameter("Entite");
String entiteId = request.getParameter("Id");
String filterLibGroup = statsSC.getAccessFilterLibGroup();
String filterIdGroup = statsSC.getAccessFilterIdGroup();
String filterLibUser = statsSC.getAccessFilterLibUser();
String filterIdUser = statsSC.getAccessFilterIdUser();
// compute result
PeriodChart lineChart =
statsSC.getEvolutionUserChart(entite, entiteId, filterLibGroup, filterIdGroup,
filterLibUser, filterIdUser);
request.setAttribute("Chart", lineChart);
// restore request param
request.setAttribute("Entite", entite);
request.setAttribute("Id", entiteId);
restoreAccessParam(request, statsSC);
destination = "/silverStatisticsPeas/jsp/viewEvolutionAccess.jsp";
} else if (function.startsWith("ViewVolumeServices")) {
// Onglet Volume
if (!UserAccessLevel.ADMINISTRATOR.equals(userProfile)) {
return getDestination("ViewVolumePublication", statsSC, request);
}
PieChart pieChart = statsSC.getVolumeServicesChart();
request.setAttribute("Chart", pieChart);
destination = "/silverStatisticsPeas/jsp/viewVolumeServices.jsp";
} else if (function.startsWith("ViewVolumePublication")) {
statsSC.setAccessMonthBegin(monthOfCurrentYear);
statsSC.setAccessYearBegin(statsSC.checkYearVolume(currentYear));
statsSC.setAccessFilterLibGroup("");
statsSC.setAccessFilterIdGroup("");
statsSC.setAccessFilterLibUser("");
statsSC.setAccessFilterIdUser("");
statsSC.setAccessSpaceId("");
statsSC.clearCurrentStats();
// init formulaire
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getAccessMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearVolume(statsSC.getAccessYearBegin()));
request.setAttribute("FilterLibGroup", statsSC.getAccessFilterLibGroup());
request.setAttribute("FilterIdGroup", statsSC.getAccessFilterIdGroup());
request.setAttribute("FilterLibUser", statsSC.getAccessFilterLibUser());
request.setAttribute("FilterIdUser", statsSC.getAccessFilterIdUser());
request.setAttribute("SpaceId", statsSC.getAccessSpaceId());
request.setAttribute("Path", statsSC.getPath());
destination = getDestination("ValidateViewVolume", statsSC, request);
} else if (function.startsWith("ValidateViewVolume")) {
// save request param
saveAccessVolumeParam(request, statsSC);
String hostMonthBegin = statsSC.getAccessMonthBegin();
String hostYearBegin = statsSC.getAccessYearBegin();
String filterIdGroup = statsSC.getAccessFilterIdGroup();
String filterIdUser = statsSC.getAccessFilterIdUser();
String spaceId = statsSC.getAccessSpaceId();
// compute result
PieChart pieChart =
statsSC.getPubliVentilChart(getRequestDate(hostYearBegin, hostMonthBegin),
filterIdGroup, filterIdUser, spaceId);
request.setAttribute("Chart", pieChart);
request.setAttribute("StatsData", statsSC.getCurrentStats());
// restore request param
restoreVolumeParam(request, statsSC);
destination = "/silverStatisticsPeas/jsp/viewVolume.jsp";
} else if (function.startsWith("VolumeCallUserPanelGroup")) {
// save request param
saveAccessVolumeParam(request, statsSC);
// init user panel
destination = statsSC.initVolumeUserPanelGroup();
} else if (function.startsWith("VolumeReturnFromUserPanelGroup")) {
// get user panel data (update FilterLib, FilterId)
statsSC.retourAccessUserPanelGroup();
// restore request param
restoreVolumeParam(request, statsSC);
destination = "/silverStatisticsPeas/jsp/viewVolume.jsp";
} else if (function.startsWith("VolumeCallUserPanelUser")) {
// save request param
saveAccessVolumeParam(request, statsSC);
// init user panel
destination = statsSC.initVolumeUserPanelUser();
} else if (function.startsWith("VolumeReturnFromUserPanelUser")) {
// get user panel data (update FilterLib, FilterId)
statsSC.retourAccessUserPanelUser();
// restore request param
restoreVolumeParam(request, statsSC);
destination = "/silverStatisticsPeas/jsp/viewVolume.jsp";
}
// Nbre de fichiers joints sur le serveur
else if (function.startsWith("ViewVolumeServer")) {
statsSC.setAccessSpaceId(request.getParameter("SpaceId"));
String spaceId = statsSC.getAccessSpaceId();
// compute result
PieChart pieChart = statsSC.getDocsVentilChart(spaceId);
request.setAttribute("Chart", pieChart);
request.setAttribute("StatsData", statsSC.getCurrentStats());
request.setAttribute("SpaceId", statsSC.getAccessSpaceId());
request.setAttribute("Path", statsSC.getPath());
destination = "/silverStatisticsPeas/jsp/viewVolumeServer.jsp";
} else if (function.startsWith("ViewVolumeSizeServer")) {
statsSC.setAccessSpaceId(request.getParameter("SpaceId"));
String spaceId = statsSC.getAccessSpaceId();
// compute result
PieChart pieChart = statsSC.getDocsSizeVentilChart(spaceId);
request.setAttribute("Chart", pieChart);
request.setAttribute("StatsData", statsSC.getCurrentStats());
request.setAttribute("SpaceId", statsSC.getAccessSpaceId());
request.setAttribute("Path", statsSC.getPath());
destination = "/silverStatisticsPeas/jsp/viewVolumeSizeServer.jsp";
} else if (function.startsWith("ViewEvolutionVolumeSizeServer")) {
// compute result
PeriodChart lineChart = statsSC.getEvolutionDocsSizeChart();
request.setAttribute("Chart", lineChart);
request.setAttribute("StatsData", statsSC.getCurrentStats());
destination = "/silverStatisticsPeas/jsp/viewEvolutionVolumeSizeServer.jsp";
} else if (function.startsWith("ViewPDCAccess")) {
// Initialize statistics session controller parameter
statsSC.setMonthBegin(monthOfLastYear);
statsSC.setYearBegin(statsSC.checkYearConnection(lastYear));
statsSC.setMonthEnd(monthOfCurrentYear);
statsSC.setYearEnd(statsSC.checkYearConnection(currentYear));
statsSC.clearCurrentStats();
// init formulaire access
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearConnection(statsSC.getYearBegin()));
request.setAttribute("MonthEnd", statsSC.getFormMonth(statsSC.getMonthEnd()));
request.setAttribute("YearEnd", statsSC.getFormYearConnection(statsSC.getYearEnd()));
// Add setter on PDC
// request.setAttribute("PrimaryAxis", statsSC.getPrimaryAxis());
// request.setAttribute("StatsData", statsSC.getAxisStats(statsFilter));
destination = getDestination("ValidateViewPDCAccess", statsSC, request);
} else if (function.startsWith("ValidateViewPDCAccess")) {
// save request param
saveAccessPDCParam(request, statsSC);
String monthBegin = getMonthParam(statsSC.getMonthBegin());
String yearBegin = statsSC.getYearBegin();
String monthEnd = getMonthParam(statsSC.getMonthEnd());
String yearEnd = statsSC.getYearEnd();
AxisStatsFilter axisStatsFilter =
new AxisStatsFilter(monthBegin, yearBegin, monthEnd, yearEnd);
// Retrieve selected axis from request
String axisId = request.getParameter("AxisId");
if (StringUtil.isDefined(axisId)) {
// set this data inside AxisStatsFilter
axisStatsFilter.setAxisId(Integer.parseInt(axisId));
}
String axisValue = request.getParameter("AxisValue");
if (StringUtil.isDefined(axisValue)) {
axisStatsFilter.setAxisValue(axisValue);
}
// compute result
List<StatisticVO> axisStats = statsSC.getAxisStats(axisStatsFilter);
// restore request param
request.setAttribute("StatsData", axisStats);
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearConnection(statsSC.getYearBegin()));
request.setAttribute("MonthEnd", statsSC.getFormMonth(statsSC.getMonthEnd()));
request.setAttribute("YearEnd", statsSC.getFormYearConnection(statsSC.getYearEnd()));
request.setAttribute("AxisId", axisId);
request.setAttribute("AxisValue", axisValue);
destination = "/silverStatisticsPeas/jsp/viewAccessPDC.jsp";
} else if (function.startsWith("ViewCrossPDCAccess")) {
statsSC.setMonthBegin(monthOfLastYear);
statsSC.setYearBegin(statsSC.checkYearConnection(lastYear));
statsSC.setMonthEnd(monthOfCurrentYear);
statsSC.setYearEnd(statsSC.checkYearConnection(currentYear));
statsSC.clearCurrentStats();
// init formulaire access
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearConnection(statsSC.getYearBegin()));
request.setAttribute("MonthEnd", statsSC.getFormMonth(statsSC.getMonthEnd()));
request.setAttribute("YearEnd", statsSC.getFormYearConnection(statsSC.getYearEnd()));
// Add setter on PDC
request.setAttribute("PrimaryAxis", statsSC.getPrimaryAxis());
destination = "/silverStatisticsPeas/jsp/viewCrossPDCAccess.jsp";
} else if (function.startsWith("ValidateViewCrossPDCAccess")) {
// save request param
saveAccessPDCParam(request, statsSC);
String monthBegin = getMonthParam(statsSC.getMonthBegin());
String yearBegin = statsSC.getYearBegin();
String monthEnd = getMonthParam(statsSC.getMonthEnd());
String yearEnd = statsSC.getYearEnd();
// Retrieve selected axis from request
Integer firstAxisId = NumberUtils.toInt(request.getParameter("FirstAxis"), 0);
Integer secondAxisId = NumberUtils.toInt(request.getParameter("SecondAxis"), 0);
// Initialize cross axis stats filter
CrossAxisStatsFilter axisStatsFilter =
new CrossAxisStatsFilter(monthBegin, yearBegin, monthEnd, yearEnd, firstAxisId,
secondAxisId);
CrossStatisticVO crossAxisStats = statsSC.getCrossAxisStats(axisStatsFilter);
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearConnection(statsSC.getYearBegin()));
request.setAttribute("MonthEnd", statsSC.getFormMonth(statsSC.getMonthEnd()));
request.setAttribute("YearEnd", statsSC.getFormYearConnection(statsSC.getYearEnd()));
// Add PDC data inside request
request.setAttribute("PrimaryAxis", statsSC.getPrimaryAxis());
request.setAttribute("FirstAxis", firstAxisId);
request.setAttribute("SecondAxis", secondAxisId);
request.setAttribute("StatsData", crossAxisStats);
destination = "/silverStatisticsPeas/jsp/viewCrossPDCAccess.jsp";
} else {
destination = "/silverStatisticsPeas/jsp/" + function;
}
} catch (Exception e) {
request.setAttribute("javax.servlet.jsp.jspException", e);
destination = "/admin/jsp/errorpageMain.jsp";
}
return destination;
}
@Override
protected boolean checkUserAuthorization(final String function,
final SilverStatisticsPeasSessionController componentSC) {
return actionAccessController.hasRightAccess(function, componentSC.getUserProfile());
}
/**
* @param monthParam string month parameter
* @return String representation of the month with two digits
*/
private String getMonthParam(String monthParam) {
String monthBegin = "" + (Integer.parseInt(monthParam) + 1);
if (monthBegin.length() < 2) {
monthBegin = "0" + monthBegin;
}
return monthBegin;
}
/**
* Set statistics session controller attributes from HttpServletRequest
* @param request which contains the parameters
* @param statsSC the statistics session controller Object
*/
private void saveConnectionParam(HttpServletRequest request,
SilverStatisticsPeasSessionController statsSC) {
String hostMonthBegin = request.getParameter("MonthBegin");
if (hostMonthBegin != null && !hostMonthBegin.equals("")) {
statsSC.setMonthBegin(request.getParameter("MonthBegin"));
statsSC.setYearBegin(request.getParameter("YearBegin"));
statsSC.setMonthEnd(request.getParameter("MonthEnd"));
statsSC.setYearEnd(request.getParameter("YearEnd"));
statsSC.setActorDetail(request.getParameter("ActorDetail"));
statsSC.setFilterType(request.getParameter("FilterType"));
statsSC.setFilterLib(request.getParameter("FilterLib"));
statsSC.setFilterId(request.getParameter("FilterId"));
}
}
/**
* Set connection parameter in request attributes
* @param request the HttpServlet
* @param statsSC the SilverStatisticsPeasSessionController object
*/
private void restoreConnectionParam(HttpServletRequest request,
SilverStatisticsPeasSessionController statsSC) {
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearConnection(statsSC.getYearBegin()));
request.setAttribute("MonthEnd", statsSC.getFormMonth(statsSC.getMonthEnd()));
request.setAttribute("YearEnd", statsSC.getFormYearConnection(statsSC.getYearEnd()));
request.setAttribute("ActorDetail", statsSC.getDetail(statsSC.getActorDetail()));
request.setAttribute("FilterType", statsSC.getFilterType());
request.setAttribute("FilterLib", statsSC.getFilterLib());
request.setAttribute("FilterId", statsSC.getFilterId());
}
private void saveAccessVolumeParam(HttpServletRequest request,
SilverStatisticsPeasSessionController statsSC) {
String hostMonthBegin = request.getParameter("MonthBegin");
if (hostMonthBegin != null && !hostMonthBegin.equals("")) {
statsSC.setAccessMonthBegin(request.getParameter("MonthBegin"));
statsSC.setAccessYearBegin(request.getParameter("YearBegin"));
statsSC.setAccessFilterLibGroup(request.getParameter("FilterLibGroup"));
statsSC.setAccessFilterIdGroup(request.getParameter("FilterIdGroup"));
statsSC.setAccessFilterLibUser(request.getParameter("FilterLibUser"));
statsSC.setAccessFilterIdUser(request.getParameter("FilterIdUser"));
statsSC.setAccessSpaceId(request.getParameter("SpaceId"));
}
}
private void restoreAccessParam(HttpServletRequest request,
SilverStatisticsPeasSessionController statsSC) {
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getAccessMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearAccess(statsSC.getAccessYearBegin()));
request.setAttribute("FilterLibGroup", statsSC.getAccessFilterLibGroup());
request.setAttribute("FilterIdGroup", statsSC.getAccessFilterIdGroup());
request.setAttribute("FilterLibUser", statsSC.getAccessFilterLibUser());
request.setAttribute("FilterIdUser", statsSC.getAccessFilterIdUser());
request.setAttribute("SpaceId", statsSC.getAccessSpaceId());
request.setAttribute("Path", statsSC.getPath());
}
private void restoreVolumeParam(HttpServletRequest request,
SilverStatisticsPeasSessionController statsSC) {
request.setAttribute("MonthBegin", statsSC.getFormMonth(statsSC.getAccessMonthBegin()));
request.setAttribute("YearBegin", statsSC.getFormYearVolume(statsSC.getAccessYearBegin()));
request.setAttribute("FilterLibGroup", statsSC.getAccessFilterLibGroup());
request.setAttribute("FilterIdGroup", statsSC.getAccessFilterIdGroup());
request.setAttribute("FilterLibUser", statsSC.getAccessFilterLibUser());
request.setAttribute("FilterIdUser", statsSC.getAccessFilterIdUser());
request.setAttribute("SpaceId", statsSC.getAccessSpaceId());
request.setAttribute("Path", statsSC.getPath());
}
/**
* Format a year and month parameter
* @param sYear the year to format
* @param sMonth the month to format
* @return a request date string with the following format sYear-sMonth-01
*/
private String getRequestDate(String sYear, String sMonth) {
String month = Integer.toString(Integer.parseInt(sMonth) + 1);
if (month.length() < 2) {
month = "0" + month;
}
return sYear + "-" + month + "-" + "01";
}
/**
* Set silver statistics session controller attributes from request
* @param request the current http request
* @param statsSC the statistics session controller.
*/
private void saveAccessPDCParam(HttpServletRequest request,
SilverStatisticsPeasSessionController statsSC) {
String monthBegin = request.getParameter("MonthBegin");
if (StringUtil.isDefined(monthBegin)) {
statsSC.setMonthBegin(request.getParameter("MonthBegin"));
statsSC.setYearBegin(request.getParameter("YearBegin"));
statsSC.setMonthEnd(request.getParameter("MonthEnd"));
statsSC.setYearEnd(request.getParameter("YearEnd"));
}
}
}
| agpl-3.0 |
FilotasSiskos/hopsworks | hopsworks-common/src/main/java/io/hops/hopsworks/common/dao/log/meta/MetaLogFacade.java | 703 | package io.hops.hopsworks.common.dao.log.meta;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import io.hops.hopsworks.common.dao.AbstractFacade;
@Stateless
public class MetaLogFacade extends AbstractFacade<MetaLog> {
private static final Logger logger = Logger.getLogger(MetaLogFacade.class.
getName());
@PersistenceContext(unitName = "kthfsPU")
private EntityManager em;
public MetaLogFacade() {
super(MetaLog.class);
}
@Override
protected EntityManager getEntityManager() {
return em;
}
public void persist(MetaLog metaLog) {
em.persist(metaLog);
}
}
| agpl-3.0 |
knowledgetechnologyuhh/docks_nightly | src/Utils/ConfigCreator.java | 19272 | /**
* DOCKS is a framework for post-processing results of Cloud-based speech
* recognition systems.
* Copyright (C) 2014 Johannes Twiefel
*
* 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:
* 7twiefel@informatik.uni-hamburg.de
*/
package Utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import Data.Result;
import Phoneme.PhonemeCreator;
/**
* class used to create a full configuration from a batchfile
* those are list of sentences, word list, XMLs for sphinx and sphinx based, language models etc.
* @author 7twiefel
*
*/
public class ConfigCreator {
private static String TAG = "ConfigCreator";
//creates a new xml file for the config
private static void createXML(String basepath, String configname, String xmlname) {
String prefix = "config/example/example";
FileInputStream fstream = null;
try {
fstream = new FileInputStream(prefix + xmlname);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(basepath+configname + xmlname));
//read in an example XML
while ((strLine = br.readLine()) != null) {
if(strLine.contains("<property name=\"grammarfile\""))
{
out.write("<property name=\"grammarfile\" value=\""+configname+"\"/>\n");
}else if(strLine.contains("<property name=\"grammarpath\""))
{
out.write("<property name=\"grammarpath\" value=\"file:"+basepath+"/model/\"/>\n");
} else if(strLine.contains("<property name=\"dictionaryfile\""))
{
out.write("<property name=\"dictionaryfile\" value=\"file:"+basepath+"model/"+configname+".dic\"/>\n");
} else if(strLine.contains("<property name=\"languagemodelfile\""))
{
out.write("<property name=\"languagemodelfile\" value=\"file:"+basepath+"model/"+configname+".lm\"/>\n");
} else
out.write(strLine+"\n");
}
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//remove all serialized phonemes
private static void removeSerializedFiles(String configname)
{
String sentenceFile = "config/"+configname+"/"+configname+".sentences.ser";
String wordFile = "config/"+configname+"/"+configname+".words.ser";
System.out.println("deleting: "+sentenceFile);
System.out.println("deleting: "+wordFile);
boolean sentenceFileDeleted = (new File(sentenceFile)).delete();
boolean wordFileDeleted = (new File(wordFile)).delete();
System.out.println("Sentence file deleted: "+Boolean.toString(sentenceFileDeleted));
System.out.println("Word file deleted: "+Boolean.toString(wordFileDeleted));
}
/**
* creates a new config from a batchfile in /config/<nameofconfig>/
* @param configname name of the config
* @param batchfile path to batchfile
*/
public static void createConfig(String configname, String batchfile) {
System.out.println("creating config:");
System.out.println(configname);
System.out.println("batchfile: "+batchfile);
String basepath = "config/"+configname+"/";
(new File(basepath)).mkdirs();
(new File(basepath+"/model")).mkdirs();
//remove serialized phonemes
removeSerializedFiles(configname);
//create sentence list
createSentenceList(batchfile, basepath+configname + ".sentences.txt");
//remove dublicates
sentenceFileDeleteDublicates(basepath+configname+".sentences.txt");
//create word list
sentenceListToWordList(basepath+configname + ".sentences.txt", basepath+configname
+ ".words.txt");
//create dictionary
wordListToDictionary(basepath,basepath+configname + ".words", basepath+"model/" + configname
+ ".dic");
//create a sentencelist grammar
sentenceListToGrammar(basepath+configname + ".sentences.txt",basepath+"model/"+configname+".gram");
//create a grammar of sentences config for sphinx
createXML(basepath,configname,".fsgsentences.xml");
//create an n-gram config for sphinx
createXML(basepath,configname,".ngram.xml");
//create a grammar of sentences config for sphinx based postprocessors
createXML(basepath,configname,".pgrammarsentences.xml");
//create an n-gram config for sphinx based postprocessors
createXML(basepath,configname,".pngram.xml");
createXML(basepath,configname,".punigram.xml");
//create a sent file from a sentencelist
sentenceListToSentFile(basepath,basepath+configname+".sentences.txt",configname);
//create a language model
sentFileToLanguageModel(basepath,basepath+"model/"+configname+".sent",configname);
}
//create a grammar of sentence out of a list of sentences
private static void sentenceListToGrammar(String sentenceFile,
String grammarFile) {
FileInputStream fstream = null;
try {
fstream = new FileInputStream(sentenceFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(grammarFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.write("#JSGF V1.0;" + "\n" + "\n" + "/**" + "\n"
+ " * JSGF Grammar for WTM" + "\n" + " */" + "\n" + "\n"
+ "grammar scenario;" + "\n" + "\n"
+ "public <utterance> = " + "(" + br.readLine() + ")");
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
out.write(" |" + "\n" + "(" + strLine + ")");
}
out.write(";");
System.out.println("AAA");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//create a sentencelist from a batch file
private static void createSentenceList(String inputBatch,
String nameSentenceFile) {
FileInputStream fstream = null;
try {
fstream = new FileInputStream(inputBatch);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(nameSentenceFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
while ((strLine = br.readLine()) != null) {
int endName = strLine.indexOf(" ");
String sentence = strLine.substring(endName + 1);
sentence = sentence.replaceAll(",", "");
sentence = sentence.replaceAll("\\.", "");
out.write(sentence + "\n");
}
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* change the path of audiofile in a batchfile
* @param batchfile
* @param newPath
*/
public static void changeBatchFilePath(String batchfile, String newPath) {
FileInputStream fstream = null;
try {
fstream = new FileInputStream(batchfile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(batchfile + ".new"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
while ((strLine = br.readLine()) != null) {
String rest = strLine.substring(strLine.lastIndexOf("/") + 1);
String line = newPath + rest + "\n";
System.out.print(line);
out.write(line);
}
System.out.println("AAA");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(new File(batchfile)).delete();
(new File(batchfile + ".new")).renameTo(new File(batchfile));
}
/**
* creates a sub data set randomly from a batch file
* @param path to batch file
* @param batchfile name of batchfile
* @param contentInPercent partition of whole data set in percent
* @param session provide a session number if there are more sessions
*/
public static void createSubBatchfile(String path, String batchfile, int contentInPercent, int session) {
int numberExamples= -1;
try {
numberExamples = TestSupervisor.count(path + batchfile);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
ArrayList<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < numberExamples; i++) {
numbers.add(i);
}
Collections.shuffle(numbers);
ArrayList<Integer> chosenNumbers = new ArrayList<Integer>();
int numberChosenExamples = (int) Math.round((numberExamples*contentInPercent)/100.0);
System.out.println(numberChosenExamples+" "+numberExamples);
for (int i = 0; i < numberChosenExamples; i++) {
chosenNumbers.add(numbers.get(i));
}
Collections.sort(chosenNumbers);
FileInputStream fstream = null;
try {
fstream = new FileInputStream(path+batchfile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(path+batchfile +"_"+contentInPercent+"_percent_session_"+session));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
int count = 0;
while ((strLine = br.readLine()) != null) {
if(chosenNumbers.contains(count))
out.write(strLine+"\n");
count++;
}
System.out.println("AAA");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//delete dublicates from a sentencelist
private static void sentenceFileDeleteDublicates(String sentenceFile) {
FileInputStream fstream = null;
try {
fstream = new FileInputStream(sentenceFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
ArrayList<String> sentences = new ArrayList<String>();
try {
while ((strLine = br.readLine()) != null) {
if(!sentences.contains(strLine))
{
sentences.add(strLine);
System.out.println(strLine+" "+sentences.size()+" "+"added");
}else
System.out.println(strLine+" "+sentences.size()+" "+"already exists");
}
System.out.println("AAA");
br.close();
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(sentenceFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for(String s: sentences)
{
out.write(s+"\n");
}
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private static void changeBatchFilePathIcub() {
String path_L = "/informatik2/wtm/KT-Datasets/recs_extMic_iCubOff/amplified_16bit_16000Hz_mono_L/";
String path_R = "/informatik2/wtm/KT-Datasets/recs_extMic_iCubOff/amplified_16bit_16000Hz_mono_R/";
String path_mean = "/informatik2/wtm/KT-Datasets/recs_extMic_iCubOff/amplified_16bit_16000Hz_mono_mean/";
for (int i = 0; i <= 180; i = i + 15) {
Printer.reset();
String formNumber = String.format("%03d", i);
changeBatchFilePath(path_L + formNumber + "_batch", path_L + "rec_"
+ formNumber + "/");
changeBatchFilePath(path_R + formNumber + "_batch", path_R + "rec_"
+ formNumber + "/");
changeBatchFilePath(path_mean + formNumber + "_batch", path_mean
+ "rec_" + formNumber + "/");
Printer.printWithTimeImportant(TAG, i + "");
}
}
/**
*
* @param path path to batch file
* @param batchfile name of batchfile
* @return a set of words contained in the batchfile
*/
public static HashSet<String> getWordList(String path, String batchfile) {
HashSet<String> words = new HashSet<String>();
FileInputStream fstream = null;
try {
fstream = new FileInputStream(path + batchfile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
try {
while ((strLine = br.readLine()) != null) {
int endName = strLine.indexOf(" ");
String sentence = strLine.substring(endName + 1);
sentence = sentence.replaceAll("[^a-zA-Z 0-9;]", "");
sentence = sentence.replaceAll(" +", " ");
if (!sentence.equals(""))
if (sentence.charAt(0) == ' ')
sentence = sentence.substring(1);
String[] sentenceWords = sentence.split(" ");
for (String s : sentenceWords)
words.add(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return words;
}
//get an output file writer
private static BufferedWriter getWriter(String file) {
try {
return new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//create a dictionary from a list of words
private static void wordListToDictionary(String basepath,String wordList, String dicfile) {
PhonemeCreator pc = PhonemeCreator.getInstance(wordList);
HashSet<String> words = new HashSet<String>();
FileInputStream fstream = null;
try {
fstream = new FileInputStream(wordList + ".txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
try {
while ((strLine = br.readLine()) != null) {
String sentence = strLine;
sentence = sentence.replaceAll(",", "");
String[] sentenceWords = sentence.split(" ");
for (String s : sentenceWords)
words.add(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedWriter out = getWriter(dicfile);
Result r;
for (String s : words) {
try {
out.write(s + "\t");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
r = new Result();
r.addResult(s);
String[] pho = pc.getPhonemes(r).get(0).getPhonemes();
for (int i = 0; i < pho.length; i++) {
if (i == pho.length - 1)
try {
out.write(pho[i] + "\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
try {
out.write(pho[i] + " ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//create a language model from a sent file
private static void sentFileToLanguageModel(String basepath,String sentFile, String configname)
{
ProcessBuilder builder = new ProcessBuilder("./tools/quick_lm.pl",
"-s",sentFile);
Process p = null;
try {
p = builder.start();
p.waitFor();
(new File(basepath +"model/"+configname+".sent.arpabo")).renameTo(new
File(basepath +"model/"+configname+".lm"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//create a sent file from a sentence list file
private static void sentenceListToSentFile(String basepath, String sentenceList,
String configname) {
FileInputStream fstream = null;
try {
fstream = new FileInputStream(sentenceList);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
FileWriter out = null;
try {
out = new FileWriter(basepath+"model/"+configname+".sent");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String strLine;
try {
while ((strLine = br.readLine()) != null) {
String sentence = strLine;
out.write("<s> " +sentence+ " </s>\n");
}
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//create a wordlist from a sentencelist
private static void sentenceListToWordList(String sentenceList,
String wordList) {
HashSet<String> words = new HashSet<String>();
FileInputStream fstream = null;
try {
fstream = new FileInputStream(sentenceList);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
try {
while ((strLine = br.readLine()) != null) {
String sentence = strLine;
sentence = sentence.replaceAll(",", "");
String[] sentenceWords = sentence.split(" ");
for (String s : sentenceWords)
words.add(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileWriter out;
try {
out = new FileWriter(wordList);
for (String word : words)
out.write(word + "\n");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| agpl-3.0 |
jwillia/kc-old1 | coeus-impl/src/main/java/org/kuali/kra/protocol/ProtocolBase.java | 75543 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kra.protocol;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.kuali.coeus.common.committee.impl.bo.CommitteeMembershipBase;
import org.kuali.coeus.common.framework.attachment.AttachmentFile;
import org.kuali.coeus.common.framework.custom.attr.CustomAttributeDocument;
import org.kuali.coeus.common.framework.version.sequence.owner.SequenceOwner;
import org.kuali.coeus.common.notification.impl.bo.KcNotification;
import org.kuali.coeus.common.framework.auth.perm.Permissionable;
import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.protocol.auth.UnitAclLoadable;
import org.kuali.kra.coi.Disclosurable;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.coeus.common.framework.krms.KcKrmsContextBo;
import org.kuali.kra.protocol.actions.ProtocolActionBase;
import org.kuali.kra.protocol.actions.ProtocolStatusBase;
import org.kuali.kra.protocol.actions.amendrenew.ProtocolAmendRenewModuleBase;
import org.kuali.kra.protocol.actions.amendrenew.ProtocolAmendRenewalBase;
import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionBase;
import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionStatusBase;
import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionTypeBase;
import org.kuali.kra.protocol.noteattachment.*;
import org.kuali.kra.protocol.onlinereview.ProtocolOnlineReviewBase;
import org.kuali.kra.protocol.personnel.ProtocolPersonBase;
import org.kuali.kra.protocol.personnel.ProtocolPersonnelService;
import org.kuali.kra.protocol.personnel.ProtocolUnitBase;
import org.kuali.kra.protocol.protocol.ProtocolTypeBase;
import org.kuali.kra.protocol.protocol.funding.ProtocolFundingSourceBase;
import org.kuali.kra.protocol.protocol.location.ProtocolLocationBase;
import org.kuali.kra.protocol.protocol.location.ProtocolLocationService;
import org.kuali.kra.protocol.protocol.reference.ProtocolReferenceBase;
import org.kuali.kra.protocol.protocol.research.ProtocolResearchAreaBase;
import org.kuali.kra.protocol.specialreview.ProtocolSpecialReviewBase;
import org.kuali.kra.protocol.specialreview.ProtocolSpecialReviewExemption;
import org.kuali.kra.protocol.summary.*;
import org.kuali.coeus.common.questionnaire.framework.answer.Answer;
import org.kuali.coeus.common.questionnaire.framework.answer.AnswerHeader;
import org.kuali.coeus.common.questionnaire.framework.answer.QuestionnaireAnswerService;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.SequenceAccessorService;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.ObjectUtils;
import java.io.Serializable;
import java.sql.Date;
import java.util.*;
import java.util.Map.Entry;
public abstract class ProtocolBase extends KcPersistableBusinessObjectBase implements SequenceOwner<ProtocolBase>, Permissionable, UnitAclLoadable, Disclosurable, KcKrmsContextBo {
private static final long serialVersionUID = -5556152547067349988L;
protected static final CharSequence AMENDMENT_LETTER = "A";
protected static final CharSequence RENEWAL_LETTER = "R";
protected static final String NEXT_ACTION_ID_KEY = "actionId";
private Long protocolId;
private String protocolNumber;
private Integer sequenceNumber;
private boolean active = true;
private String protocolTypeCode;
private String protocolStatusCode;
private String title;
private String description;
private Date initialSubmissionDate;
private Date approvalDate;
private Date expirationDate;
private Date lastApprovalDate;
private String fdaApplicationNumber;
private String referenceNumber1;
private String referenceNumber2;
private String specialReviewIndicator = "Y";
private String keyStudyPersonIndicator;
private String fundingSourceIndicator;
private String correspondentIndicator;
private String referenceIndicator;
private String relatedProjectsIndicator;
private ProtocolDocumentBase protocolDocument;
private ProtocolStatusBase protocolStatus;
private ProtocolTypeBase protocolType;
private List<ProtocolResearchAreaBase> protocolResearchAreas;
private List<ProtocolReferenceBase> protocolReferences;
private List<ProtocolLocationBase> protocolLocations;
//Is transient, used for lookup select option in UI by KNS
private String newDescription;
private boolean nonEmployeeFlag;
private List<ProtocolFundingSourceBase> protocolFundingSources;
private String leadUnitNumber;
private String principalInvestigatorId;
// lookup field
private String keyPerson;
private String investigator;
private String fundingSource;
private String performingOrganizationId;
private String researchAreaCode;
private String leadUnitName;
private List<ProtocolPersonBase> protocolPersons;
private List<ProtocolSpecialReviewBase> specialReviews;
//these are the m:m attachment protocols that that a protocol has
private List<ProtocolAttachmentProtocolBase> attachmentProtocols;
private List<ProtocolNotepadBase> notepads;
private List<ProtocolActionBase> protocolActions;
private List<ProtocolSubmissionBase> protocolSubmissions;
private ProtocolSubmissionBase protocolSubmission;
private transient List<ProtocolActionBase> sortedActions;
/*
* There should only be zero or one entry in the protocolAmendRenewals
* list. It is because of OJB that a list is used instead of a single item.
*/
private List<ProtocolAmendRenewalBase> protocolAmendRenewals;
private transient boolean correctionMode = false;
private transient DateTimeService dateTimeService;
private transient SequenceAccessorService sequenceAccessorService;
//Used to filter protocol attachments
private transient ProtocolAttachmentFilterBase protocolAttachmentFilter;
// passed in req param submissionid. used to check if irb ack is needed
// this link is from protocosubmission or notify irb message
private transient Long notifyIrbSubmissionId;
// transient for protocol header combined label
private transient String initiatorLastUpdated;
private transient String protocolSubmissionStatus;
// Custom ProtocolBase lookup fields
private transient boolean lookupPendingProtocol;
private transient boolean lookupPendingPIActionProtocol;
private transient boolean lookupActionAmendRenewProtocol;
private transient boolean lookupActionRequestProtocol;
private transient boolean lookupProtocolPersonId;
private transient boolean mergeAmendment;
public String getInitiatorLastUpdated() {
return initiatorLastUpdated;
}
public String getProtocolSubmissionStatus() {
return protocolSubmissionStatus;
}
/**
*
* Constructs an ProtocolBase BO.
*/
public ProtocolBase() {
super();
sequenceNumber = new Integer(0);
protocolResearchAreas = new ArrayList<ProtocolResearchAreaBase>();
protocolReferences = new ArrayList<ProtocolReferenceBase>();
newDescription = getDefaultNewDescription();
protocolStatus = getProtocolStatusNewInstanceHook();
protocolStatusCode = protocolStatus.getProtocolStatusCode();
protocolLocations = new ArrayList<ProtocolLocationBase>();
protocolPersons = new ArrayList<ProtocolPersonBase>();
// set the default protocol type
protocolTypeCode = getDefaultProtocolTypeCodeHook();
protocolFundingSources = new ArrayList<ProtocolFundingSourceBase>();
specialReviews = new ArrayList<ProtocolSpecialReviewBase>();
setProtocolActions(new ArrayList<ProtocolActionBase>());
setProtocolSubmissions(new ArrayList<ProtocolSubmissionBase>());
protocolAmendRenewals = new ArrayList<ProtocolAmendRenewalBase>();
// set statuscode default
setProtocolStatusCode(getDefaultProtocolStatusCodeHook());
this.refreshReferenceObject(Constants.PROPERTY_PROTOCOL_STATUS);
initializeProtocolAttachmentFilter();
}
protected abstract ProtocolStatusBase getProtocolStatusNewInstanceHook();
protected abstract String getDefaultProtocolStatusCodeHook();
protected abstract String getDefaultProtocolTypeCodeHook();
public Long getProtocolId() {
return protocolId;
}
public void setProtocolId(Long protocolId) {
this.protocolId = protocolId;
}
public String getProtocolNumber() {
return protocolNumber;
}
public void setProtocolNumber(String protocolNumber) {
this.protocolNumber = protocolNumber;
}
public Integer getSequenceNumber() {
return sequenceNumber;
}
public void setSequenceNumber(Integer sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isActive() {
return active;
}
public String getProtocolTypeCode() {
return protocolTypeCode;
}
public void setProtocolTypeCode(String protocolTypeCode) {
this.protocolTypeCode = protocolTypeCode;
}
public String getProtocolStatusCode() {
return protocolStatusCode;
}
public void setProtocolStatusCode(String protocolStatusCode) {
this.protocolStatusCode = protocolStatusCode;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the submission date. If the submission date is the last
* submission for the protocol. If the protocol has not been submitted,
* null is returned.
* @return the submission date or null if not yet submitted
*/
public Date getSubmissionDate() {
// TODO : the last one in the list may not be the last one submitted
// getProtocolSubmission will get the last one. SO, this method may not needed.
// Also, this method only referenced in test once.
Date submissionDate = null;
if (protocolSubmissions.size() > 0) {
// ProtocolSubmissionBase submission = protocolSubmissions.get(protocolSubmissions.size() - 1);
// submissionDate = submission.getSubmissionDate();
submissionDate = getProtocolSubmission().getSubmissionDate();
}
return submissionDate;
}
public Date getInitialSubmissionDate() {
return initialSubmissionDate;
}
public void setInitialSubmissionDate(Date initialSubmissionDate) {
this.initialSubmissionDate = initialSubmissionDate;
}
public Date getApprovalDate() {
return approvalDate;
}
public void setApprovalDate(Date approvalDate) {
this.approvalDate = approvalDate;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public Date getLastApprovalDate() {
return lastApprovalDate;
}
public void setLastApprovalDate(Date lastApprovalDate) {
this.lastApprovalDate = lastApprovalDate;
}
public String getFdaApplicationNumber() {
return fdaApplicationNumber;
}
public void setFdaApplicationNumber(String fdaApplicationNumber) {
this.fdaApplicationNumber = fdaApplicationNumber;
}
public String getReferenceNumber1() {
return referenceNumber1;
}
public void setReferenceNumber1(String referenceNumber1) {
this.referenceNumber1 = referenceNumber1;
}
public String getReferenceNumber2() {
return referenceNumber2;
}
public void setReferenceNumber2(String referenceNumber2) {
this.referenceNumber2 = referenceNumber2;
}
public String getSpecialReviewIndicator() {
return specialReviewIndicator;
}
public void setSpecialReviewIndicator(String specialReviewIndicator) {
this.specialReviewIndicator = specialReviewIndicator;
}
public String getKeyStudyPersonIndicator() {
return keyStudyPersonIndicator;
}
public void setKeyStudyPersonIndicator(String keyStudyPersonIndicator) {
this.keyStudyPersonIndicator = keyStudyPersonIndicator;
}
public String getFundingSourceIndicator() {
return fundingSourceIndicator;
}
public void setFundingSourceIndicator(String fundingSourceIndicator) {
this.fundingSourceIndicator = fundingSourceIndicator;
}
public String getCorrespondentIndicator() {
return correspondentIndicator;
}
public void setCorrespondentIndicator(String correspondentIndicator) {
this.correspondentIndicator = correspondentIndicator;
}
public String getReferenceIndicator() {
return referenceIndicator;
}
public void setReferenceIndicator(String referenceIndicator) {
this.referenceIndicator = referenceIndicator;
}
public String getRelatedProjectsIndicator() {
return relatedProjectsIndicator;
}
public void setRelatedProjectsIndicator(String relatedProjectsIndicator) {
this.relatedProjectsIndicator = relatedProjectsIndicator;
}
/**
* Collects and returns all online reviews for all submissions for this protocol.
* @return all online reviews for this protocol
*/
public List<ProtocolOnlineReviewBase> getProtocolOnlineReviews() {
List<ProtocolOnlineReviewBase> reviews = new ArrayList<ProtocolOnlineReviewBase>();
for (ProtocolSubmissionBase submission : getProtocolSubmissions()) {
reviews.addAll(submission.getProtocolOnlineReviews());
}
return reviews;
}
public ProtocolStatusBase getProtocolStatus() {
return protocolStatus;
}
public void setProtocolStatus(ProtocolStatusBase protocolStatus) {
this.protocolStatus = protocolStatus;
}
public ProtocolTypeBase getProtocolType() {
return protocolType;
}
public void setProtocolType(ProtocolTypeBase protocolType) {
this.protocolType = protocolType;
}
public String getNewDescription() {
return newDescription;
}
public void setNewDescription(String newDescription) {
this.newDescription = newDescription;
}
public String getDefaultNewDescription() {
return "(select)";
}
public void setProtocolResearchAreas(List<ProtocolResearchAreaBase> protocolResearchAreas) {
this.protocolResearchAreas = protocolResearchAreas;
for (ProtocolResearchAreaBase researchArea : protocolResearchAreas) {
researchArea.init(this);
}
}
public List<ProtocolResearchAreaBase> getProtocolResearchAreas() {
return protocolResearchAreas;
}
public void addProtocolResearchAreas(ProtocolResearchAreaBase protocolResearchArea) {
getProtocolResearchAreas().add(protocolResearchArea);
}
public ProtocolResearchAreaBase getProtocolResearchAreas(int index) {
while (getProtocolResearchAreas().size() <= index) {
getProtocolResearchAreas().add(getNewProtocolResearchAreaInstance());
}
return getProtocolResearchAreas().get(index);
}
protected abstract ProtocolResearchAreaBase getNewProtocolResearchAreaInstance();
public void setProtocolReferences(List<ProtocolReferenceBase> protocolReferences) {
this.protocolReferences = protocolReferences;
for (ProtocolReferenceBase reference : protocolReferences) {
reference.init(this);
}
}
public List<ProtocolReferenceBase> getProtocolReferences() {
return protocolReferences;
}
public ProtocolDocumentBase getProtocolDocument() {
return protocolDocument;
}
public void setProtocolDocument(ProtocolDocumentBase protocolDocument) {
this.protocolDocument = protocolDocument;
}
public void setProtocolLocations(List<ProtocolLocationBase> protocolLocations) {
this.protocolLocations = protocolLocations;
for (ProtocolLocationBase location : protocolLocations) {
location.init(this);
}
}
public List<ProtocolLocationBase> getProtocolLocations() {
return protocolLocations;
}
@SuppressWarnings("unchecked")
@Override
public List buildListOfDeletionAwareLists() {
List managedLists = super.buildListOfDeletionAwareLists();
managedLists.add(this.protocolResearchAreas);
managedLists.add(this.protocolReferences);
managedLists.add(getProtocolFundingSources());
managedLists.add(getProtocolLocations());
managedLists.add(getProtocolAttachmentPersonnel());
managedLists.add(getProtocolUnits());
managedLists.add(getAttachmentProtocols());
managedLists.add(getProtocolPersons());
managedLists.add(getProtocolActions());
managedLists.add(getProtocolSubmissions());
if (getProtocolAmendRenewal() != null) {
managedLists.add(getProtocolAmendRenewal().getModules());
} else {
// needed to ensure that the OjbCollectionHelper receives constant list size.
managedLists.add(new ArrayList<ProtocolAmendRenewModuleBase>());
}
managedLists.add(getProtocolAmendRenewals());
List<ProtocolSpecialReviewExemption> specialReviewExemptions = new ArrayList<ProtocolSpecialReviewExemption>();
for (ProtocolSpecialReviewBase specialReview : getSpecialReviews()) {
specialReviewExemptions.addAll(specialReview.getSpecialReviewExemptions());
}
managedLists.add(specialReviewExemptions);
managedLists.add(getSpecialReviews());
managedLists.add(getNotepads());
return managedLists;
}
/**
* This method is to return all attachments for each person.
* Purpose of this method is to use the list in buildListOfDeletionAwareLists.
* Looks like OJB is not searching beyond the first level. It doesn't delete
* from collection under ProtocolPersonBase.
* @return List<ProtocolAttachmentPersonnelBase>
*/
private List<ProtocolAttachmentPersonnelBase> getProtocolAttachmentPersonnel() {
List<ProtocolAttachmentPersonnelBase> protocolAttachmentPersonnel = new ArrayList<ProtocolAttachmentPersonnelBase>();
for (ProtocolPersonBase protocolPerson : getProtocolPersons()) {
protocolAttachmentPersonnel.addAll(protocolPerson.getAttachmentPersonnels());
}
return protocolAttachmentPersonnel;
}
/**
* This method is to return all protocol units for each person.
* Purpose of this method is to use the list in buildListOfDeletionAwareLists.
* Looks like OJB is not searching beyond the first level. It doesn't delete
* from collection under ProtocolPersonBase.
* @return List<ProtocolUnitBase>
*/
private List<ProtocolUnitBase> getProtocolUnits() {
List<ProtocolUnitBase> protocolUnits = new ArrayList<ProtocolUnitBase>();
for (ProtocolPersonBase protocolPerson : getProtocolPersons()) {
protocolUnits.addAll(protocolPerson.getProtocolUnits());
}
return protocolUnits;
}
/**
* This method is to find Principal Investigator from ProtocolPersonBase list
* @return ProtocolPersonBase
*/
public ProtocolPersonBase getPrincipalInvestigator() {
return getProtocolPersonnelService().getPrincipalInvestigator(getProtocolPersons());
}
public String getPrincipalInvestigatorName() {
ProtocolPersonBase pi = getPrincipalInvestigator();
return pi != null ? pi.getFullName() : null;
}
public ProtocolUnitBase getLeadUnit() {
ProtocolUnitBase leadUnit = null;
if (getPrincipalInvestigator() != null) {
for ( ProtocolUnitBase unit : getPrincipalInvestigator().getProtocolUnits() ) {
if (unit.getLeadUnitFlag()) {
leadUnit = unit;
}
}
}
return leadUnit;
}
public String getLeadUnitNumber() {
if (StringUtils.isBlank(leadUnitNumber)) {
if (getLeadUnit() != null) {
setLeadUnitNumber(getLeadUnit().getUnitNumber());
}
}
return leadUnitNumber;
}
public void setLeadUnitNumber(String leadUnitNumber) {
this.leadUnitNumber = leadUnitNumber;
}
public String getPrincipalInvestigatorId() {
if (StringUtils.isBlank(principalInvestigatorId)) {
if (getPrincipalInvestigator() != null) {
ProtocolPersonBase principalInvestigator = getPrincipalInvestigator();
if (StringUtils.isNotBlank(principalInvestigator.getPersonId())) {
setPrincipalInvestigatorId(principalInvestigator.getPersonId());
} else {
if (principalInvestigator.getRolodexId() != null) {
setPrincipalInvestigatorId(principalInvestigator.getRolodexId().toString());
}
}
}
}
return principalInvestigatorId;
}
public void setPrincipalInvestigatorId(String principalInvestigatorId) {
this.principalInvestigatorId = principalInvestigatorId;
}
public boolean isNonEmployeeFlag() {
return this.nonEmployeeFlag;
}
public void setNonEmployeeFlag(boolean nonEmployeeFlag) {
this.nonEmployeeFlag = nonEmployeeFlag;
}
/**
* This method is to get protocol location service
* @return ProtocolLocationService
*/
protected ProtocolLocationService getProtocolLocationService() {
ProtocolLocationService protocolLocationService = (ProtocolLocationService) KcServiceLocator.getService("protocolLocationService");
return protocolLocationService;
}
public List<ProtocolPersonBase> getProtocolPersons() {
return protocolPersons;
}
public void setProtocolPersons(List<ProtocolPersonBase> protocolPersons) {
this.protocolPersons = protocolPersons;
for (ProtocolPersonBase person : protocolPersons) {
person.init(this);
}
}
/**
* Gets index i from the protocol person list.
*
* @param index
* @return protocol person at index i
*/
public ProtocolPersonBase getProtocolPerson(int index) {
return getProtocolPersons().get(index);
}
/**
* This method is a hook to get actual protocol personnel service impl corresponding to the protocol type
* @return protocolPersonnelService
*/
protected abstract ProtocolPersonnelService getProtocolPersonnelService();
public List<ProtocolFundingSourceBase> getProtocolFundingSources() {
return protocolFundingSources;
}
public void setProtocolFundingSources(List<ProtocolFundingSourceBase> protocolFundingSources) {
this.protocolFundingSources = protocolFundingSources;
for (ProtocolFundingSourceBase fundingSource : protocolFundingSources) {
fundingSource.init(this);
}
}
public String getResearchAreaCode() {
return researchAreaCode;
}
public void setResearchAreaCode(String researchAreaCode) {
this.researchAreaCode = researchAreaCode;
}
public String getFundingSource() {
return fundingSource;
}
public void setFundingSource(String fundingSource) {
this.fundingSource = fundingSource;
}
public String getPerformingOrganizationId() {
return performingOrganizationId;
}
public void setPerformingOrganizationId(String performingOrganizationId) {
this.performingOrganizationId = performingOrganizationId;
}
public String getLeadUnitName() {
if (StringUtils.isBlank(leadUnitName)) {
if (getLeadUnit() != null) {
setLeadUnitName(getLeadUnit().getUnitName());
}
}
return leadUnitName;
}
public void setLeadUnitName(String leadUnitName) {
this.leadUnitName = leadUnitName;
}
public void setSpecialReviews(List<ProtocolSpecialReviewBase> specialReviews) {
this.specialReviews = specialReviews;
}
public void addSpecialReview(ProtocolSpecialReviewBase specialReview) {
specialReview.setSequenceOwner(this);
getSpecialReviews().add(specialReview);
}
public ProtocolSpecialReviewBase getSpecialReview(int index) {
return getSpecialReviews().get(index);
}
public List<ProtocolSpecialReviewBase> getSpecialReviews() {
return specialReviews;
}
/**
* Gets the attachment protocols. Cannot return {@code null}.
* @return the attachment protocols
*/
public List<ProtocolAttachmentProtocolBase> getAttachmentProtocols() {
if (this.attachmentProtocols == null) {
this.attachmentProtocols = new ArrayList<ProtocolAttachmentProtocolBase>();
}
return this.attachmentProtocols;
}
/**
* Gets an attachment protocol.
* @param index the index
* @return an attachment protocol
*/
public ProtocolAttachmentProtocolBase getAttachmentProtocol(int index) {
return this.attachmentProtocols.get(index);
}
/**
* Gets the notepads. Cannot return {@code null}.
* @return the notepads
*/
public List<ProtocolNotepadBase> getNotepads() {
if (this.notepads == null) {
this.notepads = new ArrayList<ProtocolNotepadBase>();
}
Collections.sort(notepads, Collections.reverseOrder());
return this.notepads;
}
/**
* Gets an attachment protocol.
* @param index the index
* @return an attachment protocol
*/
public ProtocolNotepadBase getNotepad(int index) {
return this.notepads.get(index);
}
/**
* adds an attachment protocol.
* @param attachmentProtocol the attachment protocol
* @throws IllegalArgumentException if attachmentProtocol is null
*/
private void addAttachmentProtocol(ProtocolAttachmentProtocolBase attachmentProtocol) {
ProtocolAttachmentBase.addAttachmentToCollection(attachmentProtocol, this.getAttachmentProtocols());
}
/**
* removes an attachment protocol.
* @param attachmentProtocol the attachment protocol
* @throws IllegalArgumentException if attachmentProtocol is null
*/
private void removeAttachmentProtocol(ProtocolAttachmentProtocolBase attachmentProtocol) {
ProtocolAttachmentBase.removeAttachmentFromCollection(attachmentProtocol, this.getAttachmentProtocols());
}
/**
* @deprecated
* Gets the attachment personnels. Cannot return {@code null}.
* @return the attachment personnels
*/
@Deprecated
public List<ProtocolAttachmentPersonnelBase> getAttachmentPersonnels() {
return getProtocolAttachmentPersonnel();
}
private void updateUserFields(KcPersistableBusinessObjectBase bo) {
bo.setUpdateUser(GlobalVariables.getUserSession().getPrincipalName());
bo.setUpdateTimestamp(getDateTimeService().getCurrentTimestamp());
}
/**
* Adds a attachment to a ProtocolBase where the type of attachment is used to determine
* where to add the attachment.
* @param attachment the attachment
* @throws IllegalArgumentException if attachment is null or if an unsupported attachment is found
*/
public <T extends ProtocolAttachmentBase> void addAttachmentsByType(T attachment) {
if (attachment == null) {
throw new IllegalArgumentException("the attachment is null");
}
updateUserFields(attachment);
attachment.setProtocolId(getProtocolId());
if (attachment instanceof ProtocolAttachmentProtocolBase) {
this.addAttachmentProtocol((ProtocolAttachmentProtocolBase) attachment);
} else {
throw new IllegalArgumentException("unsupported type: " + attachment.getClass().getName());
}
}
/**
* removes an attachment to a ProtocolBase where the type of attachment is used to determine
* where to add the attachment.
* @param attachment the attachment
* @throws IllegalArgumentException if attachment is null or if an unsupported attachment is found
*/
public <T extends ProtocolAttachmentBase> void removeAttachmentsByType(T attachment) {
if (attachment == null) {
throw new IllegalArgumentException("the attachment is null");
}
if (attachment instanceof ProtocolAttachmentProtocolBase) {
this.removeAttachmentProtocol((ProtocolAttachmentProtocolBase) attachment);
} else {
throw new IllegalArgumentException("unsupported type: " + attachment.getClass().getName());
}
}
public String getKeyPerson() {
return keyPerson;
}
public void setKeyPerson(String keyPerson) {
this.keyPerson = keyPerson;
}
public String getInvestigator() {
if (StringUtils.isBlank(principalInvestigatorId)) {
if (getPrincipalInvestigator() != null) {
investigator = getPrincipalInvestigator().getPersonName();
}
}
return investigator;
}
public void setInvestigator(String investigator) {
this.investigator = investigator;
}
public ProtocolSubmissionBase getProtocolSubmission() {
if (!protocolSubmissions.isEmpty()) {
// sorted by ojb
if (protocolSubmission == null
|| protocolSubmission.getSubmissionNumber() == null
|| protocolSubmissions.get(protocolSubmissions.size() - 1).getSubmissionNumber() > protocolSubmission
.getSubmissionNumber()) {
protocolSubmission = protocolSubmissions.get(protocolSubmissions.size() - 1);
}
}
else {
protocolSubmission = getProtocolSubmissionNewInstanceHook();
// TODO : the update protocol rule may not like null
protocolSubmission.setProtocolSubmissionType(getProtocolSubmissionTypeNewInstanceHook());
protocolSubmission.setSubmissionStatus(getProtocolSubmissionStatusNewInstanceHook());
}
// }
refreshReferenceObject(protocolSubmission);
return protocolSubmission;
}
protected abstract ProtocolSubmissionStatusBase getProtocolSubmissionStatusNewInstanceHook();
protected abstract ProtocolSubmissionTypeBase getProtocolSubmissionTypeNewInstanceHook();
protected abstract ProtocolSubmissionBase getProtocolSubmissionNewInstanceHook();
private void refreshReferenceObject(ProtocolSubmissionBase submission) {
// if submission just added, then these probably are empty
if (StringUtils.isNotBlank(submission.getProtocolReviewTypeCode())
&& submission.getProtocolReviewType() == null) {
submission.refreshReferenceObject("protocolReviewType");
}
if (StringUtils.isNotBlank(submission.getSubmissionStatusCode())
&& submission.getSubmissionStatus() == null) {
submission.refreshReferenceObject("submissionStatus");
}
if (StringUtils.isNotBlank(submission.getSubmissionTypeCode())
&& submission.getProtocolSubmissionType() == null) {
submission.refreshReferenceObject("protocolSubmissionType");
}
if (StringUtils.isNotBlank(submission.getSubmissionTypeQualifierCode())
&& submission.getProtocolSubmissionQualifierType() == null) {
submission.refreshReferenceObject("protocolSubmissionQualifierType");
}
}
public void setProtocolSubmission(ProtocolSubmissionBase protocolSubmission) {
this.protocolSubmission = protocolSubmission;
}
public void setProtocolActions(List<ProtocolActionBase> protocolActions) {
this.protocolActions = protocolActions;
}
public List<ProtocolActionBase> getProtocolActions() {
return protocolActions;
}
public ProtocolActionBase getLastProtocolAction() {
if (protocolActions.size() == 0) {
return null;
}
Collections.sort(protocolActions, new Comparator<ProtocolActionBase>() {
public int compare(ProtocolActionBase action1, ProtocolActionBase action2) {
return action2.getActualActionDate().compareTo(action1.getActualActionDate());
}
});
return protocolActions.get(0);
}
public boolean containsAction(String action) {
boolean result = false;
for (ProtocolActionBase protocolActionBase: getProtocolActions()) {
if (protocolActionBase.getProtocolActionTypeCode().equals(action)) {
result = true;
break;
}
}
return result;
}
public void setProtocolSubmissions(List<ProtocolSubmissionBase> protocolSubmissions) {
this.protocolSubmissions = protocolSubmissions;
}
public List<ProtocolSubmissionBase> getProtocolSubmissions() {
return protocolSubmissions;
}
/**
* Get the next value in a sequence.
* @param key the unique key of the sequence
* @return the next value
*/
public Integer getNextValue(String key) {
return protocolDocument.getDocumentNextValue(key);
}
public void setAttachmentProtocols(List<ProtocolAttachmentProtocolBase> attachmentProtocols) {
this.attachmentProtocols = attachmentProtocols;
for (ProtocolAttachmentProtocolBase attachment : attachmentProtocols) {
attachment.resetPersistenceState();
attachment.setSequenceNumber(0);
}
}
public void setNotepads(List<ProtocolNotepadBase> notepads) {
this.notepads = notepads;
}
public void setProtocolAmendRenewal(ProtocolAmendRenewalBase amendRenewal) {
protocolAmendRenewals.add(amendRenewal);
}
public ProtocolAmendRenewalBase getProtocolAmendRenewal() {
if (protocolAmendRenewals.size() == 0) return null;
return protocolAmendRenewals.get(0);
}
public List<ProtocolAmendRenewalBase> getProtocolAmendRenewals() {
return protocolAmendRenewals;
}
public void setProtocolAmendRenewals(List<ProtocolAmendRenewalBase> protocolAmendRenewals) {
this.protocolAmendRenewals = protocolAmendRenewals;
}
@Override
public Integer getOwnerSequenceNumber() {
return null;
}
@Override
public String getVersionNameField() {
return "protocolNumber";
}
@Override
public void incrementSequenceNumber() {
this.sequenceNumber++;
}
@Override
public ProtocolBase getSequenceOwner() {
return this;
}
@Override
public void setSequenceOwner(ProtocolBase newOwner) {
//no-op
}
@Override
public void resetPersistenceState() {
this.protocolId = null;
}
/**
*
* This method merges the data of the amended protocol into this protocol.
* @param amendment
*/
public void merge(ProtocolBase amendment) {
merge(amendment, true);
}
// this method was modified during IRB backfit merge with the assumption that these changes are applicable to both IRB and IACUC
public void merge(ProtocolBase amendment, boolean mergeActions) {
// set this value here, since it is applicable regardless of which modules are amended
this.lastApprovalDate = amendment.getLastApprovalDate();
List<ProtocolAmendRenewModuleBase> modules = amendment.getProtocolAmendRenewal().getModules();
removeMergeableLists(modules); // remove lists from copy of original protocol
getBusinessObjectService().save(this); // force OJB to persist removal of lists
for (ProtocolAmendRenewModuleBase module : modules) {
merge(amendment, module.getProtocolModuleTypeCode());
}
if (amendment.isRenewalWithoutAmendment() && isRenewalWithNewAttachment(amendment)) {
merge(amendment, getProtocolModuleAddModifyAttachmentCodeHook());
}
if (mergeActions) {
mergeProtocolSubmission(amendment);
mergeProtocolAction(amendment);
}
// if renewal, then set the expiration date to be the new one provided during renewal approval
if(isExpirationDateToBeUpdated(amendment)) {
this.setExpirationDate(amendment.getExpirationDate());
}
}
protected abstract String getProtocolModuleAddModifyAttachmentCodeHook();
// this method can be overridden to customize the conditions when the expiration date is to be updated for the main protocol
protected boolean isExpirationDateToBeUpdated(ProtocolBase protocol) {
return protocol.isRenewal();
}
private boolean isRenewalWithNewAttachment(ProtocolBase renewal) {
boolean hasNewAttachment = false;
for (ProtocolAttachmentProtocolBase attachment : renewal.getAttachmentProtocols()) {
if (attachment.isDraft()) {
hasNewAttachment = true;
break;
}
}
return hasNewAttachment;
}
public abstract void merge(ProtocolBase amendment, String protocolModuleTypeCode);
protected abstract void removeMergeableLists(List<ProtocolAmendRenewModuleBase> modules);
protected void mergeProtocolQuestionnaire(ProtocolBase amendment) {
// TODO : what if user did not edit questionnaire at all, then questionnaire will be wiped out ?
removeOldQuestionnaire();
amendQuestionnaire(amendment);
}
/*
* remove existing questionnaire from current
*/
protected void removeOldQuestionnaire() {
List <AnswerHeader> answerHeaders = getAnswerHeaderForProtocol(this);
if (!answerHeaders.isEmpty() && answerHeaders.get(0).getId() != null){
getBusinessObjectService().delete(answerHeaders);
}
}
/*
* add questionnaire answer from amendment to protocol
*/
protected void amendQuestionnaire(ProtocolBase amendment) {
List <AnswerHeader> answerHeaders = getAnswerHeaderForProtocol(amendment);
if (!answerHeaders.isEmpty()){
for (AnswerHeader answerHeader : answerHeaders) {
for (Answer answer : answerHeader.getAnswers()) {
answer.setAnswerHeaderId(null);
answer.setId(null);
}
answerHeader.setId(null);
answerHeader.setModuleItemKey(this.getProtocolNumber());
answerHeader.setModuleSubItemKey(this.getSequenceNumber().toString());
}
getBusinessObjectService().save(answerHeaders);
}
}
/*
* get submit for review questionnaire answerheaders
*/
public abstract List <AnswerHeader> getAnswerHeaderForProtocol(ProtocolBase protocol);
protected QuestionnaireAnswerService getQuestionnaireAnswerService() {
return KcServiceLocator.getService(QuestionnaireAnswerService.class);
}
protected BusinessObjectService getBusinessObjectService() {
return KcServiceLocator.getService(BusinessObjectService.class);
}
@SuppressWarnings("unchecked")
protected void mergeProtocolSubmission(ProtocolBase amendment) {
List<ProtocolSubmissionBase> submissions = (List<ProtocolSubmissionBase>) deepCopy(amendment.getProtocolSubmissions());
for (ProtocolSubmissionBase submission : submissions) {
submission.setProtocolNumber(this.getProtocolNumber());
submission.setSubmissionId(null);
submission.setSequenceNumber(sequenceNumber);
submission.setProtocolId(this.getProtocolId());
this.getProtocolSubmissions().add(submission);
}
}
protected abstract void mergeProtocolAction(ProtocolBase amendment);
protected void mergeGeneralInfo(ProtocolBase amendment) {
this.protocolTypeCode = amendment.getProtocolTypeCode();
this.title = amendment.getTitle();
this.initialSubmissionDate = amendment.getInitialSubmissionDate();
this.approvalDate = amendment.getApprovalDate();
this.expirationDate = amendment.getExpirationDate();
this.description = amendment.getDescription();
this.fdaApplicationNumber = amendment.getFdaApplicationNumber();
this.referenceNumber1 = amendment.getReferenceNumber1();
this.referenceNumber2 = amendment.getReferenceNumber2();
}
@SuppressWarnings("unchecked")
protected void mergeResearchAreas(ProtocolBase amendment) {
setProtocolResearchAreas((List<ProtocolResearchAreaBase>) deepCopy(amendment.getProtocolResearchAreas()));
}
@SuppressWarnings("unchecked")
protected void mergeFundingSources(ProtocolBase amendment) {
setProtocolFundingSources((List<ProtocolFundingSourceBase>) deepCopy(amendment.getProtocolFundingSources()));
}
@SuppressWarnings("unchecked")
protected void mergeReferences(ProtocolBase amendment) {
setProtocolReferences((List<ProtocolReferenceBase>) deepCopy(amendment.getProtocolReferences()));
this.fdaApplicationNumber = amendment.getFdaApplicationNumber();
this.referenceNumber1 = amendment.getReferenceNumber1();
this.referenceNumber2 = amendment.getReferenceNumber2();
this.description = amendment.getDescription();
}
@SuppressWarnings("unchecked")
protected void mergeOrganizations(ProtocolBase amendment) {
setProtocolLocations((List<ProtocolLocationBase>) deepCopy(amendment.getProtocolLocations()));
}
@SuppressWarnings("unchecked")
protected void mergeAttachments(ProtocolBase amendment) {
// TODO : may need to set protocolnumber
// personnel attachment may have protocol person id issue
// how about sequence number ?
// need to change documentstatus to 2 if it is 1
// what the new protocol's protocol_status should be ?
List<ProtocolAttachmentProtocolBase> attachmentProtocols = new ArrayList<ProtocolAttachmentProtocolBase>();
for (ProtocolAttachmentProtocolBase attachment : (List<ProtocolAttachmentProtocolBase>) deepCopy(amendment.getAttachmentProtocols())) {
attachment.setProtocolNumber(this.getProtocolNumber());
attachment.setSequenceNumber(this.getSequenceNumber());
attachment.setProtocolId(this.getProtocolId());
attachment.setId(null);
if (attachment.getFile() != null ) {
attachment.getFile().setId(null);
}
if (attachment.isDraft()) {
attachment.setDocumentStatusCode(ProtocolAttachmentStatusBase.FINALIZED);
attachmentProtocols.add(attachment);
attachment.setProtocol(this);
}
if (attachment.isDeleted() && KcServiceLocator.getService(ProtocolAttachmentService.class).isNewAttachmentVersion((ProtocolAttachmentProtocolBase) attachment)) {
attachmentProtocols.add(attachment);
attachment.setProtocol(this);
}
}
getAttachmentProtocols().addAll(attachmentProtocols);
removeDeletedAttachment();
mergeNotepads(amendment);
}
/*
* the deleted attachment will not be merged
*/
private void removeDeletedAttachment() {
List<Integer> documentIds = new ArrayList<Integer>();
List<ProtocolAttachmentProtocolBase> attachments = new ArrayList<ProtocolAttachmentProtocolBase>();
for (ProtocolAttachmentProtocolBase attachment : this.getAttachmentProtocols()) {
attachment.setProtocol(this);
if (attachment.isDeleted()) {
documentIds.add(attachment.getDocumentId());
}
}
if (!documentIds.isEmpty()) {
for (ProtocolAttachmentProtocolBase attachment : this.getAttachmentProtocols()) {
attachment.setProtocol(this);
if (!documentIds.contains(attachment.getDocumentId())) {
attachments.add(attachment);
}
}
this.setAttachmentProtocols(new ArrayList<ProtocolAttachmentProtocolBase>());
this.getAttachmentProtocols().addAll(attachments);
}
}
/*
* This is to restore attachments from protocol to amendment when 'attachment' section is unselected.
* The attachment in amendment may have been modified.
* delete 'attachment' need to be careful.
* - if the 'file' is also used in other 'finalized' attachment, then should remove this file reference from attachment
* otherwise, the delete will also delete any attachment that reference to this file
*/
protected void restoreAttachments(ProtocolBase protocol) {
List<ProtocolAttachmentProtocolBase> attachmentProtocols = new ArrayList<ProtocolAttachmentProtocolBase>();
List<ProtocolAttachmentProtocolBase> deleteAttachments = new ArrayList<ProtocolAttachmentProtocolBase>();
List<AttachmentFile> deleteFiles = new ArrayList<AttachmentFile>();
for (ProtocolAttachmentProtocolBase attachment : this.getAttachmentProtocols()) {
if (attachment.isFinal()) {
attachmentProtocols.add(attachment);
// } else if (attachment.isDraft()) {
} else {
// in amendment, DRAFT & DELETED must be new attachment because DELETED
// will not be copied from original protocol
deleteAttachments.add(attachment);
if (!fileIsReferencedByOther(attachment.getFileId())) {
deleteFiles.add(attachment.getFile());
}
attachment.setFileId(null);
}
}
if (!deleteAttachments.isEmpty()) {
getBusinessObjectService().save(deleteAttachments);
if (!deleteFiles.isEmpty()) {
getBusinessObjectService().delete(deleteFiles);
}
getBusinessObjectService().delete(deleteAttachments);
}
this.getAttachmentProtocols().clear();
this.getAttachmentProtocols().addAll(attachmentProtocols);
mergeNotepads(protocol);
}
private boolean fileIsReferencedByOther(Long fileId) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put("fileId", fileId.toString());
return getBusinessObjectService().countMatching(getProtocolAttachmentProtocolClassHook(), fieldValues) > 1;
}
protected abstract Class<? extends ProtocolAttachmentProtocolBase> getProtocolAttachmentProtocolClassHook();
protected void mergeNotepads(ProtocolBase amendment) {
List <ProtocolNotepadBase> notepads = new ArrayList<ProtocolNotepadBase>();
if (amendment.getNotepads() != null) {
for (ProtocolNotepadBase notepad : (List<ProtocolNotepadBase>) deepCopy(amendment.getNotepads())) {
notepad.setProtocolNumber(this.getProtocolNumber());
notepad.setSequenceNumber(this.getSequenceNumber());
notepad.setProtocolId(this.getProtocolId());
notepad.setId(null);
notepad.setProtocol(this);
notepads.add(notepad);
}
}
this.setNotepads(notepads);
}
@SuppressWarnings("unchecked")
protected void mergeSpecialReview(ProtocolBase amendment) {
setSpecialReviews((List<ProtocolSpecialReviewBase>) deepCopy(amendment.getSpecialReviews()));
cleanupSpecialReviews(amendment);
}
@SuppressWarnings("unchecked")
protected void mergePersonnel(ProtocolBase amendment) {
setProtocolPersons((List<ProtocolPersonBase>) deepCopy(amendment.getProtocolPersons()));
for (ProtocolPersonBase person : protocolPersons) {
Integer nextPersonId = getSequenceAccessorService().getNextAvailableSequenceNumber("SEQ_PROTOCOL_ID", person.getClass()).intValue();
person.setProtocolPersonId(nextPersonId);
for (ProtocolAttachmentPersonnelBase protocolAttachmentPersonnel : person.getAttachmentPersonnels()) {
protocolAttachmentPersonnel.setId(null);
protocolAttachmentPersonnel.setPersonId(person.getProtocolPersonId());
protocolAttachmentPersonnel.setProtocolId(getProtocolId());
protocolAttachmentPersonnel.setProtocolNumber(getProtocolNumber());
}
}
}
protected void mergeOthers(ProtocolBase amendment) {
if (protocolDocument.getCustomAttributeDocuments() == null ||
protocolDocument.getCustomAttributeDocuments().isEmpty()) {
protocolDocument.initialize();
}
if (amendment.getProtocolDocument().getCustomAttributeDocuments() == null ||
amendment.getProtocolDocument().getCustomAttributeDocuments().isEmpty()) {
amendment.getProtocolDocument().initialize();
}
for (Entry<String, CustomAttributeDocument> entry : protocolDocument.getCustomAttributeDocuments().entrySet()) {
CustomAttributeDocument cad = amendment.getProtocolDocument().getCustomAttributeDocuments().get(entry.getKey());
entry.getValue().getCustomAttribute().setValue(cad.getCustomAttribute().getValue());
}
}
protected void mergeProtocolPermissions(ProtocolBase amendment) {
// ToDo: merge permissions
}
protected Object deepCopy(Object obj) {
return ObjectUtils.deepCopy((Serializable) obj);
}
public abstract ProtocolSummary getProtocolSummary();
protected void addAdditionalInfoSummary(ProtocolSummary protocolSummary) {
AdditionalInfoSummary additionalInfoSummary = new AdditionalInfoSummary();
additionalInfoSummary.setFdaApplicationNumber(this.getFdaApplicationNumber());
additionalInfoSummary.setReferenceId1(this.getReferenceNumber1());
additionalInfoSummary.setReferenceId2(this.getReferenceNumber2());
additionalInfoSummary.setDescription(getDescription());
protocolSummary.setAdditionalInfo(additionalInfoSummary);
}
protected void addSpecialReviewSummaries(ProtocolSummary protocolSummary) {
for (ProtocolSpecialReviewBase specialReview : getSpecialReviews()) {
SpecialReviewSummary specialReviewSummary = new SpecialReviewSummary();
if (specialReview.getSpecialReviewType() == null) {
specialReview.refreshReferenceObject("specialReviewType");
}
specialReviewSummary.setType(specialReview.getSpecialReviewType().getDescription());
if (specialReview.getApprovalType() == null) {
specialReview.refreshReferenceObject("approvalType");
}
specialReviewSummary.setApprovalStatus(specialReview.getApprovalType().getDescription());
specialReviewSummary.setProtocolNumber(specialReview.getProtocolNumber());
specialReviewSummary.setApplicationDate(specialReview.getApplicationDate());
specialReviewSummary.setApprovalDate(specialReview.getApprovalDate());
specialReviewSummary.setExpirationDate(specialReview.getExpirationDate());
if (specialReview.getSpecialReviewExemptions() == null) {
specialReview.refreshReferenceObject("specialReviewExemptions");
}
specialReviewSummary.setExemptionNumbers(specialReview.getSpecialReviewExemptions());
specialReviewSummary.setComment(specialReview.getComments());
protocolSummary.add(specialReviewSummary);
}
}
protected void addOrganizationSummaries(ProtocolSummary protocolSummary) {
for (ProtocolLocationBase organization : this.getProtocolLocations()) {
OrganizationSummary organizationSummary = new OrganizationSummary();
organizationSummary.setId(organization.getOrganizationId());
organizationSummary.setOrganizationId(organization.getOrganizationId());
organizationSummary.setName(organization.getOrganization().getOrganizationName());
organizationSummary.setType(organization.getProtocolOrganizationType().getDescription());
organizationSummary.setContactId(organization.getRolodexId());
organizationSummary.setContact(organization.getRolodex());
organizationSummary.setFwaNumber(organization.getOrganization().getHumanSubAssurance());
protocolSummary.add(organizationSummary);
}
}
protected void addFundingSourceSummaries(ProtocolSummary protocolSummary) {
for (ProtocolFundingSourceBase source : getProtocolFundingSources()) {
FundingSourceSummary fundingSourceSummary = new FundingSourceSummary();
fundingSourceSummary.setFundingSourceType(source.getFundingSourceType().getDescription());
fundingSourceSummary.setFundingSource(source.getFundingSourceNumber());
fundingSourceSummary.setFundingSourceNumber(source.getFundingSourceNumber());
fundingSourceSummary.setFundingSourceName(source.getFundingSourceName());
fundingSourceSummary.setFundingSourceTitle(source.getFundingSourceTitle());
protocolSummary.add(fundingSourceSummary);
}
}
protected void addAttachmentSummaries(ProtocolSummary protocolSummary) {
for (ProtocolAttachmentProtocolBase attachment : getActiveAttachmentProtocols()) {
if (!attachment.isDeleted()) {
AttachmentSummary attachmentSummary = new AttachmentSummary();
attachmentSummary.setAttachmentId(attachment.getId());
attachmentSummary.setFileType(attachment.getFile().getType());
attachmentSummary.setFileName(attachment.getFile().getName());
attachmentSummary.setAttachmentType("Protocol: " + attachment.getType().getDescription());
attachmentSummary.setDescription(attachment.getDescription());
attachmentSummary.setDataLength(attachment.getFile().getData() == null ? 0 : attachment.getFile().getData().length);
attachmentSummary.setUpdateTimestamp(attachment.getUpdateTimestamp());
attachmentSummary.setUpdateUser(attachment.getUpdateUser());
protocolSummary.add(attachmentSummary);
}
}
for (ProtocolPersonBase person : getProtocolPersons()) {
for (ProtocolAttachmentPersonnelBase attachment : person.getAttachmentPersonnels()) {
AttachmentSummary attachmentSummary = new AttachmentSummary();
attachmentSummary.setAttachmentId(attachment.getId());
attachmentSummary.setFileType(attachment.getFile().getType());
attachmentSummary.setFileName(attachment.getFile().getName());
attachmentSummary.setAttachmentType(person.getPersonName() + ": " + attachment.getType().getDescription());
attachmentSummary.setDescription(attachment.getDescription());
attachmentSummary.setDataLength(attachment.getFile().getData() == null ? 0 : attachment.getFile().getData().length);
attachmentSummary.setUpdateTimestamp(attachment.getUpdateTimestamp());
attachmentSummary.setUpdateUser(attachment.getUpdateUser());
protocolSummary.add(attachmentSummary);
}
}
}
protected void addResearchAreaSummaries(ProtocolSummary protocolSummary) {
for (ProtocolResearchAreaBase researchArea : getProtocolResearchAreas()) {
ResearchAreaSummary researchAreaSummary = new ResearchAreaSummary();
researchAreaSummary.setResearchAreaCode(researchArea.getResearchAreaCode());
researchAreaSummary.setDescription(researchArea.getResearchAreas().getDescription());
protocolSummary.add(researchAreaSummary);
}
}
protected void addPersonnelSummaries(ProtocolSummary protocolSummary) {
for (ProtocolPersonBase person : getProtocolPersons()) {
PersonnelSummary personnelSummary = new PersonnelSummary();
personnelSummary.setPersonId(person.getPersonId());
personnelSummary.setName(person.getPersonName());
personnelSummary.setRoleName(person.getProtocolPersonRole().getDescription());
if (person.getAffiliationTypeCode() == null) {
personnelSummary.setAffiliation("");
}
else {
if (person.getAffiliationType() == null) {
person.refreshReferenceObject("affiliationType");
}
personnelSummary.setAffiliation(person.getAffiliationType().getDescription());
}
for (ProtocolUnitBase unit : person.getProtocolUnits()) {
personnelSummary.addUnit(unit.getUnitNumber(), unit.getUnitName());
}
protocolSummary.add(personnelSummary);
}
}
protected abstract ProtocolSummary createProtocolSummary();
@Override
public abstract String getDocumentKey();
@Override
public String getDocumentNumberForPermission() {
return protocolNumber;
}
@Override
public abstract List<String> getRoleNames();
public void resetForeignKeys() {
for (ProtocolActionBase action : protocolActions) {
action.resetForeignKeys();
}
}
public void resetPersistenceStateForNotifications() {
for (ProtocolActionBase action : protocolActions) {
for (KcNotification notification: action.getProtocolNotifications()) {
notification.resetPersistenceState();
}
}
}
public abstract String getNamespace();
@Override
public String getDocumentUnitNumber() {
return getLeadUnitNumber();
}
@Override
public abstract String getDocumentRoleTypeCode();
public void populateAdditionalQualifiedRoleAttributes(Map<String, String> qualifiedRoleAttributes) {
return;
}
public boolean isNew() {
return !isAmendment() && !isRenewal();
}
public boolean isAmendment() {
return protocolNumber != null && protocolNumber.contains(AMENDMENT_LETTER);
}
public boolean isRenewal() {
return protocolNumber != null && protocolNumber.contains(RENEWAL_LETTER);
}
public boolean isRenewalWithAmendment() {
return isRenewal() && CollectionUtils.isNotEmpty(this.getProtocolAmendRenewal().getModules());
}
public boolean isRenewalWithoutAmendment() {
return isRenewal() && CollectionUtils.isEmpty(this.getProtocolAmendRenewal().getModules());
}
/**
*
* If the protocol document is an amendment or renewal the parent protocol number is being returned.
* (i.e. the protocol number of the protocol that is being amended or renewed).
*
* Null will be returned if the protocol is not an amendment or renewal.
*
* @return protocolNumber of the ProtocolBase that is being amended/renewed
*/
public String getAmendedProtocolNumber() {
if (isAmendment()) {
return StringUtils.substringBefore(getProtocolNumber(), AMENDMENT_LETTER.toString());
} else if (isRenewal()) {
return StringUtils.substringBefore(getProtocolNumber(), RENEWAL_LETTER.toString());
} else {
return null;
}
}
/**
* Decides whether or not the ProtocolBase is in a state where changes will require versioning. For example: has the protocol
* had a change in status and not been versioned yet?
* @return true if versioning required false if not.
*/
public boolean isVersioningRequired() {
// TODO : why need this. it's always true
return true;
}
/**
* This method will return the list of all active attachments for this protocol; an attachment A is active for a
* protocol if either A has a doc status code of 'draft' or
* if for all other attachments for that protocol having the same doc id as A's doc id, none have a version number
* greater than A's version number.
* is defined as the o
* @return
*/
public List<ProtocolAttachmentProtocolBase> getActiveAttachmentProtocols() {
List<ProtocolAttachmentProtocolBase> activeAttachments = new ArrayList<ProtocolAttachmentProtocolBase>();
for (ProtocolAttachmentProtocolBase attachment1 : getAttachmentProtocols()) {
if (attachment1.isDraft()) {
activeAttachments.add(attachment1);
} else if (attachment1.isFinal() || attachment1.isDeleted()) {
//else if (attachment1.isFinal())) {
boolean isActive = true;
for (ProtocolAttachmentProtocolBase attachment2 : getAttachmentProtocols()) {
if (attachment1.getDocumentId().equals(attachment2.getDocumentId())
&& attachment1.getAttachmentVersion() < attachment2.getAttachmentVersion()) {
isActive = false;
break;
}
}
if (isActive) {
activeAttachments.add(attachment1);
} else {
attachment1.setActive(isActive);
}
} else {
attachment1.setActive(false);
}
}
return activeAttachments;
}
/**
* This method will return the list of undeleted attachments that are still active for this protocol.
* Essentially it filters out all the deleted elements from the list of active attachments.
* See getActiveAttachmentProtocols() for a specification of what is an 'active attachment'.
*
*
* @return
*/
// TODO the method code below could be restructured to combine the two for loops into one loop.
public List<ProtocolAttachmentProtocolBase> getActiveAttachmentProtocolsNoDelete() {
List<Integer> documentIds = new ArrayList<Integer>();
List<ProtocolAttachmentProtocolBase> activeAttachments = new ArrayList<ProtocolAttachmentProtocolBase>();
for (ProtocolAttachmentProtocolBase attachment : getActiveAttachmentProtocols()) {
if (attachment.isDeleted()) {
documentIds.add(attachment.getDocumentId());
}
}
for (ProtocolAttachmentProtocolBase attachment : getActiveAttachmentProtocols()) {
if (documentIds.isEmpty() || !documentIds.contains(attachment.getDocumentId())) {
activeAttachments.add(attachment);
} else {
attachment.setActive(false);
}
}
return activeAttachments;
}
public boolean isCorrectionMode() {
return correctionMode;
}
public void setCorrectionMode(boolean correctionMode) {
this.correctionMode = correctionMode;
}
protected DateTimeService getDateTimeService() {
if(dateTimeService == null) {
dateTimeService = (DateTimeService) KcServiceLocator.getService(DateTimeService.class);
}
return dateTimeService;
}
protected SequenceAccessorService getSequenceAccessorService() {
if(sequenceAccessorService == null) {
sequenceAccessorService = (SequenceAccessorService) KcServiceLocator.getService(SequenceAccessorService.class);
}
return sequenceAccessorService;
}
public Long getNotifyIrbSubmissionId() {
return notifyIrbSubmissionId;
}
public void setNotifyIrbSubmissionId(Long notifyIrbSubmissionId) {
this.notifyIrbSubmissionId = notifyIrbSubmissionId;
}
public boolean isLookupPendingProtocol() {
return lookupPendingProtocol;
}
public void setLookupPendingProtocol(boolean lookupPendingProtocol) {
this.lookupPendingProtocol = lookupPendingProtocol;
}
public boolean isLookupPendingPIActionProtocol() {
return lookupPendingPIActionProtocol;
}
public void setLookupPendingPIActionProtocol(boolean lookupPendingPIActionProtocol) {
this.lookupPendingPIActionProtocol = lookupPendingPIActionProtocol;
}
public boolean isLookupActionAmendRenewProtocol() {
return lookupActionAmendRenewProtocol;
}
public void setLookupActionAmendRenewProtocol(boolean lookupActionAmendRenewProtocol) {
this.lookupActionAmendRenewProtocol = lookupActionAmendRenewProtocol;
}
public boolean isLookupActionRequestProtocol() {
return lookupActionRequestProtocol;
}
public void setLookupActionRequestProtocol(boolean lookupActionRequestProtocol) {
this.lookupActionRequestProtocol = lookupActionRequestProtocol;
}
public boolean isLookupProtocolPersonId() {
return lookupProtocolPersonId;
}
public void setLookupProtocolPersonId(boolean lookupProtocolPersonId) {
this.lookupProtocolPersonId = lookupProtocolPersonId;
}
/**
*
* This method is to check if the actiontypecode is a followup action.
* @param actionTypeCode
* @return
*/
public boolean isFollowupAction(String actionTypeCode) {
return (getLastProtocolAction() == null || StringUtils.isBlank(getLastProtocolAction().getFollowupActionCode())) ? false
: actionTypeCode.equals(getLastProtocolAction().getFollowupActionCode());
}
public boolean isMergeAmendment() {
return mergeAmendment;
}
public void setMergeAmendment(boolean mergeAmendment) {
this.mergeAmendment = mergeAmendment;
}
public ProtocolAttachmentFilterBase getProtocolAttachmentFilter() {
return protocolAttachmentFilter;
}
public void setProtocolAttachmentFilter(ProtocolAttachmentFilterBase protocolAttachmentFilter) {
this.protocolAttachmentFilter = protocolAttachmentFilter;
}
/**
*
* This method returns a list of attachments which respect the sort filter
* @return a filtered list of protocol attachments
*/
public List<ProtocolAttachmentProtocolBase> getFilteredAttachmentProtocols() {
List<ProtocolAttachmentProtocolBase> filteredAttachments = new ArrayList<ProtocolAttachmentProtocolBase>();
ProtocolAttachmentFilterBase attachmentFilter = getProtocolAttachmentFilter();
if (attachmentFilter != null && StringUtils.isNotBlank(attachmentFilter.getFilterBy())) {
for (ProtocolAttachmentProtocolBase attachment1 : getAttachmentProtocols()) {
if ((attachment1.getTypeCode()).equals(attachmentFilter.getFilterBy())) {
filteredAttachments.add(attachment1);
}
}
} else {
filteredAttachments = getAttachmentProtocols();
}
if (attachmentFilter != null && StringUtils.isNotBlank(attachmentFilter.getSortBy())) {
Collections.sort(filteredAttachments, attachmentFilter.getProtocolAttachmentComparator());
}
return filteredAttachments;
}
public abstract void initializeProtocolAttachmentFilter();
public ParameterService getParameterService() {
return KcServiceLocator.getService(ParameterService.class);
}
public void cleanupSpecialReviews(ProtocolBase srcProtocol) {
List<ProtocolSpecialReviewBase> srcSpecialReviews = srcProtocol.getSpecialReviews();
List<ProtocolSpecialReviewBase> dstSpecialReviews = getSpecialReviews();
for (int i=0; i < srcSpecialReviews.size(); i++) {
ProtocolSpecialReviewBase srcSpecialReview = srcSpecialReviews.get(i);
ProtocolSpecialReviewBase dstSpecialReview = dstSpecialReviews.get(i);
// copy exemption codes, since they are transient and ignored by deepCopy()
if (srcSpecialReview.getExemptionTypeCodes() != null) {
List<String> exemptionCodeCopy = new ArrayList<String>();
for (String s: srcSpecialReview.getExemptionTypeCodes()) {
exemptionCodeCopy.add(new String(s));
}
dstSpecialReview.setExemptionTypeCodes(exemptionCodeCopy);
}
// force new table entry
dstSpecialReview.resetPersistenceState();
}
}
/**
* This method encapsulates the logic to decide if a committee member appears in the list of protocol personnel.
* It will first try to match by personIds and if personIds are not available then it will try matching by rolodexIds.
* @param member
* @return
*/
public boolean isMemberInProtocolPersonnel(CommitteeMembershipBase member) {
boolean retValue = false;
for(ProtocolPersonBase protocolPerson: this.protocolPersons) {
if( StringUtils.isNotBlank(member.getPersonId()) && StringUtils.isNotBlank(protocolPerson.getPersonId()) ) {
if(member.getPersonId().equals(protocolPerson.getPersonId())){
retValue = true;
break;
}
}
else if( StringUtils.isBlank(member.getPersonId()) && StringUtils.isBlank(protocolPerson.getPersonId()) ) {
// in this case check rolodex id
if( (null != member.getRolodexId()) && (null != protocolPerson.getRolodexId()) ) {
if(member.getRolodexId().equals(protocolPerson.getRolodexId())) {
retValue = true;
break;
}
}
}
}
return retValue;
}
/**
* This method will filter out this protocol's personnel from the given list of committee memberships
* @param members
* @return the filtered list of members
*/
public List<CommitteeMembershipBase> filterOutProtocolPersonnel(List<CommitteeMembershipBase> members) {
List<CommitteeMembershipBase> filteredMemebers = new ArrayList<CommitteeMembershipBase>();
for (CommitteeMembershipBase member : members) {
if(!isMemberInProtocolPersonnel(member)) {
filteredMemebers.add(member);
}
}
return filteredMemebers;
}
/**
*
* This method is to return the first submission date as application date. see kccoi-36 comment
* @return
*/
public Date getApplicationDate() {
if (CollectionUtils.isNotEmpty(this.protocolSubmissions)) {
return this.protocolSubmissions.get(0).getSubmissionDate();
} else {
return null;
}
}
@Override
public String getProjectName() {
return getTitle();
}
@Override
public String getProjectId() {
return getProtocolNumber();
}
// This is for viewhistory/corespondence to search prev submission
public List<ProtocolActionBase> getSortedActions() {
if (sortedActions == null) {
sortedActions = new ArrayList<ProtocolActionBase>();
for (ProtocolActionBase action : getProtocolActions()) {
sortedActions.add((ProtocolActionBase) ObjectUtils.deepCopy(action));
}
Collections.sort(sortedActions, new Comparator<ProtocolActionBase>() {
public int compare(ProtocolActionBase action1, ProtocolActionBase action2) {
return action1.getActionId().compareTo(action2.getActionId());
}
});
}
return sortedActions;
}
public boolean isEmptyProtocolResearchAreas() {
return CollectionUtils.isEmpty(getProtocolResearchAreas());
}
/*
* determine if current user is named on the protocol.
*/
public boolean isUserNamedInProtocol(String principalName) {
boolean result = false;
for (ProtocolPersonBase protocolPerson: getProtocolPersons()) {
if (principalName.equals(protocolPerson.getUserName())) {
result = true;
}
}
return result;
}
public void reconcileActionsWithSubmissions() {
HashMap<Integer, ProtocolSubmissionBase> submissionNumberMap = new HashMap<Integer, ProtocolSubmissionBase>();
for(ProtocolSubmissionBase submission : getProtocolSubmissions()) {
submissionNumberMap.put(submission.getSubmissionNumber(), submission);
}
for(ProtocolActionBase action : getProtocolActions()) {
if(action.getSubmissionNumber() != null && !action.getSubmissionNumber().equals(0)) {
if(submissionNumberMap.get(action.getSubmissionNumber()) != null) {
action.setSubmissionIdFk(submissionNumberMap.get(action.getSubmissionNumber()).getSubmissionId());
}
}
}
}
}
| agpl-3.0 |
accesstest3/AndroidFunambol | externals/jme-sdk/common/test/src/com/funambol/storage/StringKeyValueStoreTest.java | 4692 | /*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2009 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.storage;
import com.funambol.util.Log;
import com.funambol.util.ConsoleAppender;
import java.util.Enumeration;
import junit.framework.*;
public abstract class StringKeyValueStoreTest extends TestCase {
private int storeId = 0;
public StringKeyValueStoreTest(String name) {
super(name);
Log.initLog(new ConsoleAppender(), Log.TRACE);
}
public abstract StringKeyValueStore createStore(String name);
private StringKeyValueStore createNewStore() {
return createStore("Test_" + storeId++);
}
public void setUp() {
}
public void tearDown() {
}
public void testPutGet() throws Exception {
StringKeyValueStore store = createNewStore();
store.put("key", "value");
String value = store.get("key");
assertTrue("value".equals(value));
}
public void testSaveLoad() throws Exception {
StringKeyValueStore store = createStore("Test_saveLoadTest");
store.put("key-0", "value-0");
store.put("key-1", "value-1");
store.save();
// Now create a new instance and load its items
StringKeyValueStore store2 = createStore("Test_saveLoadTest");
store2.load();
String value0 = store2.get("key-0");
String value1 = store2.get("key-1");
assertTrue("value-0".equals(value0));
assertTrue("value-1".equals(value1));
}
public void testKeys() throws Exception {
StringKeyValueStore store = createNewStore();
store.put("key-0", "value-0");
store.put("key-1", "value-1");
boolean value0 = false;
boolean value1 = false;
Enumeration keys = store.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
if ("key-0".equals(key)) {
value0 = true;
} else if ("key-1".equals(key)) {
value1 = true;
} else {
assertTrue(false);
}
}
assertTrue(value0 && value1);
}
public void testContains() throws Exception {
StringKeyValueStore store = createNewStore();
store.put("key-0", "value-0");
store.put("key-1", "value-1");
boolean value0 = false;
boolean value1 = false;
assertTrue(store.contains("key-0"));
assertTrue(store.contains("key-1"));
assertTrue(!store.contains("key"));
}
public void testRemove() throws Exception {
StringKeyValueStore store = createNewStore();
store.put("key-0", "value-0");
store.put("key-1", "value-1");
assertTrue(store.contains("key-0"));
assertTrue(store.contains("key-1"));
store.remove("key-0");
assertTrue(!store.contains("key-0"));
assertTrue(store.contains("key-1"));
}
}
| agpl-3.0 |
Muizers/Werewolves | server/src/codingpro/werewolves/server/ServerToClientMessageType.java | 703 | package codingpro.werewolves.server;
import java.util.HashMap;
import java.util.Map;
public enum ServerToClientMessageType {
UPDATE_PLAYER_LIST(0),
NO_SUCH_USERNAME_IN_GAME(1),
NO_SUCH_GAME(2),
GAME_STOPPED(3),
CARD_DEALT(4),
CHANGE_PHASE(5),
INVALID_USERNAME(6),
GAME_CODE_REMOVED(7);
private int id;
private ServerToClientMessageType(int id) {
this.id = id;
}
public int getID() {
return id;
}
private static Map<Integer, ServerToClientMessageType> BY_ID = new HashMap<>();
static {
for (ServerToClientMessageType type : values()) {
BY_ID.put(type.getID(), type);
}
}
public static ServerToClientMessageType getByID(int id) {
return BY_ID.get(id);
}
}
| agpl-3.0 |
Tesora/tesora-dve-pub | tesora-dve-core/src/main/java/com/tesora/dve/sql/schema/MultiMapLookup.java | 2165 | package com.tesora.dve.sql.schema;
/*
* #%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 java.util.ArrayList;
import java.util.Collection;
import com.tesora.dve.common.MultiMap;
import com.tesora.dve.sql.util.UnaryFunction;
public class MultiMapLookup<T extends Object> extends AbstractLookup<Collection<T>>{
public MultiMapLookup(boolean exactMatch, boolean isCaseSensitive, final UnaryFunction<Name[], T> mapBy) {
super(exactMatch, isCaseSensitive, new UnaryFunction<Name[], Collection<T>>() {
@Override
public Name[] evaluate(Collection<T> object) {
ArrayList<Name> out = new ArrayList<Name>();
for(T o : object) {
Name[] ns = mapBy.evaluate(o);
for(Name n : ns)
out.add(n);
}
return (Name[])out.toArray(new Name[0]);
}
});
}
protected MultiMap<Name, T> objects = new MultiMap<Name, T>();
protected MultiMap<Name, T> capObjects = new MultiMap<Name, T>();
@Override
protected void store(boolean cap, Name n, Collection<T> o) {
if (cap) {
capObjects.putAll(n, o);
} else {
objects.putAll(n, o);
}
}
@Override
protected Collection<T> get(boolean cap, Name n) {
if (cap) {
return capObjects.get(n);
} else {
return objects.get(n);
}
}
@Override
protected void allocateBacking(boolean cap, boolean append) {
if (cap) {
if(!append || capObjects == null) capObjects = new MultiMap<Name,T>();
} else {
if (!append || objects == null) objects = new MultiMap<Name,T>();
}
}
}
| agpl-3.0 |
dzc34/Asqatasun | rules/rules-rgaa3.2017/src/test/java/org/asqatasun/rules/rgaa32017/Rgaa32017Rule041402Test.java | 4471 | /*
* 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.rgaa32017;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.entity.audit.ProcessResult;
import org.asqatasun.rules.rgaa32017.test.Rgaa32017RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 4.14.2 of the referential RGAA 3.2017
*
* @author
*/
public class Rgaa32017Rule041402Test extends Rgaa32017RuleImplementationTestCase {
/**
* Default constructor
* @param testName
*/
public Rgaa32017Rule041402Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.rgaa32017.Rgaa32017Rule041402");
}
@Override
protected void setUpWebResourceMap() {
// addWebResource("Rgaa32017.Test.4.14.2-1Passed-01");
// addWebResource("Rgaa32017.Test.4.14.2-2Failed-01");
addWebResource("Rgaa32017.Test.4.14.2-3NMI-01");
// addWebResource("Rgaa32017.Test.4.14.2-4NA-01");
}
@Override
protected void setProcess() {
//----------------------------------------------------------------------
//------------------------------1Passed-01------------------------------
//----------------------------------------------------------------------
// checkResultIsPassed(processPageTest("Rgaa32017.Test.4.14.2-1Passed-01"), 1);
//----------------------------------------------------------------------
//------------------------------2Failed-01------------------------------
//----------------------------------------------------------------------
// ProcessResult processResult = processPageTest("Rgaa32017.Test.4.14.2-2Failed-01");
// checkResultIsFailed(processResult, 1, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.FAILED,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------3NMI-01---------------------------------
//----------------------------------------------------------------------
ProcessResult processResult = processPageTest("Rgaa32017.Test.4.14.2-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("Rgaa32017.Test.4.14.2-4NA-01"));
}
@Override
protected void setConsolidate() {
// The consolidate method can be removed when real implementation is done.
// The assertions are automatically tested regarding the file names by
// the abstract parent class
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa32017.Test.4.14.2-3NMI-01").getValue());
}
}
| agpl-3.0 |
opensourceBIM/bimql | BimQL/src/nl/wietmazairac/bimql/get/attribute/GetAttributeSubIfcSimpleProperty.java | 1617 | package nl.wietmazairac.bimql.get.attribute;
/******************************************************************************
* Copyright (C) 2009-2017 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.ArrayList;
public class GetAttributeSubIfcSimpleProperty {
// fields
private Object object;
private String string;
// constructors
public GetAttributeSubIfcSimpleProperty(Object object, String string) {
this.object = object;
this.string = string;
}
// methods
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public ArrayList<Object> getResult() {
ArrayList<Object> resultList = new ArrayList<Object>();
return resultList;
}
}
| agpl-3.0 |
opensourceBIM/bimql | BimQL/src/nl/wietmazairac/bimql/set/attribute/SetAttributeSubIfcHeatingValueMeasure.java | 2378 | package nl.wietmazairac.bimql.set.attribute;
/******************************************************************************
* Copyright (C) 2009-2017 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import org.bimserver.models.ifc2x3tc1.IfcHeatingValueMeasure;
public class SetAttributeSubIfcHeatingValueMeasure {
// fields
private Object object;
private String attributeName;
private String attributeNewValue;
// constructors
public SetAttributeSubIfcHeatingValueMeasure() {
}
public SetAttributeSubIfcHeatingValueMeasure(Object object, String attributeName, String attributeNewValue) {
this.object = object;
this.attributeName = attributeName;
this.attributeNewValue = attributeNewValue;
}
// methods
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeNewValue() {
return attributeNewValue;
}
public void setAttributeNewValue(String attributeNewValue) {
this.attributeNewValue = attributeNewValue;
}
public void setAttribute() {
if (attributeName.equals("WrappedValueAsString")) {
//1NoEList
((IfcHeatingValueMeasure) object).setWrappedValueAsString(attributeNewValue);
//1void
//1String
}
else if (attributeName.equals("WrappedValue")) {
//1NoEList
((IfcHeatingValueMeasure) object).setWrappedValue(Double.parseDouble(attributeNewValue));
//1void
//1double
}
}
}
| agpl-3.0 |
quikkian-ua-devops/will-financials | kfs-ld/src/main/java/org/kuali/kfs/module/ld/document/validation/impl/LaborExpenseTransfeAmountValidValidation.java | 4517 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ld.document.validation.impl;
import org.kuali.kfs.krad.util.GlobalVariables;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.businessobject.AccountingLine;
import org.kuali.kfs.sys.document.AccountingDocument;
import org.kuali.kfs.sys.document.validation.GenericValidation;
import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent;
import org.kuali.rice.core.api.util.type.KualiDecimal;
/**
* determine whether the amount in the account is not zero
*
* @param accountingDocument the given document
* @param accountingLine the given accounting line
* @return true determine whether the amount in the account is not zero; otherwise, false
*/
public class LaborExpenseTransfeAmountValidValidation extends GenericValidation {
private AccountingLine accountingLineForValidation;
private AccountingDocument accountingDocumentForValidation;
/**
* Validates that an accounting line whether the expired account in the target accounting line
* can be used.
* <strong>Expects an accounting line as the first a parameter</strong>
*
* @see org.kuali.kfs.validation.Validation#validate(java.lang.Object[])
*/
public boolean validate(AttributedDocumentEvent event) {
boolean result = true;
AccountingLine accountingLine = getAccountingLineForValidation();
AccountingDocument accountingDocumentForValidation = getAccountingDocumentForValidation();
// not allow the zero amount on the account lines.
if (!isAmountValid(accountingDocumentForValidation, accountingLine)) {
GlobalVariables.getMessageMap().putError(KFSPropertyConstants.AMOUNT, KFSKeyConstants.ERROR_ZERO_AMOUNT, "an accounting line");
return false;
}
return result;
}
/**
* determine whether the amount in the account is not zero.
*
* @param accountingDocument the given accounting line
* @return true if the amount is not zero; otherwise, false
*/
public boolean isAmountValid(AccountingDocument document, AccountingLine accountingLine) {
KualiDecimal amount = accountingLine.getAmount();
// Check for zero amount
if (amount.isZero()) {
GlobalVariables.getMessageMap().putError(KFSPropertyConstants.AMOUNT, KFSKeyConstants.ERROR_ZERO_AMOUNT, "an accounting line");
return false;
}
return true;
}
/**
* Gets the accountingLineForValidation attribute.
*
* @return Returns the accountingLineForValidation.
*/
public AccountingDocument getAccountingDocumentForValidation() {
return accountingDocumentForValidation;
}
/**
* Sets the accountingLineForValidation attribute value.
*
* @param accountingLineForValidation The accountingLineForValidation to set.
*/
public void setAccountingLineForValidation(AccountingDocument accountingDocumentForValidation) {
this.accountingDocumentForValidation = accountingDocumentForValidation;
}
/**
* Gets the accountingLineForValidation attribute.
*
* @return Returns the accountingLineForValidation.
*/
public AccountingLine getAccountingLineForValidation() {
return accountingLineForValidation;
}
/**
* Sets the accountingLineForValidation attribute value.
*
* @param accountingLineForValidation The accountingLineForValidation to set.
*/
public void setAccountingLineForValidation(AccountingLine accountingLineForValidation) {
this.accountingLineForValidation = accountingLineForValidation;
}
}
| agpl-3.0 |
exomiser/Exomiser | exomiser-data-phenotype/src/main/java/org/monarchinitiative/exomiser/data/phenotype/processors/readers/disease/DiseasePhenotypeReader.java | 3156 | /*
* The Exomiser - A tool to annotate and prioritize genomic variants
*
* Copyright (c) 2016-2020 Queen Mary University of London.
* Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research 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 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.monarchinitiative.exomiser.data.phenotype.processors.readers.disease;
import org.monarchinitiative.exomiser.data.phenotype.processors.Resource;
import org.monarchinitiative.exomiser.data.phenotype.processors.model.disease.DiseasePhenotype;
import org.monarchinitiative.exomiser.data.phenotype.processors.readers.ResourceReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Jules Jacobsen <j.jacobsen@qmul.ac.uk>
* @since 13.0.0
*/
public class DiseasePhenotypeReader implements ResourceReader<List<DiseasePhenotype>> {
private static final Logger logger = LoggerFactory.getLogger(DiseasePhenotypeReader.class);
private final Resource hpoPhenotypeAnnotationsResource;
public DiseasePhenotypeReader(Resource hpoPhenotypeAnnotationsResource) {
this.hpoPhenotypeAnnotationsResource = hpoPhenotypeAnnotationsResource;
}
@Override
public List<DiseasePhenotype> read() {
Map<String, Set<String>> disease2PhenotypeMap = new LinkedHashMap<>();
try (BufferedReader reader = hpoPhenotypeAnnotationsResource.newBufferedReader()) {
String line;
// skip header
line = reader.readLine();
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\\t");
String diseaseId = fields[0] + ":" + fields[1];
String hpId = fields[4];
if (disease2PhenotypeMap.containsKey(diseaseId)) {
disease2PhenotypeMap.get(diseaseId).add(hpId);
} else {
Set<String> hpIds = new LinkedHashSet<>();
hpIds.add(hpId);
disease2PhenotypeMap.put(diseaseId, hpIds);
}
}
} catch (IOException ex) {
logger.error("Error reading file: {}", hpoPhenotypeAnnotationsResource.getResourcePath(), ex);
}
return disease2PhenotypeMap.entrySet()
.stream()
.map(entry -> new DiseasePhenotype(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
}
| agpl-3.0 |
jzinedine/CMDBuild | cmdbuild/src/main/java/org/cmdbuild/servlets/json/serializers/ViewSerializer.java | 1049 | package org.cmdbuild.servlets.json.serializers;
import java.util.List;
import org.cmdbuild.model.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static org.cmdbuild.servlets.json.ComunicationConstants.*;
public class ViewSerializer {
public static JSONObject toClient(List<View> views) throws JSONException {
final JSONObject out = new JSONObject();
final JSONArray jsonViews = new JSONArray();
for (View view: views) {
jsonViews.put(toClient(view));
}
out.put(VIEWS, jsonViews);
return out;
}
public static JSONObject toClient(View view) throws JSONException {
final JSONObject jsonView = new JSONObject();
jsonView.put(DESCRIPTION, view.getDescription());
jsonView.put(FILTER, view.getFilter());
jsonView.put(ID, view.getId());
jsonView.put(NAME, view.getName());
jsonView.put(SOURCE_CLASS_NAME, view.getSourceClassName());
jsonView.put(SOURCE_FUNCTION, view.getSourceFunction());
jsonView.put(TYPE, view.getType().toString());
return jsonView;
}
}
| agpl-3.0 |
intellihouse/intellihouse | co.codewizards.raspi1/src/main/java/co/codewizards/raspi1/steca/Crc.java | 2148 | package co.codewizards.raspi1.steca;
import static java.util.Objects.*;
/**
* <a href="https://www.lammertbies.nl/forum/viewtopic.php?t=1773">Found here.</a>
* @author mn
*/
public class Crc {
private final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1
private int crc;
public Crc() {
reset();
}
/**
* Updates the CRC with the given byte-array.
* @param val the value. Must not be <code>null</code>.
*/
public void update(final byte[] val) {
requireNonNull(val, "val");
update(val, 0, val.length);
}
/**
* Updates the CRC with the given byte-array starting at the index {@code pos}
* and taking {@code length} bytes into account.
* @param val the value. Must not be <code>null</code>.
* @param pos the start-position-index.
* @param length the number of bytes to use from {@code val}.
*/
public void update(final byte[] val, final int pos, final int length) {
requireNonNull(val, "val");
for (int i = pos; i < pos + length; i++) {
update(val[i]);
}
}
/**
* Updates the CRC with the given byte {@code val}.
* @param val the (next) byte to update the CRC value.
*/
public void update(final byte val) {
for (int i = 0; i < 8; i++) {
boolean bit = ((val >> (7-i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
// If coefficient of bit and remainder polynomial = 1 xor crc with polynomial
if (c15 ^ bit) crc ^= polynomial;
}
}
/**
* Resets the CRC crc to 0.
*/
public void reset() {
crc = 0;
}
/**
* Gets the CRC16 crc.
* @return the CRC16 crc.
*/
public int getCrc() {
return crc;
}
public byte[] getCrcBytes() {
final int value = getCrc();
return new byte[] {
(byte) ((value >>> 8) & 0xff),
(byte) (value & 0xff)
};
}
// public static void main(String[] args) {
//// byte[] val = new byte[] { 'Q', 'P', 'I', 'G', 'S' };
// byte[] val = new byte[] { 'Q', 'M', 'O', 'D' };
// Crc crc = new Crc();
// crc.update(val, 0, val.length);
// byte[] crcBytes = crc.getCrcBytes();
// System.out.println(Integer.toHexString(crcBytes[0] & 0xff) + " " + Integer.toHexString(crcBytes[1] & 0xff));
// }
} | agpl-3.0 |
moskiteau/KalturaGeneratedAPIClientsJava | src/main/java/com/kaltura/client/types/KalturaConfigurableDistributionJobProviderData.java | 2824 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2015 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import org.w3c.dom.Element;
import com.kaltura.client.KalturaParams;
import com.kaltura.client.KalturaApiException;
import com.kaltura.client.utils.ParseUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public abstract class KalturaConfigurableDistributionJobProviderData extends KalturaDistributionJobProviderData {
public String fieldValues;
public KalturaConfigurableDistributionJobProviderData() {
}
public KalturaConfigurableDistributionJobProviderData(Element node) throws KalturaApiException {
super(node);
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node aNode = childNodes.item(i);
String nodeName = aNode.getNodeName();
String txt = aNode.getTextContent();
if (nodeName.equals("fieldValues")) {
this.fieldValues = ParseUtils.parseString(txt);
continue;
}
}
}
public KalturaParams toParams() throws KalturaApiException {
KalturaParams kparams = super.toParams();
kparams.add("objectType", "KalturaConfigurableDistributionJobProviderData");
kparams.add("fieldValues", this.fieldValues);
return kparams;
}
}
| agpl-3.0 |
jasolangi/jasolangi.github.io | modules/distribution/src/main/java/org/openlmis/distribution/domain/DistributionStatus.java | 1113 | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* 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. For additional information contact info@OpenLMIS.org.
*/
package org.openlmis.distribution.domain;
/**
* Enum for statuses of a distribution. These distribution statuses are used to get/set the current status of an
* initiated distribution.
*/
public enum DistributionStatus {
INITIATED,
COMPLETED,
SYNCED
}
| agpl-3.0 |
kuzavas/ephesoft | dcma-gwt/dcma-gwt-core/src/main/java/com/ephesoft/dcma/gwt/core/client/ui/ScreenMask.java | 3277 | /*********************************************************************************
* Ephesoft is a Intelligent Document Capture and Mailroom Automation program
* developed by Ephesoft, Inc. Copyright (C) 2010-2012 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.dcma.gwt.core.client.ui;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
public class ScreenMask extends DialogBox {
interface Binder extends UiBinder<Widget, ScreenMask> { }
private static final Binder BINDER = GWT.create(Binder.class);
@UiField
protected Label message;
public ScreenMask() {
super();
setWidget(BINDER.createAndBindUi(this));
setAnimationEnabled(true);
setGlassEnabled(true);
setWidth("100%");
}
public void setMessage(String messageText){
message.setText(messageText);
}
//
// @Override
// protected void onPreviewNativeEvent(NativePreviewEvent preview) {
// super.onPreviewNativeEvent(preview);
//
// NativeEvent evt = preview.getNativeEvent();
// if (evt.getType().equals("keydown")) {
// // Use the popup's key preview hooks to close the dialog when either
// // enter or escape is pressed.
// switch (evt.getKeyCode()) {
// case KeyCodes.KEY_ENTER:
// case KeyCodes.KEY_ESCAPE:
// hide();
// break;
// }
// }
// }
}
| agpl-3.0 |
servernge/holocore | src/network/packets/swg/zone/chat/ChatBanAvatarFromRoom.java | 2397 | /*******************************************************************************
* Copyright (c) 2015 /// Project SWG /// www.projectswg.com
*
* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on
* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies.
* Our goal is to create an emulator which will provide a server for players to
* continue playing a game similar to the one they used to play. We are basing
* it on the final publish of the game prior to end-game events.
*
* This file is part of Holocore.
*
* --------------------------------------------------------------------------------
*
* Holocore 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.
*
* Holocore 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 Holocore. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package network.packets.swg.zone.chat;
import network.packets.swg.SWGPacket;
import resources.chat.ChatAvatar;
import java.nio.ByteBuffer;
/**
* @author Waverunner
*/
public class ChatBanAvatarFromRoom extends SWGPacket {
public static final int CRC = getCrc("ChatBanAvatarFromRoom");
private ChatAvatar avatar;
private String room;
private int sequence;
public ChatBanAvatarFromRoom() {}
@Override
public void decode(ByteBuffer data) {
if (!super.decode(data, CRC))
return;
avatar = getEncodable(data, ChatAvatar.class);
room = getAscii(data);
sequence = getInt(data);
}
@Override
public ByteBuffer encode() {
ByteBuffer bb = ByteBuffer.allocate(12 + avatar.encode().length + room.length());
addShort(bb, 4);
addInt(bb, CRC);
addEncodable(bb, avatar);
addAscii(bb, room);
addInt(bb, sequence);
return bb;
}
public ChatAvatar getAvatar() {
return avatar;
}
public String getRoom() {
return room;
}
public int getSequence() {
return sequence;
}
}
| agpl-3.0 |
torakiki/sejda-itext5 | src/main/java/org/sejda/impl/itext5/SplitByOutlineLevelTask.java | 3029 | /*
* Created on 17/gen/2014
* Copyright 2014 by Andrea Vacondio (andrea.vacondio@gmail.com).
* This file is part of sejda-itext5.
*
* sejda-itext5 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.
*
* sejda-itext5 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 sejda-itext5. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sejda.impl.itext5;
import static org.sejda.impl.itext5.util.ITextUtils.nullSafeClosePdfReader;
import org.sejda.impl.itext5.component.DefaultPdfSourceOpener;
import org.sejda.impl.itext5.component.ITextOutlineLevelsHandler;
import org.sejda.impl.itext5.component.split.PageDestinationsLevelPdfSplitter;
import org.sejda.model.exception.TaskException;
import org.sejda.model.input.PdfSourceOpener;
import org.sejda.model.outline.OutlinePageDestinations;
import org.sejda.model.parameter.SplitByOutlineLevelParameters;
import org.sejda.model.task.BaseTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.text.pdf.PdfReader;
/**
* Task splitting an input pdf document on a set of pages given by an outline level defined in the input parameter.
*
* @author Andrea Vacondio
*
*/
public class SplitByOutlineLevelTask extends BaseTask<SplitByOutlineLevelParameters> {
private static final Logger LOG = LoggerFactory.getLogger(SplitByOutlineLevelTask.class);
private PdfReader reader = null;
private PdfSourceOpener<PdfReader> sourceOpener;
private PageDestinationsLevelPdfSplitter splitter;
public void before(SplitByOutlineLevelParameters parameters) {
sourceOpener = new DefaultPdfSourceOpener();
}
public void execute(SplitByOutlineLevelParameters parameters) throws TaskException {
LOG.debug("Opening {} ", parameters.getSource());
reader = parameters.getSource().open(sourceOpener);
LOG.debug("Retrieving outline information for level {}", parameters.getLevelToSplitAt());
OutlinePageDestinations goToPagesDestination = new ITextOutlineLevelsHandler(reader,
parameters.getMatchingTitleRegEx()).getPageDestinationsForLevel(parameters.getLevelToSplitAt());
splitter = new PageDestinationsLevelPdfSplitter(reader, parameters, goToPagesDestination);
LOG.debug("Starting split by GoTo Action level for {} ", parameters);
splitter.split(getNotifiableTaskMetadata());
LOG.debug("Input documents splitted and written to {}", parameters.getOutput());
}
public void after() {
nullSafeClosePdfReader(reader);
splitter = null;
}
}
| agpl-3.0 |
Tesora/tesora-dve-pub | tesora-dve-message-api/src/main/java/com/tesora/dve/comms/client/messages/ExecutePreparedStatementRequest.java | 1331 | package com.tesora.dve.comms.client.messages;
/*
* #%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 java.util.List;
public class ExecutePreparedStatementRequest extends StatementBasedRequest {
private static final long serialVersionUID = 1L;
private final List<String> values;
public ExecutePreparedStatementRequest(String stmtID, List<String> params) {
super(stmtID);
values = params;
}
@Override
public MessageType getMessageType() {
return MessageType.EXECUTE_PREPARED_REQUEST;
}
@Override
public MessageVersion getVersion() {
return MessageVersion.VERSION1;
}
public List<String> getValues() {
return values;
}
}
| agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-rgaa3.0/src/test/java/org/asqatasun/rules/rgaa30/Rgaa30Rule041102Test.java | 4422 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa30;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.entity.audit.ProcessResult;
import org.asqatasun.rules.rgaa30.test.Rgaa30RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 4.11.2 of the referential Rgaa 3.0.
*
* @author
*/
public class Rgaa30Rule041102Test extends Rgaa30RuleImplementationTestCase {
/**
* Default constructor
* @param testName
*/
public Rgaa30Rule041102Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.rgaa30.Rgaa30Rule041102");
}
@Override
protected void setUpWebResourceMap() {
// addWebResource("Rgaa30.Test.4.11.2-1Passed-01");
// addWebResource("Rgaa30.Test.4.11.2-2Failed-01");
addWebResource("Rgaa30.Test.4.11.2-3NMI-01");
// addWebResource("Rgaa30.Test.4.11.2-4NA-01");
}
@Override
protected void setProcess() {
//----------------------------------------------------------------------
//------------------------------1Passed-01------------------------------
//----------------------------------------------------------------------
// checkResultIsPassed(processPageTest("Rgaa30.Test.4.11.2-1Passed-01"), 1);
//----------------------------------------------------------------------
//------------------------------2Failed-01------------------------------
//----------------------------------------------------------------------
// ProcessResult processResult = processPageTest("Rgaa30.Test.4.11.2-2Failed-01");
// checkResultIsFailed(processResult, 1, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.FAILED,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------3NMI-01---------------------------------
//----------------------------------------------------------------------
ProcessResult processResult = processPageTest("Rgaa30.Test.4.11.2-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("Rgaa30.Test.4.11.2-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("Rgaa30.Test.4.11.2-3NMI-01").getValue());
}
}
| agpl-3.0 |
geomajas/geomajas-project-client-gwt2 | plugin/editing/common/src/main/java/org/geomajas/plugin/editing/client/BaseGeometryEditor.java | 1708 | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.plugin.editing.client;
import org.geomajas.annotation.Api;
import org.geomajas.plugin.editing.client.gfx.GeometryRenderer;
import org.geomajas.plugin.editing.client.service.GeometryEditService;
import org.geomajas.plugin.editing.client.snap.SnapService;
/**
* Base interface for geometry editors in all faces. TODO: check for redundant methods.
*
* @author Jan De Moerloose
* @since 2.0.0
*/
@Api(allMethods = true)
public interface BaseGeometryEditor {
/**
* Get the geometry editor service.
*
* @return the service
*/
GeometryEditService getEditService();
/**
* Is the editing session busy ?
*
* @return true if busy
*/
boolean isBusyEditing();
/**
* Get the snapping service for this editor.
*
* @return the service
*/
SnapService getSnappingService();
/**
* Get the renderer for the editor.
*
* @return the renderer
*/
GeometryRenderer getRenderer();
/**
* Is snapping on for dragging ?
*
* @return true if on
*/
boolean isSnapOnDrag();
/**
* Set whether to snap while in drag mode.
*
* @param true if snapping is on
*/
void setSnapOnDrag(boolean b);
/**
* Set whether to snap while in insert mode.
*
* @param true if snapping is on
*/
void setSnapOnInsert(boolean b);
} | agpl-3.0 |
GTAUN/wl-common | src/main/java/net/gtaun/wl/common/dialog/DialogUtils.java | 328 | package net.gtaun.wl.common.dialog;
import org.apache.commons.lang3.StringUtils;
public final class DialogUtils
{
public static String rightPad(String str, int size, int tabSize)
{
return str + StringUtils.repeat('\t', (size - str.length() + (tabSize-1)) / tabSize);
}
private DialogUtils()
{
}
}
| agpl-3.0 |
pligor/predicting-future-product-prices | SFA/src/MyClass.java | 2731 | import sfa.timeseries.TimeSeries;
import sfa.timeseries.TimeSeriesLoader;
import sfa.transformation.SFA;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static easyjcckit.QuickPlot.*;
/**
* Created by student on 24/7/2017.
*/
public class MyClass {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
try {
TimeSeries[] train = TimeSeriesLoader.loadDatset(new File("./datasets/CBF/CBF_TRAIN"));
//TimeSeries[] small = new TimeSeries[]{};
ArrayList<TimeSeries> small = new ArrayList<>();
int count = 0;
for(TimeSeries tt : train) {
//System.out.println(tt.getLength());
small.add(tt);
count += 1;
if(count > 10) {
break;
}
}
//TimeSeries[] small = (TimeSeries[]) (Arrays.stream(train).limit(10).toArray());
TimeSeries[] smalls = Arrays.copyOf(small.toArray(), small.size(), TimeSeries[].class);
System.out.println(train.length);
System.out.println(smalls.length);
//return;
sfait(train);
System.out.println();
sfait(smalls);
/*double[] data = train[1].getData();
*//*for(double dd : data) {
System.out.println(dd);
}*//*
//System.out.println(data.length);
//IntStream.range(0, 10);
double[] xaxis = IntStream.range(0, data.length).mapToDouble(n -> n).toArray();
//double[] yvalues = new double[]{0,1,4,9,16,25};
double[] yvalues = data;
plot( xaxis, yvalues ); // create a plot using xaxis and yvalues
*/
} catch (IOException e) {
e.printStackTrace();
}
// IntStream.range(0, 10).forEach(
// n -> {
// System.out.println(n);
// }
// );
//double[] yvalues = new double[]{0,1,2,3,4,5};
//addPlot( xaxis, yvalues ); // create a second plot on top of first
System.out.println("Press enter to exit");
//System.in.read();
}
public static void sfait(TimeSeries[] ts) {
SFA sfa = new SFA(SFA.HistogramType.EQUI_DEPTH);
short[][] wordsTrain = sfa.fitTransform(ts, 10, 4, false);
for(short[] word : wordsTrain) {
String str = java.util.Arrays.toString(word);
System.out.println(str);
}
}
}
| agpl-3.0 |
moinc/flow | project/src/main/java/nl/agiletech/flow/project/types/User.java | 771 | package nl.agiletech.flow.project.types;
import java.io.OutputStream;
import java.io.PrintWriter;
public class User extends Task {
public User(boolean repeatable) {
super(false);
}
@Override
public String getVersion() {
return null;
}
@Override
public void initialize(Context context) throws Exception {
}
@Override
public void inspect(Context context, Catalog catalog) throws Exception {
}
@Override
public void update(Context context, Catalog catalog) throws Exception {
}
@Override
public void resource(Context context, OutputStream outputStream) throws Exception {
}
@Override
public void report(Context context, PrintWriter printWriter) throws Exception {
}
@Override
public void terminate(Context context) throws Exception {
}
}
| agpl-3.0 |
hltn/opencps | portlets/opencps-portlet/docroot/WEB-INF/service/org/opencps/processmgt/service/ProcessOrderService.java | 2605 | /**
* 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.processmgt.service;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.jsonwebservice.JSONWebService;
import com.liferay.portal.kernel.transaction.Isolation;
import com.liferay.portal.kernel.transaction.Transactional;
import com.liferay.portal.security.ac.AccessControlled;
import com.liferay.portal.service.BaseService;
import com.liferay.portal.service.InvokableService;
/**
* Provides the remote service interface for ProcessOrder. Methods of this
* service are expected to have security checks based on the propagated JAAS
* credentials because this service can be accessed remotely.
*
* @author khoavd
* @see ProcessOrderServiceUtil
* @see org.opencps.processmgt.service.base.ProcessOrderServiceBaseImpl
* @see org.opencps.processmgt.service.impl.ProcessOrderServiceImpl
* @generated
*/
@AccessControlled
@JSONWebService
@Transactional(isolation = Isolation.PORTAL, rollbackFor = {
PortalException.class, SystemException.class})
public interface ProcessOrderService extends BaseService, InvokableService {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. Always use {@link ProcessOrderServiceUtil} to access the process order remote service. Add custom service methods to {@link org.opencps.processmgt.service.impl.ProcessOrderServiceImpl} and rerun ServiceBuilder to automatically copy the method declarations to this interface.
*/
/**
* Returns the Spring bean ID for this bean.
*
* @return the Spring bean ID for this bean
*/
public java.lang.String getBeanIdentifier();
/**
* Sets the Spring bean ID for this bean.
*
* @param beanIdentifier the Spring bean ID for this bean
*/
public void setBeanIdentifier(java.lang.String beanIdentifier);
@Override
public java.lang.Object invokeMethod(java.lang.String name,
java.lang.String[] parameterTypes, java.lang.Object[] arguments)
throws java.lang.Throwable;
} | agpl-3.0 |
automenta/narchy | ui/src/main/java/spacegraph/space3d/phys/math/MiscUtil.java | 5688 | /*
* Java port of Bullet (c) 2008 Martin Dvorak <jezek2@advel.cz>
*
* Bullet Continuous Collision Detection and Physics Library
* Copyright (c) 2003-2008 Erwin Coumans http:
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package spacegraph.space3d.phys.math;
import jcog.data.list.FasterList;
import jcog.util.ArrayUtils;
import spacegraph.space3d.phys.util.IntArrayList;
import spacegraph.space3d.phys.util.OArrayList;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Comparator;
import static java.util.Collections.swap;
/**
* Miscellaneous utility functions.
*
* @author jezek2
*/
public class MiscUtil {
public static int getListCapacityForHash(Collection<?> list) {
return getListCapacityForHash(list.size());
}
private static int getListCapacityForHash(int size) {
int n = 2;
while (n < size) {
n <<= 1;
}
return n;
}
/**
* Ensures valid index in provided list by filling list with provided values
* until the index is valid.
*/
public static <T> void ensureIndex(OArrayList<T> list, int index, T value) {
while (list.size() <= index) {
list.add(value);
}
}
/**
* Resizes list to exact size, filling with given value when expanding.
*/
public static void resize(IntArrayList list, int size, int value) {
int s = list.size();
while (s < size) {
list.add(value);
s++;
}
while (s > size) {
list.removeQuick(--s);
}
}
/**
* Resizes list to exact size, filling with new instances of given class type
* when expanding.
*/
public static <T> void resizeIntArray(OArrayList<int[]> list, int size, int arrayLen) {
int ls = list.size();
while (ls < size) {
list.add(new int[arrayLen]);
ls++;
}
while (ls > size) {
list.removeFast(--ls);
}
}
/**
* Resizes list to exact size, filling with new instances of given class type
* when expanding.
*/
public static <T> void resize(FasterList<T> list, int size, Class<T> valueCls) {
try {
int ls = list.size();
while (ls < size) {
list.add(valueCls != null? valueCls.getConstructor().newInstance() : null);
ls++;
}
while (ls > size) {
list.removeFast(--ls);
}
}
catch (IllegalAccessException | InstantiationException e) {
throw new IllegalStateException(e);
} catch (NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* Searches object in array.
*
* @return first index of match, or -1 when not found
*/
public static <T> int indexOf(T[] array, T obj) {
for (int i=0; i<array.length; i++) {
if (array[i] == obj) return i;
}
return -1;
}
private static <T> void downHeap(FasterList<T> pArr, int k, int n, Comparator<T> comparator) {
/* PRE: a[k+1..N] is a heap */
/* POST: a[k..N] is a heap */
T temp = pArr.get(k - 1);
/* k has child(s) */
while (k <= n / 2) {
int child = 2 * k;
if ((child < n) && comparator.compare(pArr.get(child - 1), pArr.get(child)) < 0) {
child++;
}
/* pick larger child */
if (comparator.compare(temp, pArr.get(child - 1)) < 0) {
/* move child up */
pArr.setFast(k - 1, pArr.get(child - 1));
k = child;
}
else {
break;
}
}
pArr.setFast(k - 1, temp);
}
/**
* Sorts list using quick sort.<p>
*/
public static <T> void quickSort(FasterList<T> list, Comparator<T> comparator) {
if (list.size() > 1) {
quickSortInternal(list, comparator, 0, list.size() - 1);
}
}
private static <T> void quickSortInternal(FasterList<T> list, Comparator<T> comparator, int lo, int hi) {
int i = lo, j = hi;
T x = list.get((lo + hi) / 2);
do {
while (comparator.compare(list.get(i), x) < 0) i++;
while (comparator.compare(x, list.get(j)) < 0) j--;
if (i <= j) {
swap(list, i, j);
i++;
j--;
}
}
while (i <= j);
if (lo < j) {
quickSortInternal(list, comparator, lo, j);
}
if (i < hi) {
quickSortInternal(list, comparator, i, hi);
}
}
public static void quickSort(int[][] list, int n) {
if (n > 1) {
quickSortInternal(list, 0, n - 1);
}
}
/** public int compare(int[] o1, int[] o2) { return o1[0] < o2[0] ? -1 : +1; } */
private static void quickSortInternal(int[][] list, int lo, int hi) {
int i = lo, j = hi;
int[] x = list[((lo + hi) / 2)];
do {
while (list[i][0]< x[0]) i++;
while (x[0] < list[j][0]) j--;
if (i <= j) {
ArrayUtils.swap(list, i, j);
i++;
j--;
}
}
while (i <= j);
if (lo < j) {
quickSortInternal(list, lo, j);
}
if (i < hi) {
quickSortInternal(list, i, hi);
}
}
}
| agpl-3.0 |
jzinedine/CMDBuild | cmdbuild/src/main/java/org/cmdbuild/servlets/json/schema/taskmanager/Utils.java | 1409 | package org.cmdbuild.servlets.json.schema.taskmanager;
import java.util.List;
import java.util.Map;
import org.cmdbuild.logger.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class Utils {
private static final Logger logger = Log.JSONRPC;
private static final Marker marker = MarkerFactory.getMarker(Utils.class.getName());
private Utils() {
// prevents instantiation
}
public static Map<String, String> toMap(final JSONObject json) {
try {
final Map<String, String> map = Maps.newHashMap();
if (json != null && json.length() > 0) {
for (final String key : JSONObject.getNames(json)) {
map.put(key, json.getString(key));
}
}
return map;
} catch (final Exception e) {
logger.warn(marker, "error parsing json data");
throw new RuntimeException(e);
}
}
public static Iterable<String> toIterable(final JSONArray json) {
try {
final List<String> values = Lists.newArrayList();
if (json != null && json.length() > 0) {
for (int index = 0; index < json.length(); index++) {
values.add(json.getString(index));
}
}
return values;
} catch (final Exception e) {
logger.warn(marker, "error parsing json data");
throw new RuntimeException(e);
}
}
}
| agpl-3.0 |
cojen/Tupl | src/main/java/org/cojen/tupl/core/Sequencer.java | 6888 | /*
* Copyright 2020 Cojen.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.cojen.tupl.core;
import org.cojen.tupl.util.Latch;
import org.cojen.tupl.util.Parker;
/**
* Special kind of condition variable in which threads wait for a sequence to reach a specific
* value. This allows multiple threads to perform work out of order but apply their results in
* order.
*
* @author Brian S O'Neill
*/
final class Sequencer extends Latch {
// Hashtable of waiters.
private Waiter[] mWaiters;
private int mWaitersSize;
private long mValue;
/**
* @param initial initial sequence value
* @param numWaiters initial number of potential waiters
* @throws IllegalArgumentException if initial is max value
*/
public Sequencer(long initial, int numWaiters) {
if (initial == Long.MAX_VALUE) {
throw new IllegalArgumentException();
}
mWaiters = new Waiter[Utils.roundUpPower2(numWaiters)];
mValue = initial;
}
/**
* Wait until the sequence value is exactly equal to the given value.
*
* @param waiter thread-local instance; pass null to create a new instance automatically
* @return false if aborted
* @throws IllegalStateException if another thread is waiting on the same value or if the
* sequence value is higher than the given value
*/
public boolean await(long value, Waiter waiter) throws InterruptedException {
boolean registered = false;
while (true) {
acquireExclusive();
try {
if (mValue == Long.MAX_VALUE) {
return false;
}
if (mValue == value) {
return true;
}
if (mValue > value) {
throw new IllegalStateException();
}
if (!registered) {
if (waiter == null) {
waiter = new Waiter();
}
Waiter[] waiters = mWaiters;
int index = ((int) value) & (waiters.length - 1);
for (Waiter w = waiters[index]; w != null; w = w.mNext) {
if (w.mValue == value) {
throw new IllegalStateException();
}
}
if (mWaitersSize > waiters.length) {
grow();
waiters = mWaiters;
index = ((int) value) & (waiters.length - 1);
}
waiter.mValue = value;
waiter.mNext = waiters[index];
waiters[index] = waiter;
mWaitersSize++;
registered = true;
}
} finally {
releaseExclusive();
}
// The Sequencer is expected to be used to coordinate threads which are blocked on
// file I/O, and so parking immediately is the most efficient thing to do. As long
// as enough threads are running, there's little risk of a CPU core going to sleep.
Parker.parkNow(this);
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
}
private void grow() {
Waiter[] waiters = mWaiters;
int capacity = waiters.length << 1;
var newWaiters = new Waiter[capacity];
int newMask = capacity - 1;
for (int i=waiters.length; --i>=0 ;) {
for (Waiter w = waiters[i]; w != null; ) {
Waiter next = w.mNext;
int ix = ((int) w.mValue) & newMask;
w.mNext = newWaiters[ix];
newWaiters[ix] = w;
w = next;
}
}
mWaiters = newWaiters;
}
/**
* Updates the sequence value and wakes up any thread waiting for it.
*
* @return false if aborted
* @throws IllegalStateException if the given value isn't higher than the current sequence
* value
*/
public boolean signal(long value) {
Waiter w;
findWaiter: {
acquireExclusive();
try {
if (value <= mValue) {
if (mValue == Long.MAX_VALUE) {
return false;
}
throw new IllegalStateException();
}
mValue = value;
Waiter[] waiters = mWaiters;
int index = ((int) value) & (waiters.length - 1);
Waiter prev = null;
for (w = waiters[index]; w != null; w = w.mNext) {
if (w.mValue == value) {
if (prev == null) {
waiters[index] = w.mNext;
} else {
prev.mNext = w.mNext;
}
mWaitersSize--;
break findWaiter;
} else {
prev = w;
}
}
return true;
} finally {
releaseExclusive();
}
}
Parker.unpark(w.mThread);
w.mNext = null;
return true;
}
/**
* Wakes up all waiting threads.
*/
public void abort() {
acquireExclusive();
try {
mValue = Long.MAX_VALUE;
Waiter[] waiters = mWaiters;
for (int i=0; i<waiters.length; i++) {
for (Waiter w = waiters[i], prev = null; w != null; ) {
Parker.unpark(w.mThread);
Waiter next = w.mNext;
w.mNext = null;
w = next;
}
waiters[i] = null;
}
mWaitersSize = 0;
} finally {
releaseExclusive();
}
}
public static class Waiter {
private final Thread mThread;
private long mValue;
private Waiter mNext;
public Waiter() {
mThread = Thread.currentThread();
}
}
}
| agpl-3.0 |
Xenoage/Zong | utils/utils-base/src/com/xenoage/utils/io/StreamUtils.java | 1568 | package com.xenoage.utils.io;
import java.io.IOException;
/**
* Some useful methods for streams.
*
* @author Andreas Wenger
*/
public class StreamUtils {
/**
* Default implementation of {@link InputStream#read(byte[])}.
* Uses {@link #read(InputStream, byte[], int, int)} (see performance warning).
*/
public static int read(InputStream stream, byte... b)
throws IOException {
return stream.read(b, 0, b.length);
}
/**
* Default implementation of {@link InputStream#read(byte[], int, int)}.
* Reads byte after byte (uses {@link InputStream#read()}), which is very slow.
* Use a better implementation when possible.
*/
public static int read(InputStream stream, byte[] b, int off, int len)
throws IOException {
int i = 0;
for (; i < len; i++) {
int c = stream.read();
if (c == -1) {
break;
}
b[off + i] = (byte) c;
}
return i;
}
/**
* Default implementation of {@link OutputStream#write(byte[])}.
* Uses {@link #write(OutputStream, byte[], int, int)} (see performance warning).
*/
public static void write(OutputStream stream, byte... b)
throws IOException {
write(stream, b, 0, b.length);
}
/**
* Default implementation of {@link OutputStream#write(byte[], int, int)}.
* Writes byte after byte (uses {@link OutputStream#write(int)}), which is very slow.
* Use a better implementation when possible.
*/
public static void write(OutputStream stream, byte b[], int off, int len)
throws IOException {
for (int i = 0; i < len ; i++) {
stream.write(b[off + i]);
}
}
}
| agpl-3.0 |
voncuver/cwierkacz | src/main/java/com/pk/cwierkacz/twitter/attachment/TweetAttachment.java | 508 | package com.pk.cwierkacz.twitter.attachment;
/**
* Attachment which we can add to tweet: f.ex. picture or geo location etc.
*
*/
public abstract class TweetAttachment< T >
{
public TweetAttachment( T attachment ) {
this.attachment = attachment;
}
private final T attachment;
public T getAttachment( ) {
return attachment;
}
public boolean isDefined( ) {
if ( attachment == null )
return false;
else
return true;
}
}
| agpl-3.0 |
rafaelsisweb/restheart | src/test/java/org/restheart/handlers/files/GetFileHandlerTest.java | 1643 | /*
* RESTHeart - the Web API for MongoDB
* Copyright (C) SoftInstigate Srl
*
* 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.restheart.handlers.files;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Maurizio Turatti <maurizio@softinstigate.com>
*/
public class GetFileHandlerTest {
private static final Logger LOG = LoggerFactory.getLogger(GetFileHandlerTest.class);
@Rule
public TestRule watcher = new TestWatcher() {
@Override
protected void starting(Description description) {
LOG.info("executing test {}", description.toString());
}
};
public GetFileHandlerTest() {
}
@Test
public void testExtractBucket() {
assertEquals("mybucket", GetFileBinaryHandler.extractBucketName("mybucket.files"));
}
} | agpl-3.0 |
o2oa/o2oa | o2server/x_cms_assemble_control/src/main/java/com/x/cms/assemble/control/jaxrs/document/ActionQueryListPrevWithFilter.java | 10888 | package com.x.cms.assemble.control.jaxrs.document;
import com.google.gson.JsonElement;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.cms.core.entity.Document;
import com.x.cms.core.entity.Review;
import com.x.cms.core.express.tools.filter.QueryFilter;
import com.x.cms.core.express.tools.filter.term.InTerm;
import com.x.cms.core.express.tools.filter.term.NotInTerm;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
public class ActionQueryListPrevWithFilter extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionQueryListPrevWithFilter.class);
protected ActionResult<List<Wo>> execute( HttpServletRequest request, String id, Integer count, JsonElement jsonElement, EffectivePerson effectivePerson ) {
ActionResult<List<Wo>> result = new ActionResult<>();
Long total = 0L;
Wi wi = null;
List<Wo> wos = new ArrayList<>();
List<Document> documentList = null;
List<Document> searchResultList = new ArrayList<>();
List<Review> reviewList = null;
Boolean check = true;
Boolean isManager = false;
String personName = effectivePerson.getDistinguishedName();
QueryFilter queryFilter = null;
if ( count == 0 ) { count = 20; }
if ( StringUtils.isEmpty( id ) || "(0)".equals( id ) ) { id = null; }
try {
wi = this.convertToWrapIn( jsonElement, Wi.class );
} catch (Exception e ) {
check = false;
Exception exception = new ExceptionDocumentInfoProcess( e, "系统在将JSON信息转换为对象时发生异常。JSON:" + jsonElement.toString() );
result.error( exception );
logger.error( e, effectivePerson, request, null);
}
if ( wi == null ) { wi = new Wi(); }
if( StringUtils.isEmpty( wi.getDocumentType() )) {
wi.setDocumentType( "信息" );
}
if( StringUtils.isEmpty( wi.getOrderField() )) {
wi.setOrderField( "createTime" );
}
if( StringUtils.isEmpty( wi.getOrderType() )) {
wi.setOrderType( "DESC" );
}
if( ListTools.isEmpty( wi.getStatusList() )) {
List<String> status = new ArrayList<>();
status.add( "published" );
wi.setStatusList( status );
}
if (check) {
try {
queryFilter = wi.getQueryFilter();
} catch (Exception e) {
check = false;
Exception exception = new ExceptionDocumentInfoProcess(e, "系统在获取查询条件信息时发生异常。");
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
}
if( check ) {
try {
if( effectivePerson.isManager() || userManagerService.isHasPlatformRole( effectivePerson.getDistinguishedName(), "CMSManager" )) {
isManager = true;
}
} catch (Exception e) {
check = false;
Exception exception = new ExceptionDocumentInfoProcess(e, "系统在判断用户是否是管理时发生异常。");
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
}
if( check ) {
//查询是否已读,需要使用相应的ID进行IN操作,效率有一些低
List<String> readDocIds = null;
if( "READ".equalsIgnoreCase( wi.getReadFlag() )) { //只查询阅读过的
//查询出该用户所有已经阅读过的文档ID列表
try {
readDocIds = documentViewRecordServiceAdv.listDocIdsByPerson( personName, 2000 );
if( ListTools.isEmpty( readDocIds )) {
readDocIds = new ArrayList<>();
readDocIds.add( "no Document readed" );
}
if( isManager ) {
queryFilter.addInTerm( new InTerm( "id", new ArrayList<>( readDocIds ) ) );
}else {
queryFilter.addInTerm( new InTerm( "docId", new ArrayList<>( readDocIds ) ) );
}
} catch (Exception e) {
check = false;
Exception exception = new ExceptionDocumentInfoProcess(e, "系统在查询用户已经阅读过的文档ID列表时发生异常。");
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
}else if("UNREAD".equalsIgnoreCase( wi.getReadFlag() )) { //只查询未阅读过的
//查询出该用户所有已经阅读过的文档ID列表
try {
readDocIds = documentViewRecordServiceAdv.listDocIdsByPerson( personName, 2000 );
if( ListTools.isNotEmpty( readDocIds )) {
if( isManager ) {
queryFilter.addNotInTerm( new NotInTerm( "id", new ArrayList<>( readDocIds ) ) );
}else {
queryFilter.addNotInTerm( new NotInTerm( "docId", new ArrayList<>( readDocIds ) ) );
}
}
} catch (Exception e) {
check = false;
Exception exception = new ExceptionDocumentInfoProcess(e, "系统在查询用户已经阅读过的文档ID列表时发生异常。");
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
}
}
if (check) { // 从Review表中查询符合条件的对象总数
try {
if( isManager ) { //直接从Document忽略权限查询
total = documentQueryService.countWithConditionOutofPermission( queryFilter );
}else {
total = documentQueryService.countWithConditionInReview( personName, queryFilter );
}
} catch (Exception e) {
check = false;
Exception exception = new ExceptionDocumentInfoProcess(e, "系统在获取用户可查询到的文档数据条目数量时发生异常。");
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
}
if (check) {
//document和Review除了sequence还有5个排序列支持title, appAlias, categoryAlias, categoryName, creatorUnitName的分页查询
//除了sequence和title, appAlias, categoryAlias, categoryName, creatorUnitName之外,其他的列排序全部在内存进行分页
try {
if( isManager ) {
//判断排序列是不是已经在Document表里做了sequence索引列,如果是,则只需要从document表查询 即可。
if( Document.isFieldInSequence( wi.getOrderField()) ) { //直接从Document忽略权限查询
searchResultList = documentQueryService.listPrevWithConditionOutofPermission( id, count, wi.getOrderField(), wi.getOrderType(), queryFilter );
}else {
//根据人员权限查询出2000条文档的完整信息,然后对某属性进行排序,在内存中进行分页
documentList = documentQueryService.listNextWithConditionOutofPermission( wi.getOrderField(), wi.getOrderType(), queryFilter, 2000 );
//循环分页,查询传入的ID所在的位置,向后再查询N条
if( ListTools.isNotEmpty( documentList )) {
Document document = null;
int index = -1;
//放一页到searchResultList中进行返回
for( int i = 0; i< documentList.size(); i++ ) {
document = documentList.get(i);
if( StringUtils.isEmpty( id ) || document.getId().equalsIgnoreCase( id ) ) {
index = i;
}
}
for( ; index >=0; index-- ){
searchResultList.add( documentList.get(index) );
if( searchResultList.size() >= count ) { break; }
}
}
}
}else {
if( Document.isFieldInSequence(wi.getOrderField()) ) { // 从Review表中查询符合条件的对象,并且转换为Document对象列表
searchResultList = documentQueryService.listPrevWithConditionInReview( id, count, wi.getOrderField(), wi.getOrderType(), personName, queryFilter );
}else {
reviewList = documentQueryService.listNextWithConditionInReview( wi.getOrderField(), wi.getOrderType(), personName, queryFilter, 2000 );
//循环分页,查询传入的ID所在的位置,向后再查询N条,转换为Document放到searchResultList
searchResultList = new ArrayList<>();
if( ListTools.isNotEmpty( reviewList )) {
Boolean add2List = false;
Review review = null;
int index = -1;
//放一页到searchResultList中进行返回
for( int i = 0; i< reviewList.size(); i++ ) {
review = reviewList.get(i);
if( StringUtils.isEmpty( id ) || review.getDocId().equalsIgnoreCase( id ) ) {
index = i;
}
}
for( ; index >=0; index-- ){
review = reviewList.get( index );
searchResultList.add(documentQueryService.get( review.getDocId() ) );
if( searchResultList.size() >= count ) { break; }
}
}
}
}
} catch (Exception e) {
check = false;
Exception exception = new ExceptionDocumentInfoProcess(e, "系统在根据用户可访问的文档ID列表对文档进行分页查询时发生异常。");
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
}
if (check) {
if ( searchResultList != null ) {
Wo wo = null;
for( Document document : searchResultList ) {
if( document != null ){
try {
wo = Wo.copier.copy( document );
if( wo.getCreatorPerson() != null && !wo.getCreatorPerson().isEmpty() ) {
wo.setCreatorPersonShort( wo.getCreatorPerson().split( "@" )[0]);
}
if( wo.getCreatorUnitName() != null && !wo.getCreatorUnitName().isEmpty() ) {
wo.setCreatorUnitNameShort( wo.getCreatorUnitName().split( "@" )[0]);
}
if( wo.getCreatorTopUnitName() != null && !wo.getCreatorTopUnitName().isEmpty() ) {
wo.setCreatorTopUnitNameShort( wo.getCreatorTopUnitName().split( "@" )[0]);
}
if( wi.getNeedData() ) {
//需要组装数据
wo.setData( documentQueryService.getDocumentData( document ) );
}
} catch (Exception e) {
check = false;
Exception exception = new ExceptionDocumentInfoProcess(e, "系统获取文档数据内容信息时发生异常。Id:" + document.getCategoryId());
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
wos.add( wo );
}
}
}
}
result.setCount(total);
result.setData(wos);
return result;
}
public class DocumentCacheForFilter {
private Long total = 0L;
private List<Wo> documentList = null;
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<Wo> getDocumentList() {
return documentList;
}
public void setDocumentList(List<Wo> documentList) {
this.documentList = documentList;
}
}
public static class Wi extends WrapInDocumentFilter{
}
public static class Wo extends WrapOutDocumentList {
public static List<String> excludes = new ArrayList<String>();
public static final WrapCopier<Document, Wo> copier = WrapCopierFactory.wo( Document.class, Wo.class, null,JpaObject.FieldsInvisible);
}
}
| agpl-3.0 |
IntersectAustralia/cbioportal | web/src/main/java/org/mskcc/cbio/portal/web/api/ApiController.java | 19699 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.mskcc.cbio.portal.web.api;
import java.util.ArrayList;
import java.util.List;
import org.mskcc.cbio.portal.service.ApiService;
import org.mskcc.cbio.portal.model.DBCancerType;
import org.mskcc.cbio.portal.model.DBClinicalField;
import org.mskcc.cbio.portal.model.DBClinicalPatientData;
import org.mskcc.cbio.portal.model.DBClinicalSampleData;
import org.mskcc.cbio.portal.model.DBGene;
import org.mskcc.cbio.portal.model.DBGeneAlias;
import org.mskcc.cbio.portal.model.DBGeneticProfile;
import org.mskcc.cbio.portal.model.DBPatient;
import org.mskcc.cbio.portal.model.DBProfileData;
import org.mskcc.cbio.portal.model.DBSample;
import org.mskcc.cbio.portal.model.DBSampleList;
import org.mskcc.cbio.portal.model.DBStudy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.Example;
import io.swagger.annotations.ExampleProperty;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.mskcc.cbio.portal.model.DBAltCountInput;
/**
*
* @author abeshoua
*/
@Controller
public class ApiController {
@Autowired
private ApiService service;
/* DISPATCHERS */
@ApiOperation(value = "Get cancer types with meta data",
nickname = "getCancerTypes",
notes = "")
@Transactional
@RequestMapping(value = "/cancertypes", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBCancerType> getCancerTypes(
@ApiParam(required = false, value = "List of cancer type identifiers (example: cll,brca,coad). Unrecognized ids are silently ignored. Empty string returns all.")
@RequestParam(required = false)
List<String> cancer_type_ids) {
if (cancer_type_ids == null) {
return service.getCancerTypes();
} else {
return service.getCancerTypes(cancer_type_ids);
}
}
@ApiOperation(value = "Get mutation count for certain gene. If per_study is true will return count for each study, if false will return the total count. User can specify specifc study set to look for.",
nickname = "getMutationCount",
notes = "")
@Transactional
@RequestMapping(value = "/mutation_count", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<Map<String, String>> getMutationsCounts(
HttpServletRequest request,
@ApiParam(required = true, value = "\"count\" or \"frequency\"")
@RequestParam(required = true) String type, @RequestParam(required = true) Boolean per_study, @RequestParam(required = false) List<String> studyId, @RequestParam(required = true) List<String> gene, @RequestParam(required = false) List<Integer> start, @RequestParam(required = false) List<Integer> end, @RequestParam(required = false) List<String> echo) {
Enumeration<String> parameterNames = request.getParameterNames();
String[] fixedInput = {"type", "per_study", "gene", "start", "end", "echo"};
Map<String,String[]> customizedAttrs = new HashMap<String,String[]>();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
if(!Arrays.asList(fixedInput).contains(paramName)){
String[] paramValues = request.getParameterValues(paramName);
customizedAttrs.put(paramName, paramValues[0].split(","));
}
}
return service.getMutationsCounts(customizedAttrs, type, per_study, studyId, gene, start, end, echo);
}
@ApiOperation(value = "Get clinical data records, filtered by sample ids",
nickname = "getSampleClinicalData",
notes = "")
@Transactional
@RequestMapping(value = "/clinicaldata/samples", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBClinicalSampleData> getSampleClinicalData(
@ApiParam(required = true, value = "A single study id, such as those returned by /api/studies. (example: brca_tcga)")
@RequestParam(required = true)
String study_id,
@ApiParam(required = true, value = "List of attribute ids, such as those returned by /api/clinicalattributes/samples. (example: SAMPLE_TYPE,IS_FFPE)")
@RequestParam(required = true)
List<String> attribute_ids,
@ApiParam(required = false, value = "List of sample identifiers. Unrecognized ids are silently ignored. Empty string returns all.")
@RequestParam(required = false)
List<String> sample_ids) {
if (sample_ids == null) {
return service.getSampleClinicalData(study_id, attribute_ids);
} else {
return service.getSampleClinicalData(study_id, attribute_ids, sample_ids);
}
}
@ApiOperation(value = "Get clinical data records filtered by patient ids",
nickname = "getPatientClinicalData",
notes = "")
@Transactional
@RequestMapping(value = "/clinicaldata/patients", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBClinicalPatientData> getPatientClinicalData(
@ApiParam(required = true, value = "A single study id, such as those returned by /api/studies. (example: brca_tcga)")
@RequestParam(required = true)
String study_id,
@ApiParam(required = true, value = "List of attribute ids, such as those returned by /api/clinicalattributes/patients. (example: PATIENT_ID,DFS_STATUS)")
@RequestParam(required = true)
List<String> attribute_ids,
@ApiParam(required = false, value = "List of patient identifiers such as those returned by /api/patients. Unrecognized ids are silently ignored. Empty string returns all.")
@RequestParam(required = false)
List<String> patient_ids) {
if (patient_ids == null) {
return service.getPatientClinicalData(study_id, attribute_ids);
} else {
return service.getPatientClinicalData(study_id, attribute_ids, patient_ids);
}
}
@ApiOperation(value = "Get clinical attribute identifiers, filtered by identifier",
nickname = "getClinicalAttributes",
notes = "")
@Transactional
@RequestMapping(value = "/clinicalattributes", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBClinicalField> getClinicalAttributes(
@ApiParam(value = "List of attribute ids. If provided, returned clinical attributes will be the ones with matching attribute ids. Empty string returns all clinical attributes.")
@RequestParam(required = false)
List<String> attr_ids) {
if (attr_ids == null) {
return service.getClinicalAttributes();
} else {
return service.getClinicalAttributes(attr_ids);
}
}
@ApiOperation(value = "Get clinical attribute identifiers, filtered by sample",
nickname = "getSampleClinicalAttributes",
notes = "")
@Transactional
@RequestMapping(value = "/clinicalattributes/samples", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBClinicalField> getSampleClinicalAttributes(
@ApiParam(value = "A single study id, such as those returned by /api/studies. (example: brca_tcga). Empty string returns clinical attributes across all studies.")
@RequestParam(required = false)
String study_id,
@ApiParam(required = false, value = "List of sample_ids. If provided, returned clinical attributes will be those which appear in any listed sample. Empty string returns clinical attributes across all samples.")
@RequestParam(required = false)
List<String> sample_ids) {
if (sample_ids == null && study_id == null) {
return service.getSampleClinicalAttributes();
} else if (study_id != null && sample_ids != null) {
return service.getSampleClinicalAttributes(study_id, sample_ids);
} else if (sample_ids == null) {
return service.getSampleClinicalAttributesByInternalIds(service.getSampleInternalIds(study_id));
} else {
return new ArrayList<>();
}
}
@ApiOperation(value = "Get clinical attribute identifiers, filtered by patient",
nickname = "getPatientClinicalAttributes",
notes = "")
@Transactional
@RequestMapping(value = "/clinicalattributes/patients", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBClinicalField> getPatientClinicalAttributes(
@ApiParam(required = false, value = "A single study id, such as those returned by /api/studies. (example: brca_tcga). Empty string returns clinical attributes across all studies.")
@RequestParam(required = false)
String study_id,
@ApiParam(required = false, value = "List of patient_ids. If provided, returned clinical attributes will be those which appear in any listed patient. Empty string returns clinical attributes across all patients.")
@RequestParam(required = false)
List<String> patient_ids) {
if (patient_ids == null && study_id == null) {
return service.getPatientClinicalAttributes();
} else if (study_id != null && patient_ids != null) {
return service.getPatientClinicalAttributes(study_id, patient_ids);
} else if (patient_ids == null) {
return service.getPatientClinicalAttributesByInternalIds(service.getPatientInternalIdsByStudy(study_id));
} else {
return new ArrayList<>();
}
}
@ApiOperation(value = "Get gene meta data by hugo gene symbol lookup",
nickname = "getGenes",
notes = "")
@Transactional
@RequestMapping(value = "/genes", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBGene> getGenes(
@ApiParam(required = false, value = "List of hugo gene symbols. Unrecognized genes are silently ignored. Empty string returns all genes.")
@RequestParam(required = false)
List<String> hugo_gene_symbols) {
if (hugo_gene_symbols == null) {
return service.getGenes();
} else {
return service.getGenes(hugo_gene_symbols);
}
}
@ApiOperation(value = "Get noncanonical gene symbols by Entrez id lookup",
nickname = "getGenesAliases",
notes = "")
@Transactional
@RequestMapping(value = "/genesaliases", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBGeneAlias> getGenesAliases(
@ApiParam(required = false, value = "List of Entrez gene ids. Unrecognized IDs are silently ignored. Empty list returns all genes.")
@RequestParam(required = false)
List<Long> entrez_gene_ids) {
if (entrez_gene_ids == null) {
return service.getGenesAliases();
} else {
return service.getGenesAliases(entrez_gene_ids);
}
}
@ApiOperation(value = "Get list of genetic profile identifiers by study",
nickname = "getGeneticProfiles",
notes = "")
@Transactional
@RequestMapping(value = "/geneticprofiles", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBGeneticProfile> getGeneticProfiles(
@ApiParam(required = false, value = "A single study id, such as those returned by /api/studies. (example: brca_tcga). Must be empty to query by genetic profile ids (across all studies).")
@RequestParam(required = false)
String study_id,
@ApiParam(required = false, value = "List of genetic_profile_ids. (example: brca_tcga_pub_mutations). Empty string returns all genetic profiles. If study_id argument was provided, this argument will be ignored.")
@RequestParam(required = false)
List<String> genetic_profile_ids) {
if (study_id != null) {
return service.getGeneticProfiles(study_id);
} else if (genetic_profile_ids != null) {
return service.getGeneticProfiles(genetic_profile_ids);
} else {
return service.getGeneticProfiles();
}
}
@ApiOperation(value = "Get list of sample lists (list name and sample id list) by study",
nickname = "getSampleLists",
notes = "")
@Transactional
@RequestMapping(value = "/samplelists", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBSampleList> getSampleLists(
@ApiParam(required = false, value = "A single study id, such as those returned by /api/studies. (example: brca_tcga). Must be empty to query by sample list ids (across all studies).")
@RequestParam(required = false)
String study_id,
@ApiParam(required = false, value = "List of sample list ids. (example: brca_tcga_idc,brca_tcga_lobular). Empty string returns all genetic profiles. If study_id argument was provided, this argument will be ignored.")
@RequestParam(required = false)
List<String> sample_list_ids) {
if (study_id != null) {
return service.getSampleLists(study_id);
} else if (sample_list_ids != null) {
return service.getSampleLists(sample_list_ids);
} else {
return service.getSampleLists();
}
}
@ApiOperation(value = "Get patient id list by study or by sample id",
nickname = "getPatients",
notes = "")
@Transactional
@RequestMapping(value = "/patients", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBPatient> getPatients(
@ApiParam(required = true, value = "A single study id, such as those returned by /api/studies. (example: brca_tcga)")
@RequestParam(required = true)
String study_id,
@ApiParam(required = false, value = "List of patient ids such as those returned by /api/patients. Empty string returns all. Must be empty to query by sample ids.")
@RequestParam(required = false)
List<String> patient_ids,
@ApiParam(required = false, value = "List of sample identifiers. Empty string returns all. If patient_ids argument was provided, this argument will be ignored.")
@RequestParam(required = false)
List<String> sample_ids) {
if (patient_ids != null) {
return service.getPatientsByPatient(study_id, patient_ids);
} else if (sample_ids != null) {
return service.getPatientsBySample(study_id, sample_ids);
} else {
return service.getPatients(study_id);
}
}
@ApiOperation(value = "Get genetic profile data across samples for given genes, and filtered by sample id or sample list id",
nickname = "getGeneticProfileData",
notes = "")
@Transactional
@RequestMapping(value = "/geneticprofiledata", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBProfileData> getGeneticProfileData(
@ApiParam(required = true, value = "List of genetic_profile_ids such as those returned by /api/geneticprofiles. (example: brca_tcga_pub_mutations). Unrecognized genetic profile ids are silently ignored. Profile data is only returned for matching ids.")
@RequestParam(required = true)
List<String> genetic_profile_ids,
@ApiParam(required = true, value = "List of hugo gene symbols. (example: AKT1,CASP8,TGFBR1) Unrecognized gene ids are silently ignored. Profile data is only returned for matching genes.")
@RequestParam(required = true)
List<String> genes,
@ApiParam(required = false, value = "List of sample identifiers such as those returned by /api/samples. Empty string returns all. Must be empty to query by sample list ids.")
@RequestParam(required = false)
List<String> sample_ids,
@ApiParam(required = false, value = "A single sample list ids such as those returned by /api/samplelists. (example: brca_tcga_idc,brca_tcga_lobular). Empty string returns all. If sample_ids argument was provided, this argument will be ignored.")
@RequestParam(required = false)
String sample_list_id) {
if (sample_ids == null && sample_list_id == null) {
return service.getGeneticProfileData(genetic_profile_ids, genes);
} else if (sample_ids != null) {
return service.getGeneticProfileDataBySample(genetic_profile_ids, genes, sample_ids);
} else {
return service.getGeneticProfileDataBySampleList(genetic_profile_ids, genes, sample_list_id);
}
}
@ApiOperation(value = "Get list of samples ids with meta data by study, filtered by sample ids or patient ids",
nickname = "getSamples",
notes = "")
@Transactional
@RequestMapping(value = "/samples", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBSample> getSamples(
@ApiParam(required = true, value = "A single study id, such as those returned by /api/studies. (example: brca_tcga)")
@RequestParam(required = true)
String study_id,
@ApiParam(required = false, value = "List of sample identifiers. Unrecognized ids are silently ignored. Empty string returns all. Must be empty to query by patient_ids.")
@RequestParam(required = false)
List<String> sample_ids,
@ApiParam(required = false, value = "List of patient identifiers such as those returned by /api/patients. Unrecognized ids are silently ignored. Empty string returns all. If sample_ids argument was provided, this arument will be ignored.")
@RequestParam(required = false)
List<String> patient_ids) {
if (sample_ids != null) {
return service.getSamplesBySample(study_id, sample_ids);
} else if (patient_ids != null) {
return service.getSamplesByPatient(study_id, patient_ids);
} else {
return service.getSamples(study_id);
}
}
@ApiOperation(value = "Get studies",
nickname = "getStudies",
notes = "")
@Transactional
@RequestMapping(value = "/studies", method = {RequestMethod.GET, RequestMethod.POST})
public @ResponseBody List<DBStudy> getStudies(
@ApiParam(required = false, value = "List of study_ids. Unrecognized ids are silently ignored. Empty string returns all.")
@RequestParam(required = false)
List<String> study_ids) {
if (study_ids == null) {
return service.getStudies();
} else {
return service.getStudies(study_ids);
}
}
}
| agpl-3.0 |
Tanaguru/Tanaguru | rules/rgaa4-2019/src/test/java/org/tanaguru/rules/rgaa42019/Rgaa42019Rule070201Test.java | 4452 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.rgaa42019;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.entity.audit.ProcessResult;
import org.tanaguru.rules.rgaa42019.test.Rgaa42019RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 7-2-1 of the referential Rgaa 4-2019.
*
* @author edaconceicao
*/
public class Rgaa42019Rule070201Test extends Rgaa42019RuleImplementationTestCase {
/**
* Default constructor
*/
public Rgaa42019Rule070201Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.tanaguru.rules.rgaa42019.Rgaa42019Rule070201");
}
@Override
protected void setUpWebResourceMap() {
// addWebResource("Rgaa4-2019.Test.7.2.1-1Passed-01");
// addWebResource("Rgaa4-2019.Test.7.2.1-2Failed-01");
addWebResource("Rgaa4-2019.Test.7.2.1-3NMI-01");
// addWebResource("Rgaa4-2019.Test.7.2.1-4NA-01");
}
@Override
protected void setProcess() {
//----------------------------------------------------------------------
//------------------------------1Passed-01------------------------------
//----------------------------------------------------------------------
// checkResultIsPassed(processPageTest("Rgaa4-2019.Test.7.2.1-1Passed-01"), 1);
//----------------------------------------------------------------------
//------------------------------2Failed-01------------------------------
//----------------------------------------------------------------------
// ProcessResult processResult = processPageTest("Rgaa4-2019.Test.7.2.1-2Failed-01");
// checkResultIsFailed(processResult, 1, 1);
// checkRemarkIsPresent(
// processResult,
// TestSolution.FAILED,
// "#MessageHere",
// "#CurrentElementHere",
// 1,
// new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue"));
//----------------------------------------------------------------------
//------------------------------3NMI-01---------------------------------
//----------------------------------------------------------------------
ProcessResult processResult = processPageTest("Rgaa4-2019.Test.7.2.1-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("Rgaa4-2019.Test.7.2.1-4NA-01"));
}
@Override
protected void setConsolidate() {
// The consolidate method can be removed when real implementation is done.
// The assertions are automatically tested regarding the file names by
// the abstract parent class
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa4-2019.Test.7.2.1-3NMI-01").getValue());
}
}
| agpl-3.0 |
deerwalk/voltdb | src/frontend/org/voltdb/utils/Collector.java | 27418 | /* This file is part of VoltDB.
* Copyright (C) 2008-2017 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.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
import org.apache.log4j.Logger;
import org.apache.log4j.varia.NullAppender;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltcore.utils.CoreUtils;
import org.voltdb.CLIConfig;
import org.voltdb.VoltDB;
import org.voltdb.common.Constants;
import org.voltdb.settings.NodeSettings;
import org.voltdb.types.TimestampType;
import com.google_voltpatches.common.base.Throwables;
public class Collector {
private final static String ZIP_ENTRY_FOLDER_BASE_SUFFIX = "_volt_collect_logs_";
final static String PREFIX_DEFAULT_COLLECT_FILE = "voltdb_collect";
final static String COLLECT_FILE_EXTENSION = ".zip";
private static String m_configInfoPath = null;
private static String m_catalogJarPath = null;
private static String m_deploymentPath = null;
private static String m_systemCheckPath = null;
private static String m_pathPropertiesPath = null;
private static String m_clusterPropertiesPath = null;
private static CollectConfig m_config;
public static long m_currentTimeMillis = System.currentTimeMillis();
private static String m_workingDir = null;
private static Set<String> m_logPaths = new HashSet<String>();
private static Properties m_systemStats = new Properties();
private static VoltFile m_voltdbRoot = null;
private static String m_zipFolderBase = "";
static String getZipCollectFolderBase() { return m_zipFolderBase; }
public static String[] cmdFilenames = {"sardata", "dmesgdata", "syscheckdata"};
static class CollectConfig extends CLIConfig {
@Option(desc = "file name prefix for uniquely identifying collection")
String prefix = "";
@Option(desc = "file name prefix for uniquely identifying collection")
String outputFile = "";
@Option(desc = "list the log files without collecting them")
boolean dryrun = false;
@Option(desc = "exclude heap dump file from collection")
boolean skipheapdump = true;
@Option(desc = "number of days of files to collect (files included are log, crash files), Current day value is 1")
int days = 7;
@Option(desc = "the voltdbroot path")
String voltdbroot = "";
@Option(desc = "overwrite output file if it exists")
boolean force= false;
@Option
String libPathForTest = "";
@Override
public void validate() {
if (days < 0) exitWithMessageAndUsage("days must be >= 0");
if (voltdbroot.trim().isEmpty()) exitWithMessageAndUsage("Invalid database directory");
}
}
private static void populateVoltDBCollectionPaths() {
m_voltdbRoot = new VoltFile(m_config.voltdbroot);
if (!m_voltdbRoot.exists()) {
System.err.println(m_voltdbRoot.getParentFile().getAbsolutePath() + " does not contain a valid database "
+ "directory. Specify valid path to the database directory.");
VoltDB.exit(-1);
}
if (!m_voltdbRoot.isDirectory()) {
System.err.println(m_voltdbRoot.getParentFile().getAbsolutePath() + " is a not directory. Specify valid "
+ " database directory in --dir option.");
VoltDB.exit(-1);
}
if (!m_voltdbRoot.canRead() || !m_voltdbRoot.canExecute()) {
System.err.println(m_voltdbRoot.getParentFile().getAbsolutePath() + " does not have read/exceute permission.");
VoltDB.exit(-1);
}
m_config.voltdbroot = m_voltdbRoot.getAbsolutePath();
// files to collect from config dir
String configLogDirPath = m_voltdbRoot.getAbsolutePath() + File.separator + Constants.CONFIG_DIR + File.separator;
m_configInfoPath = configLogDirPath + "config.json";
m_catalogJarPath = configLogDirPath + "catalog.jar";
m_deploymentPath = configLogDirPath + "deployment.xml";
m_pathPropertiesPath = configLogDirPath + "path.properties";
m_clusterPropertiesPath = configLogDirPath + "cluster.properties";
m_systemCheckPath = m_voltdbRoot.getAbsolutePath() + File.separator + "systemcheck";
// Validate voltdbroot path is valid or not - check if deployment and config info json exists
File deploymentFile = new File(m_deploymentPath);
File configInfoFile = new File(m_configInfoPath);
if (!deploymentFile.exists() || !configInfoFile.exists()) {
System.err.println("ERROR: Invalid database directory " + m_voltdbRoot.getParentFile().getAbsolutePath()
+ ". Specify valid database directory using --dir option.");
VoltDB.exit(-1);
}
if (!m_config.prefix.isEmpty()) {
m_config.outputFile = m_config.prefix + "_" + PREFIX_DEFAULT_COLLECT_FILE + "_"
+ CoreUtils.getHostnameOrAddress() + COLLECT_FILE_EXTENSION;
}
if (m_config.outputFile.isEmpty()) {
m_config.outputFile = PREFIX_DEFAULT_COLLECT_FILE + "_" + CoreUtils.getHostnameOrAddress()
+ COLLECT_FILE_EXTENSION;;
}
File outputFile = new File(m_config.outputFile);
if (outputFile.exists() && !m_config.force) {
System.err.println("ERROR: Output file " + outputFile.getAbsolutePath() + " already exists."
+ " Use --force to overwrite an existing file.");
VoltDB.exit(-1);
}
}
public static void main(String[] args) {
// get rid of log4j "no appenders could be found for logger" warning when called from VEM
Logger.getRootLogger().addAppender(new NullAppender());
m_config = new CollectConfig();
m_config.parse(Collector.class.getName(), args);
if (!m_config.outputFile.trim().isEmpty() && !m_config.prefix.trim().isEmpty()) {
System.err.println("For outputfile, specify either --output or --prefix. Can't specify "
+ "both of them.");
m_config.printUsage();
VoltDB.exit(-1);
}
populateVoltDBCollectionPaths();
JSONObject jsonObject = parseJSONFile(m_configInfoPath);
parseJSONObject(jsonObject);
String systemStatsPathBase;
if (m_config.libPathForTest.isEmpty())
systemStatsPathBase = System.getenv("VOLTDB_LIB");
else
systemStatsPathBase = m_config.libPathForTest;
String systemStatsPath;
if (System.getProperty("os.name").contains("Mac"))
systemStatsPath = systemStatsPathBase + File.separator + "macstats.properties";
else
systemStatsPath = systemStatsPathBase + File.separator + "linuxstats.properties";
try {
InputStream systemStatsIS = new FileInputStream(systemStatsPath);
m_systemStats.load(systemStatsIS);
} catch (IOException e) {
Throwables.propagate(e);
}
Set<String> collectionFilesList = setCollection(m_config.skipheapdump);
if (m_config.dryrun) {
System.out.println("List of the files to be collected:");
for (String path: collectionFilesList) {
System.out.println(" " + path);
}
System.out.println("[dry-run] A tgz file containing above files would be generated in current dir");
System.out.println(" Use --upload option to enable uploading via SFTP");
}
else {
generateCollection(collectionFilesList);
}
}
public static JSONObject parseJSONFile(String configInfoPath) {
JSONObject jsonObject = null;
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(configInfoPath)));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
jsonObject = new JSONObject(builder.toString());
} catch (FileNotFoundException e) {
System.err.println("config log file '" + configInfoPath + "' could not be found.");
VoltDB.exit(-1);
} catch (IOException e) {
System.err.println(e.getMessage());
VoltDB.exit(-1);
} catch (JSONException e) {
System.err.println("Error with config file: " + configInfoPath);
System.err.println(e.getLocalizedMessage());
VoltDB.exit(-1);
}
return jsonObject;
}
private static void parseJSONObject(JSONObject jsonObject) {
try {
m_workingDir = jsonObject.getString("workingDir");
m_logPaths.clear();
JSONArray jsonArray = jsonObject.getJSONArray("log4jDst");
for (int i = 0; i < jsonArray.length(); i++) {
String path = jsonArray.getJSONObject(i).getString("path");
m_logPaths.add(path);
}
} catch (JSONException e) {
System.err.println(e.getMessage());
}
}
private static String getLinuxOSInfo() {
// Supported Linux OS for voltdb are CentOS, Redhat and Ubuntu
String versionInfo = "";
BufferedReader br = null;
// files containing the distribution info
// Ubuntu - "/etc/lsb-release"
// Redhat, CentOS - "/etc/redhat-release"
final List<String> distInfoFilePaths = Arrays.asList("/etc/lsb-release",
"/etc/redhat-release");
for (String filePath : distInfoFilePaths) {
if (Files.exists(Paths.get(filePath))) {
try {
br = new BufferedReader(new FileReader(filePath));
}
catch (FileNotFoundException excp) {
System.err.println(excp.getMessage());
}
break;
}
}
if (br != null) {
StringBuffer buffer = new StringBuffer();
try {
while ((versionInfo = br.readLine()) != null) {
buffer.append(versionInfo);
}
versionInfo = buffer.toString();
}
catch (IOException io) {
System.err.println(io.getMessage());
versionInfo = "";
}
}
return versionInfo;
}
private static Set<String> setCollection(boolean skipHeapDump) {
Set<String> collectionFilesList = new HashSet<String>();
try {
if (new File(m_deploymentPath).exists()) {
collectionFilesList.add(m_deploymentPath);
}
if (new File(m_catalogJarPath).exists()) {
collectionFilesList.add(m_catalogJarPath);
}
if (new File(m_systemCheckPath).exists()) {
collectionFilesList.add(m_systemCheckPath);
}
if (new File(m_configInfoPath).exists()) {
collectionFilesList.add(m_configInfoPath);
}
if (new File(m_pathPropertiesPath).exists()) {
collectionFilesList.add(m_pathPropertiesPath);
}
if (new File(m_clusterPropertiesPath).exists()) {
collectionFilesList.add(m_clusterPropertiesPath);
}
for (String path: m_logPaths) {
for (File file: new File(path).getParentFile().listFiles()) {
if (file.getName().startsWith(new File(path).getName())
&& isFileModifiedInCollectionPeriod(file)) {
collectionFilesList.add(file.getCanonicalPath());
}
}
}
for (File file: new File(m_config.voltdbroot).listFiles()) {
if (file.getName().startsWith("voltdb_crash") && file.getName().endsWith(".txt")
&& isFileModifiedInCollectionPeriod(file)) {
collectionFilesList.add(file.getCanonicalPath());
}
if (file.getName().startsWith("hs_err_pid") && file.getName().endsWith(".log")
&& isFileModifiedInCollectionPeriod(file)) {
collectionFilesList.add(file.getCanonicalPath());
}
}
for (File file: new File(m_workingDir).listFiles()) {
if (file.getName().startsWith("voltdb_crash") && file.getName().endsWith(".txt")
&& isFileModifiedInCollectionPeriod(file)) {
collectionFilesList.add(file.getCanonicalPath());
}
if (file.getName().startsWith("hs_err_pid") && file.getName().endsWith(".log")
&& isFileModifiedInCollectionPeriod(file)) {
collectionFilesList.add(file.getCanonicalPath());
}
}
String systemLogBase;
final String systemLogBaseDirPath = "/var/log/";
if (System.getProperty("os.name").startsWith("Mac")) {
systemLogBase = "system.log";
} else {
String versionInfo = getLinuxOSInfo();
if (versionInfo.contains("Ubuntu")) {
systemLogBase = "syslog";
}
else {
systemLogBase = "messages";
if (versionInfo.isEmpty()) {
System.err.println("Couldn't find distribution info for supported systems. Perform"
+ " lookup for system logs in files named: " + systemLogBase);
}
}
}
for (File file: new File(systemLogBaseDirPath).listFiles()) {
if (file.getName().startsWith(systemLogBase)) {
collectionFilesList.add(file.getCanonicalPath());
}
}
if (!skipHeapDump) {
for (File file: new File("/tmp").listFiles()) {
if (file.getName().startsWith("java_pid") && file.getName().endsWith(".hprof")
&& isFileModifiedInCollectionPeriod(file)) {
collectionFilesList.add(file.getCanonicalPath());
}
}
}
collectionFilesList.add("duvoltdbrootdata (result of executing \"du -h <voltdbroot>\")");
collectionFilesList.add("dudroverflowdata (result of executing \"du -h <droverflow>\")");
collectionFilesList.add("duexportoverflowdata (result of executing \"du -h <exportoverflow>\")");
collectionFilesList.add("ducommandlog (result of executing \"du -h <command_log>\")");
collectionFilesList.add("ducommandlogsnapshot (result of executing \"du -h <command_log_snapshot>\")");
for (String fileName : m_systemStats.stringPropertyNames()) {
collectionFilesList.add(fileName + " (result of executing \"" + m_systemStats.getProperty(fileName) + "\")");
}
File varlogDir = new File("/var/log");
if (varlogDir.canRead()) {
for (File file: varlogDir.listFiles()) {
if ((file.getName().startsWith("syslog") || file.getName().equals("dmesg"))
&& isFileModifiedInCollectionPeriod(file)) {
if (file.canRead()) {
collectionFilesList.add(file.getCanonicalPath());
}
}
}
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
return collectionFilesList;
}
//checks whether the file is in the duration(days) specified by the user
//value of diff = 0 indicates current day
private static boolean isFileModifiedInCollectionPeriod(File file){
long diff = m_currentTimeMillis - file.lastModified();
if(diff >= 0) {
return TimeUnit.MILLISECONDS.toDays(diff)+1 <= m_config.days;
}
return false;
}
public static void resetCurrentDay() {
m_currentTimeMillis = System.currentTimeMillis();
}
private static void generateCollection(Set<String> paths) {
try {
TimestampType ts = new TimestampType(new java.util.Date());
String timestamp = ts.toString().replace(' ', '-').replace(':', '-');
// get rid of microsecond part
timestamp = timestamp.substring(0, "YYYY-mm-DD-HH-MM-ss".length());
m_zipFolderBase = (m_config.prefix.isEmpty() ? "" : m_config.prefix + "_") +
CoreUtils.getHostnameOrAddress() + ZIP_ENTRY_FOLDER_BASE_SUFFIX + timestamp;
String folderPath = m_zipFolderBase + File.separator;
String collectionFilePath = m_config.outputFile;
FileOutputStream collectionStream = new FileOutputStream(collectionFilePath);
ZipOutputStream zipStream = new ZipOutputStream(collectionStream);
Map<String, Integer> pathCounter = new HashMap<String, Integer>();
// Collect files with paths indicated in the list
for (String path: paths) {
// Skip particular items corresponding to temporary files that are only generated during collecting
if (Arrays.asList(cmdFilenames).contains(path.split(" ")[0])) {
continue;
}
File file = new File(path);
String filename = file.getName();
String entryPath = file.getName();
for (String logPath: m_logPaths) {
if (filename.startsWith(new File(logPath).getName())) {
entryPath = "voltdb_logs" + File.separator + file.getName();
break;
}
}
if (filename.startsWith("voltdb_crash")) {
entryPath = "voltdb_crashfiles" + File.separator + file.getName();
}
if (filename.startsWith("syslog") || filename.equals("dmesg") || filename.equals("systemcheck") ||
filename.startsWith("hs_err_pid") || path.startsWith("/var/log/")) {
entryPath = "system_logs" + File.separator + file.getName();
}
if (filename.equals("deployment.xml")
|| filename.equals("catalog.jar")
|| filename.equals("config.json")
|| filename.equals("path.properties")
|| filename.equals("cluster.properties")) {
entryPath = "voltdb_files" + File.separator + file.getName();
}
if (filename.endsWith(".hprof")) {
entryPath = "heap_dumps" + File.separator + file.getName();
}
if (file.isFile() && file.canRead() && file.length() > 0) {
String zipPath = folderPath + entryPath;
System.out.println(zipPath + "...");
if (pathCounter.containsKey(zipPath)) {
Integer pathCount = pathCounter.get(zipPath);
pathCounter.put(zipPath, pathCount + 1);
zipPath = zipPath.concat("(" + pathCount.toString() + ")");
} else {
pathCounter.put(zipPath, 1);
}
ZipEntry zEntry= new ZipEntry(zipPath);
zipStream.putNextEntry(zEntry);
FileInputStream in = new FileInputStream(path);
int len;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
zipStream.write(buffer, 0, len);
}
in.close();
zipStream.closeEntry();
}
}
String duCommand = m_systemStats.getProperty("dudata");
if (duCommand != null) {
String[] duVoltdbrootCmd = {"bash", "-c", duCommand + " " + m_config.voltdbroot};
cmd(zipStream, duVoltdbrootCmd, folderPath + "system_logs" + File.separator, "duvoltdbrootdata");
String drOverflowPath = m_config.voltdbroot + File.separator + "dr_overflow";
String exportOverflowPath = m_config.voltdbroot + File.separator + "export_overflow";
String commandLogPath = m_config.voltdbroot + File.separator + "command_log";
String commandLogSnapshotPath = m_config.voltdbroot + File.separator + "command_log_snapshot";
if (m_pathPropertiesPath != null && !m_pathPropertiesPath.trim().isEmpty()
&& (new File(m_pathPropertiesPath)).exists()) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(m_pathPropertiesPath);
prop.load(input);
} catch (IOException excp) {
System.err.println(excp.getMessage());
}
if (!prop.isEmpty()) {
String cmdLogPropPath = prop.getProperty(NodeSettings.CL_PATH_KEY, null);
if (cmdLogPropPath != null && !cmdLogPropPath.trim().isEmpty()) {
commandLogPath = cmdLogPropPath;
}
String cmdLogSnapshotPropPath = prop.getProperty(NodeSettings.CL_SNAPSHOT_PATH_KEY, null);
if (cmdLogSnapshotPropPath != null && !cmdLogSnapshotPropPath.trim().isEmpty()) {
commandLogSnapshotPath = cmdLogSnapshotPropPath;
}
String drOverflowPropPath = prop.getProperty(NodeSettings.DR_OVERFLOW_PATH_KEY, null);
if (drOverflowPropPath != null && !drOverflowPropPath.trim().isEmpty()) {
drOverflowPath = drOverflowPropPath;
}
String exportOverflowPropPath = prop.getProperty(NodeSettings.EXPORT_OVERFLOW_PATH_KEY, null);
if (exportOverflowPropPath != null && !exportOverflowPropPath.trim().isEmpty()) {
exportOverflowPath = exportOverflowPropPath;
}
}
}
String[] duDrOverflowCmd = {"bash", "-c", duCommand + " " + drOverflowPath};
cmd(zipStream, duDrOverflowCmd, folderPath + "system_logs" + File.separator, "dudroverflowdata");
String[] duExportOverflowCmd = {"bash", "-c", duCommand + " " + exportOverflowPath};
cmd(zipStream, duExportOverflowCmd, folderPath + "system_logs" + File.separator, "duexportoverflowdata");
String[] duCommadLodCmd = {"bash", "-c", duCommand + " " + commandLogPath};
cmd(zipStream, duCommadLodCmd, folderPath + "system_logs" + File.separator, "ducommandlog");
String[] commandLogSnapshotCmd = {"bash", "-c", duCommand + " " + commandLogSnapshotPath};
cmd(zipStream, commandLogSnapshotCmd, folderPath + "system_logs" + File.separator, "ducommandlogsnapshot");
}
for (String fileName : m_systemStats.stringPropertyNames()) {
String[] statsCmd = {"bash", "-c", m_systemStats.getProperty(fileName)};
cmd(zipStream, statsCmd, folderPath + "system_logs" + File.separator, fileName);
}
zipStream.close();
long sizeInByte = new File(collectionFilePath).length();
String sizeStringInKB = String.format("%5.2f", (double)sizeInByte / 1000);
System.out.println("\nCollection file created in " + collectionFilePath + "; file size: " + sizeStringInKB + " KB");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static void cmd(ZipOutputStream zipStream, String[] command, String folderPath, String resFilename)
throws IOException, ZipException {
System.out.println(folderPath + resFilename + "...");
File tempFile = File.createTempFile(resFilename, null);
tempFile.deleteOnExit();
Process p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader ereader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
// If we dont have anything in stdout look in stderr.
if (tempFile.length() <= 0) {
if (ereader != null) {
while ((line = ereader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
}
}
writer.close();
if (tempFile.length() > 0) {
ZipEntry zEntry= new ZipEntry(folderPath + resFilename);
zipStream.putNextEntry(zEntry);
FileInputStream in = new FileInputStream(tempFile);
int len;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
zipStream.write(buffer, 0, len);
}
in.close();
zipStream.closeEntry();
}
}
}
| agpl-3.0 |
quikkian-ua-devops/will-financials | kfs-core/src/main/java/org/kuali/kfs/fp/document/validation/impl/CreditCardReceiptDocumentTotalValidation.java | 3058 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.fp.document.validation.impl;
import org.kuali.kfs.fp.document.CreditCardReceiptDocument;
import org.kuali.kfs.krad.util.GlobalVariables;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.document.validation.GenericValidation;
import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent;
/**
* Validation which tests that the amount in credit card lines equals the amount in accounting lines
* on the document.
*/
public class CreditCardReceiptDocumentTotalValidation extends GenericValidation {
private CreditCardReceiptDocument creditCardReceiptDocumentForValidation;
/**
* For Credit Card Receipt documents, the document is balanced if the sum total of credit card receipts equals the sum total of
* the accounting lines.
*
* @see org.kuali.kfs.sys.document.validation.Validation#validate(org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent)
*/
public boolean validate(AttributedDocumentEvent event) {
// make sure the document is in balance
boolean isValid = creditCardReceiptDocumentForValidation.getSourceTotal().equals(creditCardReceiptDocumentForValidation.getTotalDollarAmount());
if (!isValid) {
GlobalVariables.getMessageMap().putError(KFSPropertyConstants.NEW_CREDIT_CARD_RECEIPT, KFSKeyConstants.CreditCardReceipt.ERROR_DOCUMENT_CREDIT_CARD_RECEIPT_OUT_OF_BALANCE);
}
return isValid;
}
/**
* Gets the creditCardReceiptDocumentForValidation attribute.
*
* @return Returns the creditCardReceiptDocumentForValidation.
*/
public CreditCardReceiptDocument getCreditCardReceiptDocumentForValidation() {
return creditCardReceiptDocumentForValidation;
}
/**
* Sets the creditCardReceiptDocumentForValidation attribute value.
*
* @param creditCardReceiptDocumentForValidation The creditCardReceiptDocumentForValidation to set.
*/
public void setCreditCardReceiptDocumentForValidation(CreditCardReceiptDocument creditCardReceiptDocumentForValidation) {
this.creditCardReceiptDocumentForValidation = creditCardReceiptDocumentForValidation;
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_cms_assemble_control/src/main/java/com/x/cms/assemble/control/jaxrs/permission/ExceptionAppInfoPermissionSave.java | 390 | package com.x.cms.assemble.control.jaxrs.permission;
import com.x.base.core.project.exception.LanguagePromptException;
class ExceptionAppInfoPermissionSave extends LanguagePromptException {
private static final long serialVersionUID = 1859164370743532895L;
ExceptionAppInfoPermissionSave( Throwable e, String id ) {
super( "保存栏目权限时发生异常。ID:{}" ,id, e );
}
}
| agpl-3.0 |
martinbaker/euclideanspace | com.euclideanspace.spad.builder/src/com/euclideanspace/spad/builder/FileContentBuffer.java | 1832 | /* Copyright 2012 Martin John Baker
*
* This file is part of EuclideanSpace.
*
* EuclideanSpace 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.
*
* EuclideanSpace 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 EuclideanSpace. If not, see <http://www.gnu.org/licenses/>.
*/
package com.euclideanspace.spad.builder;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
/**
* @author Martin John Baker
*/
public class FileContentBuffer extends InputStream {
/**
* holds the data
*/
LinkedList<String> data = new LinkedList<String>();
/**
* line currently being read
*/
byte[] currentLine = null;
/**
* pointer to position in line currently being read
*/
int lineIndex = 0;
public FileContentBuffer(){
}
/**
* required for InputStream which is used by file.create in close
*/
@Override
public int read() throws IOException {
if (currentLine == null) {
if (data.isEmpty()) return -1;
currentLine = data.removeFirst().getBytes();
lineIndex = 0;
}
int val = currentLine[lineIndex++];
if (lineIndex >= currentLine.length) {
currentLine = null;
}
return val;
}
public void write(String line){
data.addLast(line);
}
/**
* close is not needed.
*/
/*public void close(){
System.err.println("FileContentBuffer.close():" + name);
}*/
}
| agpl-3.0 |
jburnim/GreasySpoon | src/tools/httpserver/custom/ScriptList.java | 17639 | /**----------------------------------------------------------------------------
* GreasySpoon
* Copyright (C) 2008 Karel Mittig
*-----------------------------------------------------------------------------
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Please refer to the LICENSE.txt file that comes along with this source file
* or to http://www.gnu.org/licenses/gpl.txt for a full version of the license.
*
*-----------------------------------------------------------------------------
* For any comment, question, suggestion, bugfix or code contribution please
* contact Karel Mittig : karel [dot] mittig [at] gmail [dot] com
*-----------------------------------------------------------------------------*/
package tools.httpserver.custom;
///////////////////////////////////
//Import
import icap.services.resources.gs.JavaSpoonScript;
import icap.services.resources.gs.SpoonScript;
import icap.core.Icap;
import java.io.*;
import java.util.*;
import javax.script.*;
import tools.httpserver.HttpConstants;
import tools.httpserver.TextTools;
import tools.httpserver.User;
import org.apache.commons.lang.StringEscapeUtils;
///////////////////////////////////
/**
* HTML manipulation dedicated to GreasySpon service.<br>
* Generate HTML tags for GreasySpoon scripts list.<br>
* Replace <!--content--> tag by generated HMTL list.
*/
public class ScriptList implements HttpConstants{
/** String used to indicate events*/
private static String comment = "";
/** String used to indicate errors*/
private static String error = "";
//public static ScriptList self;
// <------------------------------------------------------------------------------------------>
/**
* Insert Scripts list into given HTML page
* @param content The HTML page to update
* @param requestmode Set if page is listing request mode script or not (if not, means response scripts)
* @param user User who made the request
* @return the updated HTML page
*/
public static String setScripts(String content, boolean requestmode, User user){
StringBuilder sb = new StringBuilder();
SpoonScript script;
SpoonScript[] scripts;
if (requestmode) scripts = icap.services.GreasySpoon.reqSpoonScripts;
else scripts = icap.services.GreasySpoon.respSpoonScripts;
int counter = -1;
for (int i=0; i<scripts.length; i++){
script = scripts[i];
counter++;
if (script.getPendingErrors().length()!=0){
error+=StringEscapeUtils.escapeHtml(script.getPendingErrors()).replace("\n", "<br />")+"<br />";
}
sb.append("<tr class=\"tablecontent\">\r\n");
//del checkbox
sb.append("<td><input name=\"delete_").append(script.getFile().getName().toLowerCase()).append("\"");
if (!allowed(user.getRights(), script.getRights()))sb.append(" disabled");
sb.append(" value=\"").append(script.getScriptName().toLowerCase())
.append("\" type=\"checkbox\"></td>\r\n");
//enabled checkbox
sb.append("<td><input name=\"enable_").append(script.getFile().getName().toLowerCase()).append("\"");
if (user.getRights()==RIGHTS.NONE) sb.append(" disabled");
sb.append(" value=\"")
.append(script.getScriptName().toLowerCase()).append("\" type=\"checkbox\"")
.append(script.getStatus()?"CHECKED":"").append("></td>\r\n");
//edit link
sb.append("<td><a name=\"").append(script.getScriptName()).append("\" href=\"editfile.html?filename=")
.append(TextTools.utf8ToHex(script.getFile().getAbsolutePath()).replace(" ", "+"))
.append("\">Edit</a></td>\r\n");
// rule number
sb.append("<td>").append(counter).append("</td>\r\n");
//name
sb.append("<td>").append(script.getScriptName()).append("</td>\r\n");
//language
sb.append("<td>").append(script.getLanguage()).append("</td>\r\n");
//description
sb.append("<td>").append(script.getDescription()).append("</td>\r\n");
}
content = content.replace("<!--content-->", sb.toString());
content = content.replace("<!-- comment -->", comment);
content = content.replace("<!-- error -->", error);
comment = ""; error = "";
return content;
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* Check if user rights are enough to manipulate file
* @param userrights User rights
* @param filerights File attached rights
* @return true if user is allowed to manipulate file
*/
public static boolean allowed(RIGHTS userrights, RIGHTS filerights){
if (userrights==RIGHTS.NONE) return false;
if (userrights==RIGHTS.ADMIN) return true;
if (userrights==filerights) return true;
if (filerights==RIGHTS.ADMIN) return false;
if (filerights==RIGHTS.NONE && userrights==RIGHTS.USER) return true;
return false;
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* @return number of REQMOD scripts
*/
public static int getReqmodScriptsNumber(){
return icap.services.GreasySpoon.reqSpoonScripts.length;
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* @return number of RESPMOD scripts
*/
public static int getRespmodScriptsNumber(){
return icap.services.GreasySpoon.respSpoonScripts.length;
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* Check pending errors for given script
* @param filename The script filename (as stored on disk) to check
* @return Pending error or empty script if none
*/
public static String checkScriptErrors(String filename){
SpoonScript script;
try{
File scriptfile = new File(filename);
Vector<SpoonScript> scripts = new Vector<SpoonScript>(Arrays.asList(icap.services.GreasySpoon.reqSpoonScripts));
scripts.addAll(Arrays.asList(icap.services.GreasySpoon.respSpoonScripts));
for (int i=0; i<scripts.size(); i++){
script = scripts.elementAt(i);
if (script.getFile().equals(scriptfile)){
return script.getPendingErrors();
}
}
}catch (Exception e){
//e.printStackTrace();
}
return "";
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* Force script refresh
* @param filename The script to reload
* @return Pending error(s) if any, empty string otherwise
*/
public static String refreshScript(String filename){
SpoonScript script;
try{
File scriptfile = new File(filename);
Vector<SpoonScript> scripts = new Vector<SpoonScript>(Arrays.asList(icap.services.GreasySpoon.reqSpoonScripts));
scripts.addAll(Arrays.asList(icap.services.GreasySpoon.respSpoonScripts));
for (int i=0; i<scripts.size(); i++){
script = scripts.elementAt(i);
if (script.getFile().equals(scriptfile)){
script.refresh();
return script.getPendingErrors();
}
}
}catch (Exception e){
return e.getLocalizedMessage();
}
return "";
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* @return Shared cache Information
*/
public static String getSharedCacheInfo(){
int sharedcacheSize = SpoonScript.getSharedCacheSize();
return ""+sharedcacheSize;
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* Update GreasySpoon service scripts based on provided parameters
* @param params_values String table with each line composed of "param=value"
* @param requestmode Set if information concerns REQMOD scripts or not (if not, means RESPMOD scripts)
*/
public static void update(String[] params_values, boolean requestmode){
Hashtable<String, String> table = new Hashtable<String, String>();
for (String s:params_values){
String[] values = s.split("=");
if (values.length==1) {
table.put(values[0], "");
} else if (values.length==2){
values[0] = values[0].replace("+", " ");
table.put(values[0], values[1] );
}
}
Vector<SpoonScript> todelete = new Vector<SpoonScript>();
Vector<SpoonScript> scripts = new Vector<SpoonScript>(Arrays.asList(
requestmode? icap.services.GreasySpoon.reqSpoonScripts
:icap.services.GreasySpoon.respSpoonScripts));
boolean deleted = false;
for (SpoonScript script:scripts){
String name = script.getFile().getName().toLowerCase();
if (table.get("delete_"+name)!=null){
todelete.add(script);
deleted = true;
continue;
}
boolean newstatus = false;
if (table.get("enable_"+name)!=null){
newstatus = true;
}
if (script.getStatus()!=newstatus){
script.setStatus(newstatus);
script.saveWithNewStatus();
}
}
for (SpoonScript script:todelete){
scripts.remove(script);
script.getFile().delete();
if (script.getFile().getName().endsWith(".java")){
String classname = script.getFile().getParent() +"/nativejava/" + ((JavaSpoonScript)script).getInternalName() + ".class";
new File(classname).delete();
}
}
if (deleted){
if (requestmode) {
icap.services.GreasySpoon.reqSpoonScripts = scripts.toArray(new SpoonScript[0]);
} else {
icap.services.GreasySpoon.respSpoonScripts = scripts.toArray(new SpoonScript[0]);
}
}
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* Insert info to create a new script into HTML page
* @param content HTML page to update
* @return HTML page updated with script creation menu
*/
public static String newScript(String content){
content = content.replace("<!-- comment -->", comment);
content = content.replace("<!-- error -->", error);
comment = ""; error = "";
Vector<String[]> engines = getScriptEngines();
StringBuilder listlanguague=new StringBuilder();
for (int i=0; i<engines.size();i++){
if (engines.elementAt(i)[0].equalsIgnoreCase("xslt") || engines.elementAt(i)[0].equalsIgnoreCase("xpath")){
listlanguague.append("<option class=\"item\" title=\"script.language\" value=\"")
.append(engines.elementAt(i)[0]).append("\">")
.append(engines.elementAt(i)[0]).append("</option>\r\n");
} else {
listlanguague.append("<option class=\"item\" title=\"script.language\" value=\"")
.append(engines.elementAt(i)[0]).append("\">")
.append(engines.elementAt(i)[1])
.append("</option>\r\n");
}
}
content = content.replace("<!--languagelist-->",listlanguague.toString());
return content;
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* Create a new empty SpoonScript file using provided parameters
* @param params_values parameters to use for file creation (table containing "param=value" strings)
* @param type Set if script concerns REQMOD or RESPMOD
* @param user User who generates the request
* @return Action to do after: edit the new file if all is ok, return error otherwise
*/
public static String create(String[] params_values, Icap.TYPE type, User user){
String name = null;
String language = null;
for (String s:params_values){
String[] values = s.split("=");
if (values.length!=2) continue;
if (values[0].equals("script.name")) name = values[1].replace("+"," ").trim();
if (values[0].equals("script.language")) language= TextTools.hexToUTF8(values[1]).trim();
}
if (name == null || language == null){
error = "Invalid script name or language";
return "";
}
SpoonScript[] scripts = type==Icap.TYPE.REQMOD?icap.services.GreasySpoon.reqSpoonScripts:icap.services.GreasySpoon.respSpoonScripts;
for (SpoonScript script:scripts){
if (script.getScriptName().equalsIgnoreCase(name)){
error = "A script with this name already exists.";
return "";
}
}
ScriptEngineFactory factory = null;
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
for (ScriptEngineFactory factories : scriptEngineManager.getEngineFactories()){
if (factories.getEngineName().equalsIgnoreCase(language)){
factory = factories;
break;
}
}
String factorylanguage;
String extension;
if (factory==null){
if (language.equals("java")){
factorylanguage = "java";
extension = "java";
} else {
error = "Provided language cannot be founded.";
return "";
}
} else {
factorylanguage = factory.getLanguageName();
extension = factory.getExtensions().get(0);
}
String scriptdirectory = icap.services.GreasySpoon.scriptsDirectory;
String commentstring= icap.services.GreasySpoon.languageComments.getProperty(factorylanguage,"//").trim();
String tag;
if (type == Icap.TYPE.REQMOD){
tag = icap.services.GreasySpoon.greasySpoonReqTag;
} else {
tag = icap.services.GreasySpoon.greasySpoonRespTag;
}
String filecomment = SpoonScript.getScriptSkeleton(type, extension,commentstring);
String filename = scriptdirectory+File.separator+name.replace(" ", "_").replace("%20", "_")+tag+extension;
SpoonScript.save(filename, filecomment.replace("%name%", name), user.getRights());
icap.services.GreasySpoon.forceReload();
return "edit="+filename;
}
// <------------------------------------------------------------------------------------------>
// <------------------------------------------------------------------------------------------>
/**
* @return a vector containing Scriptengines names and associated languages
*/
public static Vector<String[]> getScriptEngines(){
Vector<String[]> vector = new Vector<String[]>();
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
for (ScriptEngineFactory factories : scriptEngineManager.getEngineFactories()){
boolean inserted = false;
for (int i=0; i<vector.size(); i++){
String[] s = vector.elementAt(i);
if (s[0].compareToIgnoreCase(factories.getEngineName())>0){
vector.insertElementAt(new String[]{factories.getEngineName(),factories.getLanguageName()}, i);
inserted = true;
break;
}
}
if (!inserted) vector.add(new String[]{factories.getEngineName(),factories.getLanguageName()});
}
if (javax.tools.ToolProvider.getSystemJavaCompiler()!=null){
vector.add(new String[]{"java","java"});
}
return vector;
}
// <------------------------------------------------------------------------------------------>
}
| agpl-3.0 |
JayAvery/geomastery | src/java/jayavery/geomastery/main/GeoBlocks.java | 21755 | /*******************************************************************************
* Copyright (C) 2017 Jay Avery
*
* This file is part of Geomastery. Geomastery is free software: distributed
* under the GNU Affero General Public License (<http://www.gnu.org/licenses/>).
******************************************************************************/
package jayavery.geomastery.main;
import java.util.Set;
import com.google.common.collect.Sets;
import jayavery.geomastery.blocks.BlockAntler;
import jayavery.geomastery.blocks.BlockBeam;
import jayavery.geomastery.blocks.BlockBed;
import jayavery.geomastery.blocks.BlockBeehive;
import jayavery.geomastery.blocks.BlockBuildingAbstract;
import jayavery.geomastery.blocks.BlockCarcass;
import jayavery.geomastery.blocks.BlockContainerFacing;
import jayavery.geomastery.blocks.BlockContainerMulti;
import jayavery.geomastery.blocks.BlockContainerSingle;
import jayavery.geomastery.blocks.BlockCrop;
import jayavery.geomastery.blocks.BlockCropBlockfruit;
import jayavery.geomastery.blocks.BlockCropHarvestable;
import jayavery.geomastery.blocks.BlockDoor;
import jayavery.geomastery.blocks.BlockFlatroof;
import jayavery.geomastery.blocks.BlockFruit;
import jayavery.geomastery.blocks.BlockHarvestableLeaves;
import jayavery.geomastery.blocks.BlockLadder;
import jayavery.geomastery.blocks.BlockLight;
import jayavery.geomastery.blocks.BlockMushroombaby;
import jayavery.geomastery.blocks.BlockPitchroof;
import jayavery.geomastery.blocks.BlockRiceBase;
import jayavery.geomastery.blocks.BlockRiceTop;
import jayavery.geomastery.blocks.BlockRubble;
import jayavery.geomastery.blocks.BlockSawpit;
import jayavery.geomastery.blocks.BlockSeedling;
import jayavery.geomastery.blocks.BlockSlab;
import jayavery.geomastery.blocks.BlockSolid;
import jayavery.geomastery.blocks.BlockStairsComplex;
import jayavery.geomastery.blocks.BlockStairsStraight;
import jayavery.geomastery.blocks.BlockTar;
import jayavery.geomastery.blocks.BlockVault;
import jayavery.geomastery.blocks.BlockVaultDoubling;
import jayavery.geomastery.blocks.BlockWall;
import jayavery.geomastery.blocks.BlockWallComplex;
import jayavery.geomastery.blocks.BlockWallFence;
import jayavery.geomastery.blocks.BlockWallHeaping;
import jayavery.geomastery.blocks.BlockWallLog;
import jayavery.geomastery.blocks.BlockWallThin;
import jayavery.geomastery.blocks.BlockWindow;
import jayavery.geomastery.blocks.BlockWood;
import jayavery.geomastery.items.ItemPlacing;
import jayavery.geomastery.utilities.BlockMaterial;
import jayavery.geomastery.utilities.EBlockWeight;
import jayavery.geomastery.utilities.EToolType;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.BlockFluidBase;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
/** Stores and registers all new Geomastery blocks. */
public class GeoBlocks {
/** All new blocks. */
public static final Set<Block> BLOCKS = Sets.newHashSet();
/** Items which are restricted to the offhand slot. */
private static final Set<Item> OFFHAND_ONLY = Sets.newHashSet();
/** Leaves which need to set transparency. */
public static final Set<BlockHarvestableLeaves> LEAVES = Sets.newHashSet();
/** Blockfruit crops which need custom state mapper. */
public static final Set<BlockCropBlockfruit> CROP_BLOCKFRUIT = Sets.newHashSet();
/** All blocks which have delayed baking models. */
public static final Set<Block> DELAYED_BAKE = Sets.newHashSet();
/** Straight walls which need delayed baking models. */
public static final Set<BlockWall> RENDER_STRAIGHT = Sets.newHashSet();
/** Complex walls which need delayed baking models. */
public static final Set<BlockWall> RENDER_COMPLEX = Sets.newHashSet();
/** Single walls which need delayed baking models. */
public static final Set<BlockWall> RENDER_SINGLE = Sets.newHashSet();
/** Heaping walls which need delayed baking mdoels. */
public static final Set<BlockWall> RENDER_HEAPING = Sets.newHashSet();
// Fluids
public static Fluid tarFluid = new Fluid("fluid_tar", new ResourceLocation(Geomastery.MODID, "blocks/liquids/tar_still"), new ResourceLocation(Geomastery.MODID, "blocks/liquids/tar_flowing")).setViscosity(10000);
public static BlockFluidBase tar;
// Beds
public static final BlockBed BED_LEAF = makeItemBuilding(new BlockBed.Leaf(), true);
public static final BlockBed BED_COTTON = makeItemBuilding(new BlockBed.Cotton(), true);
public static final BlockBed BED_WOOL = makeItemBuilding(new BlockBed.Wool(), true);
public static final BlockBed BED_SIMPLE = makeItemBuilding(new BlockBed.Simple(), true);
// Antler
public static final Block ANTLER = makeItemless(new BlockAntler());
// Beehive
public static final BlockBeehive BEEHIVE = makeItemBlock(new BlockBeehive());
// Carcasses
public static final BlockCarcass CARCASS_CHICKEN = makeItemBuilding(new BlockCarcass.Chicken());
public static final BlockCarcass CARCASS_COWPART = makeItemBuilding(new BlockCarcass.Cowpart(), true);
public static final BlockCarcass CARCASS_PIG = makeItemBuilding(new BlockCarcass.Pig(), true);
public static final BlockCarcass CARCASS_SHEEP = makeItemBuilding(new BlockCarcass.Sheep(), true);
public static final BlockCarcass CARCASS_RABBIT = makeItemBuilding(new BlockCarcass.Rabbit());
// Multiblock complex devices
public static final BlockContainerMulti.Candlemaker CRAFTING_CANDLEMAKER = makeItemBuilding(new BlockContainerMulti.Candlemaker(), true);
public static final BlockContainerMulti.Forge CRAFTING_FORGE = makeItemBuilding(new BlockContainerMulti.Forge(), true);
public static final BlockContainerMulti.Mason CRAFTING_MASON = makeItemBuilding(new BlockContainerMulti.Mason(), true);
public static final BlockContainerMulti.Textiles CRAFTING_TEXTILES = makeItemBuilding(new BlockContainerMulti.Textiles(), true);
public static final BlockContainerMulti.Woodworking CRAFTING_WOODWORKING = makeItemBuilding(new BlockContainerMulti.Woodworking(), true);
public static final BlockContainerMulti.Armourer CRAFTING_ARMOURER = makeItemBuilding(new BlockContainerMulti.Armourer(), true);
public static final BlockSawpit CRAFTING_SAWPIT = makeItemBuilding(new BlockSawpit(), true);
public static final BlockContainerMulti.Clay FURNACE_CLAY = makeItemBuilding(new BlockContainerMulti.Clay(), true);
public static final BlockContainerMulti.Stone FURNACE_STONE = makeItemBuilding(new BlockContainerMulti.Stone(), true);
// Single complex blocks
public static final BlockBuildingAbstract<?> CRAFTING_KNAPPING = makeItemBuilding(new BlockContainerSingle.Knapping());
public static final BlockBuildingAbstract<?> DRYING = makeItemBuilding(new BlockContainerSingle.Drying());
public static final BlockBuildingAbstract<?> COMPOSTHEAP = makeItemBuilding(new BlockContainerFacing.Compostheap(), true);
public static final BlockBuildingAbstract<?> FURNACE_CAMPFIRE = makeItemBuilding(new BlockContainerSingle.Campfire());
public static final BlockBuildingAbstract<?> FURNACE_POTFIRE = makeItemBuilding(new BlockContainerSingle.Potfire());
public static final BlockBuildingAbstract<?> CHEST = makeItemBuilding(new BlockContainerFacing.Chest());
public static final BlockBuildingAbstract<?> BASKET = makeItemBuilding(new BlockContainerSingle.Basket());
public static final BlockBuildingAbstract<?> BOX = makeItemBuilding(new BlockContainerSingle.Box());
// Lights
public static final BlockBuildingAbstract<?> CANDLE_BEESWAX = makeItemBuilding(new BlockLight.Candle("candle_beeswax", 0.005F, 15));
public static final BlockBuildingAbstract<?> CANDLE_TALLOW = makeItemBuilding(new BlockLight.Candle("candle_tallow", 0.02F, 15));
public static final BlockBuildingAbstract<?> TORCH_TALLOW = makeItemBuilding(new BlockLight.Torch("torch_tallow", 0.005F, 4));
public static final BlockBuildingAbstract<?> TORCH_TAR = makeItemBuilding(new BlockLight.Torch("torch_tar", 0.02F, 4));
public static final BlockBuildingAbstract<?> LAMP_CLAY = makeItemBuilding(new BlockLight.Lamp("lamp_clay", 4));
// Single crops
public static final BlockCrop CHICKPEA = makeItemless(new BlockCrop.Chickpea());
public static final BlockCrop COTTON = makeItemless(new BlockCrop.Cotton());
public static final BlockCrop HEMP = makeItemless(new BlockCrop.Hemp());
public static final BlockCrop PEPPER = makeItemless(new BlockCrop.Pepper());
public static final BlockCrop WHEAT = makeItemless(new BlockCrop.Wheat());
public static final BlockCrop CARROT = makeItemless(new BlockCrop.Carrot());
public static final BlockCrop POTATO = makeItemless(new BlockCrop.Potato());
public static final BlockCrop BEETROOT = makeItemless(new BlockCrop.Beetroot());
// Harvestable crops
public static final BlockCropHarvestable BERRY = makeItemless(new BlockCropHarvestable.Berry());
public static final BlockCropHarvestable BEAN = makeItemless(new BlockCropHarvestable.Bean());
public static final BlockCropHarvestable TOMATO = makeItemless(new BlockCropHarvestable.Tomato());
// Blockfruit crops
public static final BlockCropBlockfruit MELON_CROP = makeItemless(new BlockCropBlockfruit.Melon(), CROP_BLOCKFRUIT);
public static final BlockCropBlockfruit PUMPKIN_CROP = makeItemless(new BlockCropBlockfruit.Pumpkin(), CROP_BLOCKFRUIT);
// Block fruits
public static final BlockFruit MELON_FRUIT = makeItemBlock(new BlockFruit("melon_fruit", () -> GeoItems.MELON, () -> GeoItems.SEED_MELON));
public static final BlockFruit PUMPKIN_FRUIT = makeItemBlock(new BlockFruit("pumpkin_fruit", () -> GeoItems.PUMPKIN, () -> GeoItems.SEED_PUMPKIN));
// Rice
public static final Block RICE_BASE = makeItemless(new BlockRiceBase());
public static final Block RICE_TOP = makeItemless(new BlockRiceTop());
// Baby mushrooms
public static final Block MUSHROOMBABY_BROWN = makeItemless(new BlockMushroombaby("mushroombaby_brown", () -> Blocks.BROWN_MUSHROOM));
public static final Block MUSHROOMBABY_RED = makeItemless(new BlockMushroombaby("mushroombaby_red", () -> Blocks.RED_MUSHROOM));
// Seedlings
public static final BlockSeedling SEEDLING_APPLE = makeItemBlock(new BlockSeedling.Apple());
public static final BlockSeedling SEEDLING_PEAR = makeItemBlock(new BlockSeedling.Pear());
public static final BlockSeedling SEEDLING_ORANGE = makeItemBlock(new BlockSeedling.Orange());
public static final BlockSeedling SEEDLING_BANANA = makeItemBlock(new BlockSeedling.Banana());
// Leaves
public static final BlockHarvestableLeaves LEAF_APPLE = makeItemBlock(new BlockHarvestableLeaves("leaf_apple", () -> GeoItems.APPLE, () -> SEEDLING_APPLE, 0.05F), LEAVES);
public static final BlockHarvestableLeaves LEAF_BANANA = makeItemBlock(new BlockHarvestableLeaves("leaf_banana", () -> GeoItems.BANANA, () -> SEEDLING_BANANA, 0.15F), LEAVES);
public static final BlockHarvestableLeaves LEAF_PEAR = makeItemBlock(new BlockHarvestableLeaves("leaf_pear", () -> GeoItems.PEAR, () -> SEEDLING_PEAR, 0.05F), LEAVES);
public static final BlockHarvestableLeaves LEAF_ORANGE = makeItemBlock(new BlockHarvestableLeaves("leaf_orange", () -> GeoItems.ORANGE, () -> SEEDLING_ORANGE, 0.1F), LEAVES);
// Logs
public static final Block WOOD_APPLE = makeItemBlock(new BlockWood("wood_apple", 2F));
public static final Block WOOD_BANANA = makeItemBlock(new BlockWood("wood_banana", 1F));
public static final Block WOOD_PEAR = makeItemBlock(new BlockWood("wood_pear", 2F));
public static final Block WOOD_ORANGE = makeItemBlock(new BlockWood("wood_orange", 2F));
// Ores
public static final Block LODE_AMETHYST = makeItemBlock(new BlockSolid(Material.ROCK, "lode_amethyst", 4F, () -> GeoItems.AMETHYST, 2, EToolType.PICKAXE));
public static final Block LODE_FIREOPAL = makeItemBlock(new BlockSolid(Material.ROCK, "lode_fireopal", 4F, () -> GeoItems.FIREOPAL, 5, EToolType.PICKAXE));
public static final Block LODE_RUBY = makeItemBlock(new BlockSolid(Material.ROCK, "lode_ruby", 4F, () -> GeoItems.RUBY, 3, EToolType.PICKAXE));
public static final Block LODE_SAPPHIRE = makeItemBlock(new BlockSolid(Material.ROCK, "lode_sapphire", 4F, () -> GeoItems.SAPPHIRE, 8, EToolType.PICKAXE));
public static final Block ORE_COPPER = makeItemBlock(new BlockSolid(Material.ROCK, "ore_copper", 3F, () -> GeoItems.ORE_COPPER, 1, EToolType.PICKAXE));
public static final Block ORE_SILVER = makeItemBlock(new BlockSolid(Material.ROCK, "ore_silver", 3F, () -> GeoItems.ORE_SILVER, 1, EToolType.PICKAXE));
public static final Block ORE_TIN = makeItemBlock(new BlockSolid(Material.ROCK, "ore_tin", 3F, () -> GeoItems.ORE_TIN, 1, EToolType.PICKAXE));
// Rocks
public static final Block SALT = makeItemBlock(new BlockSolid(Material.ROCK, "salt", 1F, () -> GeoItems.SALT, 1, EToolType.PICKAXE));
public static final Block CHALK = makeItemBlock(new BlockSolid(Material.ROCK, "chalk", 3F, () -> GeoItems.CHALK, 1, EToolType.PICKAXE));
public static final Block PEAT = makeItemBlock(new BlockSolid(BlockMaterial.SOIL, "peat", 0.5F, () -> GeoItems.PEAT_WET, 1, EToolType.SHOVEL));
// Rubble
public static final BlockBuildingAbstract<?> RUBBLE = makeItemBuilding(new BlockRubble());
// Walls (in rendering priority order)
public static final BlockBuildingAbstract<?> WALL_LOG = makeItemBuilding(new BlockWallLog(), RENDER_STRAIGHT, DELAYED_BAKE);
public static final BlockBuildingAbstract<?> FENCE = makeItemBuilding(new BlockWallFence(), RENDER_SINGLE, DELAYED_BAKE);
public static final BlockBuildingAbstract<?> WALL_POLE = makeItemBuilding(new BlockWallThin(BlockMaterial.WOOD_FURNITURE, "wall_pole", 2F, 180, 4), RENDER_SINGLE, DELAYED_BAKE);
public static final BlockBuildingAbstract<?> FRAME = makeItemBuilding(new BlockWallThin(BlockMaterial.WOOD_FURNITURE, "frame", 2F, 180, 6), RENDER_SINGLE, DELAYED_BAKE);
public static final BlockBuildingAbstract<?> WALL_MUD = makeItemBuilding(new BlockWallHeaping(BlockMaterial.STONE_FURNITURE, "wall_mud", 1F, 0), RENDER_HEAPING, DELAYED_BAKE);
public static final BlockBuildingAbstract<?> WALL_ROUGH = makeItemBuilding(new BlockWallHeaping(BlockMaterial.STONE_FURNITURE, "wall_rough", 1.5F, 0), RENDER_HEAPING, DELAYED_BAKE);
public static final BlockBuildingAbstract<?> WALL_BRICK = makeItemBuilding(new BlockWallComplex(BlockMaterial.STONE_FURNITURE, "wall_brick", 2F), RENDER_COMPLEX, DELAYED_BAKE);
public static final BlockBuildingAbstract<?> WALL_STONE = makeItemBuilding(new BlockWallComplex(BlockMaterial.STONE_FURNITURE, "wall_stone", 2F), RENDER_COMPLEX, DELAYED_BAKE);
// Complex stairs
public static final BlockBuildingAbstract<?> STAIRS_BRICK = makeItemBuilding(new BlockStairsComplex(BlockMaterial.STONE_FURNITURE, "stairs_brick", 3F, 2));
public static final BlockBuildingAbstract<?> STAIRS_STONE = makeItemBuilding(new BlockStairsComplex(BlockMaterial.STONE_FURNITURE, "stairs_stone", 3F, 2));
// Double joining stairs
public static final BlockBuildingAbstract<?> STAIRS_WOOD = makeItemBuilding(new BlockStairsStraight.Joining("stairs_wood", 2F, 4));
// Single stairs
public static final BlockBuildingAbstract<?> STAIRS_POLE = makeItemBuilding(new BlockStairsStraight.Single("stairs_pole", 2F, 4));
// Vaults
public static final BlockVault VAULT_BRICK = makeItemBuilding(new BlockVaultDoubling("vault_brick", EBlockWeight.HEAVY, 2));
public static final BlockVault VAULT_STONE = makeItemBuilding(new BlockVaultDoubling("vault_stone", EBlockWeight.HEAVY, 2));
public static final BlockVault VAULT_FRAME = makeItemBuilding(new BlockVault("vault_frame", BlockMaterial.WOOD_FURNITURE, EBlockWeight.LIGHT, 6));
// Doors
public static final BlockDoor DOOR_POLE = makeItemBuilding(new BlockDoor("door_pole"), true);
public static final BlockDoor DOOR_WOOD = makeItemBuilding(new BlockDoor("door_wood"), true);
// Window
public static final BlockBuildingAbstract<?> WINDOW = makeItemBuilding(new BlockWindow());
// Ladder
public static final BlockLadder LADDER = makeItemBuilding(new BlockLadder());
// Beams
public static final BlockBeam BEAM_THIN = makeItemBuilding(new BlockBeam("beam_thick", 4, 8), true, DELAYED_BAKE);
public static final BlockBeam BEAM_THICK = makeItemBuilding(new BlockBeam("beam_thin", 2, 4), true, DELAYED_BAKE);
// Slabs
public static final BlockSlab SLAB_STONE = makeItemBuilding(new BlockSlab("slab_stone"));
public static final BlockSlab SLAB_BRICK = makeItemBuilding(new BlockSlab("slab_brick"));
// Flat roofs
public static final BlockBuildingAbstract<?> FLATROOF_POLE = makeItemBuilding(new BlockFlatroof("flatroof_pole", 1F));
// Pitched roofs
public static final BlockBuildingAbstract<?> PITCHROOF_CLAY = makeItemBuilding(new BlockPitchroof(BlockMaterial.WOOD_FURNITURE, "pitchroof_clay", 2F, 4));
/** Adjusts vanilla blocks, register fluids. */
public static void preInit() {
Geomastery.LOG.info("Registering fluids");
FluidRegistry.registerFluid(tarFluid);
GameRegistry.register(tar = makeItemless(new BlockTar()));
Geomastery.LOG.info("Altering vanilla block properties");
Blocks.LOG.setHarvestLevel("axe", 1);
Blocks.LOG2.setHarvestLevel("axe", 1);
Blocks.DIRT.setHarvestLevel("shovel", 1);
Blocks.GRASS.setHarvestLevel("shovel", 1);
Blocks.SAND.setHarvestLevel("shovel", 1);
Blocks.CLAY.setHardness(1.8F).setHarvestLevel("shovel", 1);
Blocks.GRAVEL.setHarvestLevel("shovel", 1);
Blocks.COBBLESTONE.setHarvestLevel("pickaxe", 1);
Blocks.STONE.setHarvestLevel("pickaxe", 1);
Blocks.COAL_ORE.setHarvestLevel("pickaxe", 1);
Blocks.DIAMOND_ORE.setHardness(4F).setHarvestLevel("pickaxe", 1);
Blocks.EMERALD_ORE.setHardness(4F).setHarvestLevel("pickaxe", 1);
Blocks.GOLD_ORE.setHardness(3F).setHarvestLevel("pickaxe", 1);
Blocks.IRON_ORE.setHardness(3F).setHarvestLevel("pickaxe", 1);
Blocks.LAPIS_ORE.setHardness(4F).setHarvestLevel("pickaxe", 1);
Blocks.LIT_REDSTONE_ORE.setHardness(4F).setHarvestLevel("pickaxe", 1);
Blocks.REDSTONE_ORE.setHardness(4F).setHarvestLevel("pickaxe", 1);
Blocks.QUARTZ_ORE.setHarvestLevel("pickaxe", 1);
Blocks.LEAVES.setHardness(0.2F)
.setHarvestLevel(EToolType.MACHETE.name(), 1);
Blocks.REEDS.setHardness(0.2F)
.setHarvestLevel(EToolType.SICKLE.name(), 1);
}
/** Makes this item offhand only. */
public static void addOffhandOnly(Item item) {
OFFHAND_ONLY.add(item);
}
/** @return Whether this item is offhand only. */
public static boolean isOffhandOnly(Item item) {
return GeoConfig.gameplay.inventory && OFFHAND_ONLY.contains(item);
}
/** Creates an ItemBlock, adds to maps and sets as needed. */
private static <B extends Block> B makeItemBlock(B block,
int stackSize, boolean isOffhandOnly, Set<? super B>... sets) {
Item item = new ItemBlock(block).setMaxStackSize(stackSize)
.setRegistryName(block.getRegistryName());
if (isOffhandOnly) {
OFFHAND_ONLY.add(item);
}
for (Set<? super B> set : sets) {
set.add(block);
}
GeoItems.ITEMS.add(item);
BLOCKS.add(block);
return block;
}
/** Gets ItemBuilding, adds to maps and sets as needed. */
private static <B extends BlockBuildingAbstract<?>> B makeItemBuilding(
B block, boolean isOffhandOnly, Set<? super B>...sets) {
ItemPlacing item = block.getItem();
if (isOffhandOnly) {
OFFHAND_ONLY.add(item);
}
for (Set<? super B> set : sets) {
set.add(block);
}
GeoItems.ITEMS.add(item);
BLOCKS.add(block);
return block;
}
/** Adds to maps and sets as needed without any item. */
private static <B extends Block> B makeItemless(B block,
Set<? super B>... sets) {
BLOCKS.add(block);
for (Set<? super B> set : sets) {
set.add(block);
}
return block;
}
private static <B extends BlockBuildingAbstract<?>> B makeItemBuilding(
B block, Set<? super B>...sets) {
return makeItemBuilding(block, false, sets);
}
private static <B extends Block> B makeItemBlock(B block,
Set<? super B>... sets) {
return makeItemBlock(block, 1, false, sets);
}
}
| agpl-3.0 |
RestComm/jss7 | map/map-api/src/main/java/org/restcomm/protocols/ss7/map/api/service/oam/ReportAmount.java | 2120 | /*
* 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.protocols.ss7.map.api.service.oam;
/**
*
<code>
ReportAmount ::= ENUMERATED {
d1 (0),
d2 (1),
d4 (2),
d8 (3),
d16 (4),
d32 (5),
d64 (6),
infinity (7)
}
</code>
*
*
* @author sergey vetyutnev
*
*/
public enum ReportAmount {
d1(0), d2(1), d4(2), d8(3), d16(4), d32(5), d64(6), infinity(7);
private int code;
private ReportAmount(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public static ReportAmount getInstance(int code) {
switch (code) {
case 0:
return ReportAmount.d1;
case 1:
return ReportAmount.d2;
case 2:
return ReportAmount.d4;
case 3:
return ReportAmount.d8;
case 4:
return ReportAmount.d16;
case 5:
return ReportAmount.d32;
case 6:
return ReportAmount.d64;
case 7:
return ReportAmount.infinity;
default:
return null;
}
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/common/excel/writer/Excel2007WriterImpl.java | 1340 | package com.x.attendance.assemble.common.excel.writer;
public class Excel2007WriterImpl extends AbstractExcel2007Writer{
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//构建excel2007写入器
AbstractExcel2007Writer excel07Writer = new Excel2007WriterImpl();
//调用处理方法
excel07Writer.process("F://test07.xlsx");
}
/*
* 可根据需求重写此方法,对于单元格的小数或者日期格式,会出现精度问题或者日期格式转化问题,建议使用字符串插入方法
* @see com.excel.ver2.AbstractExcel2007Writer#generate()
*/
@Override
public void generate()throws Exception {
//电子表格开始
beginSheet();
for (int rownum = 0; rownum < 100; rownum++) {
//插入新行
insertRow(rownum);
//建立新单元格,索引值从0开始,表示第一列
createCell(0, "中国<" + rownum + "!");
createCell(1, 34343.123456789);
createCell(2, "23.67%");
createCell(3, "12:12:23");
createCell(4, "2010-10-11 12:12:23");
createCell(5, "true");
createCell(6, "false");
//结束行
endRow();
}
//电子表格结束
endSheet();
}
}
| agpl-3.0 |
jzinedine/CMDBuild | core/src/main/java/org/cmdbuild/logic/data/access/CMCardWithPosition.java | 310 | package org.cmdbuild.logic.data.access;
import org.cmdbuild.dao.entry.CMCard;
public class CMCardWithPosition {
final public Long position;
final public CMCard card;
public CMCardWithPosition( //
final Long position, //
final CMCard card //
) {
this.position = position;
this.card = card;
}
} | agpl-3.0 |
moskiteau/KalturaGeneratedAPIClientsJava | src/com/kaltura/client/types/KalturaRelatedFilter.java | 2107 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2015 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import org.w3c.dom.Element;
import com.kaltura.client.KalturaParams;
import com.kaltura.client.KalturaApiException;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
* @date Mon, 10 Aug 15 02:02:11 -0400
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public abstract class KalturaRelatedFilter extends KalturaFilter {
public KalturaRelatedFilter() {
}
public KalturaRelatedFilter(Element node) throws KalturaApiException {
super(node);
}
public KalturaParams toParams() {
KalturaParams kparams = super.toParams();
kparams.add("objectType", "KalturaRelatedFilter");
return kparams;
}
}
| agpl-3.0 |
bitblit11/yamcs | yamcs-api/src/main/java/org/yamcs/api/ws/WebSocketExecutionException.java | 596 | package org.yamcs.api.ws;
import org.yamcs.protobuf.Web.WebSocketServerMessage.WebSocketExceptionData;
/**
* Use by the WebSocketClient for the exceptions received via the websocket interface
* @author nm
*
*/
public class WebSocketExecutionException extends Exception {
private final WebSocketExceptionData exceptionData;
public WebSocketExecutionException(WebSocketExceptionData exceptionData) {
super(exceptionData.toString());
this.exceptionData = exceptionData;
}
public WebSocketExceptionData getExceptionData() {
return exceptionData;
}
}
| agpl-3.0 |
marioestradarosa/axelor-development-kit | axelor-core/src/main/java/com/axelor/data/xml/XMLImporter.java | 7842 | /**
* Axelor Business Solutions
*
* Copyright (C) 2012-2014 Axelor (<http://axelor.com>).
*
* 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/>.
*/
package com.axelor.data.xml;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.FlushModeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.axelor.data.ImportException;
import com.axelor.data.ImportTask;
import com.axelor.data.Importer;
import com.axelor.data.Listener;
import com.axelor.data.adapter.DataAdapter;
import com.axelor.db.JPA;
import com.axelor.db.Model;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.mapper.MapperWrapper;
/**
* XML data importer.
* <br>
* <br>
* This class also provides {@link #run(ImportTask)} method to import data programmatically.
* <br>
* <br>
* For example:
* <pre>
* XMLImporter importer = new XMLImporter("path/to/xml-config.xml");
*
* importer.runTask(new ImportTask(){
*
* public void configure() throws IOException {
* input("contacts.xml", new File("data/xml/contacts.xml"));
* input("contacts.xml", new File("data/xml/contacts2.xml"));
* }
*
* public boolean handle(ImportException e) {
* System.err.println("Import error: " + e);
* return true;
* }
* }
* </pre>
*
*/
public class XMLImporter implements Importer {
private Logger log = LoggerFactory.getLogger(getClass());
private File dataDir;
private XMLConfig config;
private Map<String, Object> context;
private List<Listener> listeners = Lists.newArrayList();
private boolean canClear = true;
@Inject
public XMLImporter(
@Named("axelor.data.config") String configFile,
@Named("axelor.data.dir") String dataDir) {
Preconditions.checkNotNull(configFile);
File file = new File(configFile);
Preconditions.checkArgument(file.isFile(), "No such file: " + configFile);
if (dataDir != null) {
File _data = new File(dataDir);
Preconditions.checkArgument(_data.isDirectory());
this.dataDir = _data;
}
this.config = XMLConfig.parse(file);
}
public XMLImporter(String configFile) {
this(configFile, null);
}
public void setContext(Map<String, Object> context) {
this.context = context;
}
private List<File> getFiles(String... names) {
List<File> all = Lists.newArrayList();
for (String name : names)
all.add(dataDir != null ? new File(dataDir, name) : new File(name));
return all;
}
public void addListener(Listener listener) {
this.listeners.add(listener);
}
public void clearListener() {
this.listeners.clear();
}
public void setCanClear(boolean canClear) {
this.canClear = canClear;
}
private int getBatchSize() {
try {
Object val = JPA.em().getEntityManagerFactory().getProperties().get("hibernate.jdbc.batch_size");
return Integer.parseInt(val.toString());
} catch (Exception e) {
}
return DEFAULT_BATCH_SIZE;
}
@Override
public void run() {
for (XMLInput input : config.getInputs()) {
String fileName = input.getFileName();
List<File> files = this.getFiles(fileName);
for(File file : files) {
try {
this.process(input, file);
} catch (Exception e) {
log.error("Error while importing {}.", file, e);
}
}
}
}
public void run(ImportTask task) {
try {
if (task.readers.isEmpty()) {
task.configure();
}
for (XMLInput input : config.getInputs()) {
for(Reader reader : task.readers.get(input.getFileName())) {
try {
process(input, reader);
} catch(ImportException e) {
if (!task.handle(e)) {
break;
}
}
}
}
} catch(IOException e) {
throw new IllegalArgumentException(e);
} finally {
task.readers.clear();
}
}
/**
* Process the data file with the given input binding.
*
* @param input input binding configuration
* @param file data file
* @throws ImportException
*/
private void process(XMLInput input, File file) throws ImportException {
try {
log.info("Importing: {}", file.getName());
this.process(input, new FileReader(file));
} catch (IOException e) {
throw new ImportException(e);
}
}
private void process(XMLInput input, Reader reader) throws ImportException {
final int batchSize = getBatchSize();
final XStream stream = new XStream(new StaxDriver()) {
private String root = null;
@Override
@SuppressWarnings("all")
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
@Override
public Class realClass(String elementName) {
if (root == null) {
root = elementName;
return Document.class;
}
return Element.class;
}
};
}
};
final XMLBinder binder = new XMLBinder(input, context) {
int count = 0;
int total = 0;
@Override
protected void handle(Object bean, XMLBind binding, Map<String, Object> ctx) {
if (bean == null) {
return;
}
try {
bean = binding.call(bean, ctx);
if (bean != null) {
bean = JPA.manage((Model) bean);
count++;
for(Listener listener : listeners) {
listener.imported((Model) bean);
}
}
} catch (Exception e) {
log.error("Unable to import object {}.", bean);
log.error("With binding {}.", binding);
log.error("With exception:", e);
// Recover the transaction
if (JPA.em().getTransaction().getRollbackOnly()) {
JPA.em().getTransaction().rollback();
}
if (!JPA.em().getTransaction().isActive()) {
JPA.em().getTransaction().begin();
}
for(Listener listener : listeners) {
listener.handle((Model) bean, e);
}
}
if (++total % batchSize == 0) {
JPA.flush();
JPA.clear();
}
}
@Override
protected void finish() {
for(Listener listener : listeners) {
listener.imported(total, count);
}
}
};
// register type adapters
for(DataAdapter adapter : defaultAdapters) {
binder.registerAdapter(adapter);
}
for(DataAdapter adapter : config.getAdapters()) {
binder.registerAdapter(adapter);
}
for(DataAdapter adapter : input.getAdapters()) {
binder.registerAdapter(adapter);
}
stream.setMode(XStream.NO_REFERENCES);
stream.registerConverter(new ElementConverter(binder));
final EntityManager em = JPA.em();
final EntityTransaction txn = em.getTransaction();
final boolean started = !txn.isActive();
if (canClear) {
em.setFlushMode(FlushModeType.COMMIT);
}
if (started) {
txn.begin();
}
try {
stream.fromXML(reader);
binder.finish();
if (txn.isActive() && started) {
txn.commit();
if (canClear) {
em.clear();
}
}
} catch (Exception e) {
if (txn.isActive() && started) {
txn.rollback();
}
throw new ImportException(e);
}
}
}
| agpl-3.0 |
OnyxDevTools/onyx-database-parent | onyx-database-examples/querying/src/main/java/com/onyxdevtools/example/querying/Main.java | 141730 | package com.onyxdevtools.example.querying;
import com.onyx.exception.OnyxException;
import com.onyx.persistence.factory.PersistenceManagerFactory;
import com.onyx.persistence.factory.impl.EmbeddedPersistenceManagerFactory;
import com.onyx.persistence.manager.PersistenceManager;
import com.onyxdevtools.example.query.KotlinQueryBuilder;
import com.onyxdevtools.example.querying.entities.*;
import java.io.File;
import java.util.Arrays;
//J-
@SuppressWarnings({"SpellCheckingInspection", "WeakerAccess"})
public class Main extends AbstractDemo
{
public static void main(final String[] args) throws OnyxException
{
final String pathToOnyxDB = System.getProperty("user.home") + File.separatorChar + ".onyxdb" + File.separatorChar + "sandbox"
+ File.separatorChar + "querying-db.oxd";
// Delete database so you have a clean slate
deleteDatabase(pathToOnyxDB);
final PersistenceManagerFactory factory = new EmbeddedPersistenceManagerFactory(pathToOnyxDB);
factory.setCredentials("onyx-user", "SavingDataIsFun!");
factory.initialize();
final PersistenceManager manager = factory.getPersistenceManager();
seedData(manager);
factory.close(); //close the factory so that we can use it again
System.out.print("\n Find Example: \n");
FindExample.demo();
System.out.print("\nFindById Example: \n");
FindByIdExample.demo();
System.out.print("\nList Example: \n");
ListExample.demo();
System.out.print("\nQuery Example: \n");
QueryExample.demo();
System.out.print("\nCompound Query Example: \n");
CompoundQueryExample.demo();
System.out.print("\nDelete Query Example: \n");
DeleteQueryExample.demo();
System.out.print("\nUpdate Query Example: \n");
UpdateQueryExample.demo();
System.out.print("\nSorting and Paging Example: \n");
SortingAndPagingExample.demo();
System.out.print("\nLazy Query Example: \n");
LazyQueryExample.demo();
System.out.println("Group By Example");
GroupByExample.demo();
System.out.println("Kotlin Query Builder Example");
KotlinQueryBuilder.demo();
}
private static void seedData(PersistenceManager manager) throws OnyxException
{
//Create league
League nfl = new League();
nfl.setName("NFL");
nfl.setDescription("National Football League");
//create a season
Season season2015 = new Season();
season2015.setYear(2015);
//add the season to the league
nfl.getSeasons().add(season2015);
//create conferences
Conference afc = new Conference();
afc.setName("AFC");
Conference nfc = new Conference();
nfc.setName("NFC");
//create divisions
Division afcNorth = new Division();
afcNorth.setName("AFC NORTH");
Division afcSouth = new Division();
afcSouth.setName("AFC SOUTH");
Division afcEast = new Division();
afcEast.setName("AFC EAST");
Division afcWest = new Division();
afcWest.setName("AFC WEST");
Division nfcNorth = new Division();
nfcNorth.setName("NFC NORTH");
Division nfcSouth = new Division();
nfcSouth.setName("NFC SOUTH");
Division nfcEast = new Division();
nfcEast.setName("NFC EAST");
Division nfcWest = new Division();
nfcWest.setName("NFC WEST");
//Add conferences to the season
season2015.getConferences().add(nfc);
season2015.getConferences().add(afc);
//Add divisions to conferences
nfc.getDivisions().add(nfcNorth);
nfc.getDivisions().add(nfcSouth);
nfc.getDivisions().add(nfcEast);
nfc.getDivisions().add(nfcWest);
afc.getDivisions().add(afcNorth);
afc.getDivisions().add(afcSouth);
afc.getDivisions().add(afcEast);
afc.getDivisions().add(afcWest);
//Create teams
Team raiders = new Team();
raiders.setTeamName("Raiders");
Team broncos = new Team();
broncos.setTeamName("Broncos");
Team chiefs = new Team();
chiefs.setTeamName("Chiefs");
Team chargers = new Team();
chargers.setTeamName("Chargers");
Team patriots = new Team();
patriots.setTeamName("Patriots");
Team bills = new Team();
bills.setTeamName("Bills");
Team jets = new Team();
jets.setTeamName("Jets");
Team dolphins = new Team();
dolphins.setTeamName("Dolphins");
Team texans = new Team();
texans.setTeamName("Texans");
Team colts = new Team();
colts.setTeamName("Colts");
Team jaguars = new Team();
jaguars.setTeamName("Jaguars");
Team titans = new Team();
titans.setTeamName("Titans");
Team steelers = new Team();
steelers.setTeamName("Steelers");
Team bengals = new Team();
bengals.setTeamName("Bengals");
Team browns = new Team();
browns.setTeamName("Browns");
Team ravens = new Team();
ravens.setTeamName("Ravens");
//NFC
Team seahawks = new Team();
seahawks.setTeamName("Seahawks");
Team rams = new Team();
rams.setTeamName("Rams");
Team niners = new Team();
niners.setTeamName("49ers");
Team cardinals = new Team();
cardinals.setTeamName("Cardinals");
Team panthers = new Team();
panthers.setTeamName("Panthers");
Team falcons = new Team();
falcons.setTeamName("Falcons");
Team buccaneers = new Team();
buccaneers.setTeamName("Buccaneers");
Team saints = new Team();
saints.setTeamName("Saints");
Team cowboys = new Team();
cowboys.setTeamName("Cowboys");
Team eagles = new Team();
eagles.setTeamName("Eagles");
Team giants = new Team();
giants.setTeamName("Giants");
Team redskins = new Team();
redskins.setTeamName("Redskins");
Team bears = new Team();
bears.setTeamName("Bears");
Team lions = new Team();
lions.setTeamName("Lions");
Team packers = new Team();
packers.setTeamName("Packers");
Team vikings = new Team();
vikings.setTeamName("Vikings");
//Add teams to divisions
afcWest.setTeams(Arrays.asList(raiders, broncos, chiefs, chargers));
afcSouth.setTeams(Arrays.asList(colts, texans, jaguars, titans));
afcEast.setTeams(Arrays.asList(patriots, bills, jets, dolphins));
afcNorth.setTeams(Arrays.asList(steelers, bengals, browns, ravens));
nfcWest.setTeams(Arrays.asList(seahawks, niners, rams, cardinals));
nfcSouth.setTeams(Arrays.asList(panthers, falcons, saints, buccaneers));
nfcEast.setTeams(Arrays.asList(cowboys, eagles, giants, redskins));
nfcNorth.setTeams(Arrays.asList(bears, lions, vikings, packers));
//Add players to each team
//AFC WEST
//Raiders
Player raidersQB = new Player();
raidersQB.setFirstName("Derick");
raidersQB.setLastName("Carr");
raidersQB.setPosition("QB");
Player raidersRB1 = new Player();
raidersRB1.setFirstName("Latavius");
raidersRB1.setLastName("Murray");
raidersRB1.setPosition("RB");
Player raidersRB2 = new Player();
raidersRB2.setFirstName("Taiwan");
raidersRB2.setLastName("Jones");
raidersRB2.setPosition("RB");
Player raidersWR1 = new Player();
raidersWR1.setFirstName("Michael");
raidersWR1.setLastName("Crabtree");
raidersWR1.setPosition("WR");
Player raidersWR2 = new Player();
raidersWR2.setFirstName("Amari");
raidersWR2.setLastName("Cooper");
raidersWR2.setPosition("WR");
//Broncos
Player broncosQB = new Player();
broncosQB.setFirstName("Payton");
broncosQB.setLastName("Manning");
broncosQB.setPosition("QB");
Player broncosRB1 = new Player();
broncosRB1.setFirstName("Ronnie");
broncosRB1.setLastName("Hillman");
broncosRB1.setPosition("RB");
Player broncosRB2 = new Player();
broncosRB2.setFirstName("C.J.");
broncosRB2.setLastName("Anderson");
broncosRB2.setPosition("RB");
Player broncosWR1 = new Player();
broncosWR1.setFirstName("Demaryius");
broncosWR1.setLastName("Thomas");
broncosWR1.setPosition("WR");
Player broncosWR2 = new Player();
broncosWR2.setFirstName("Emmanual");
broncosWR2.setLastName("Sanders");
broncosWR2.setPosition("WR");
//Cheifs
Player cheifsQB = new Player();
cheifsQB.setFirstName("Alex");
cheifsQB.setLastName("Smith");
cheifsQB.setPosition("QB");
Player cheifsRB1 = new Player();
cheifsRB1.setFirstName("Charcandrick");
cheifsRB1.setLastName("West");
cheifsRB1.setPosition("RB");
Player cheifsRB2 = new Player();
cheifsRB2.setFirstName("Spencer");
cheifsRB2.setLastName("Ware");
cheifsRB2.setPosition("RB");
Player cheifsWR1 = new Player();
cheifsWR1.setFirstName("Jeremy");
cheifsWR1.setLastName("Maclin");
cheifsWR1.setPosition("WR");
Player cheifsWR2 = new Player();
cheifsWR2.setFirstName("Albert");
cheifsWR2.setLastName("Wilson");
cheifsWR2.setPosition("WR");
//Chargers
Player chargersQB = new Player();
chargersQB.setFirstName("Phillip"); //todo, spelling
chargersQB.setLastName("Rivers");
chargersQB.setPosition("QB");
Player chargersRB1 = new Player();
chargersRB1.setFirstName("Melvin");
chargersRB1.setLastName("Gordon");
chargersRB1.setPosition("RB");
Player chargersRB2 = new Player();
chargersRB2.setFirstName("Danny");
chargersRB2.setLastName("Woodhead");
chargersRB2.setPosition("RB");
Player chargersWR1 = new Player();
chargersWR1.setFirstName("Keenan");
chargersWR1.setLastName("Allen");
chargersWR1.setPosition("WR");
Player chargersWR2 = new Player();
chargersWR2.setFirstName("Malcom");
chargersWR2.setLastName("Floyd");
chargersWR2.setPosition("WR");
raiders.setPlayers(Arrays.asList(raidersQB, raidersRB1, raidersRB2, raidersWR1, raidersWR2));
broncos.setPlayers(Arrays.asList(broncosQB, broncosRB1, broncosRB2, broncosWR1, broncosWR2));
chiefs.setPlayers(Arrays.asList(cheifsQB, cheifsRB1, cheifsRB2, cheifsWR1, cheifsWR2));
chargers.setPlayers(Arrays.asList(chargersQB, chargersRB1, chargersRB2, chargersWR1, chargersWR2));
//AFC EAST
//Patriots
Player patriotsQB = new Player();
patriotsQB.setFirstName("Tom");
patriotsQB.setLastName("Brady");
patriotsQB.setPosition("QB");
Player patriotsRB1 = new Player();
patriotsRB1.setFirstName("LeGarrette");
patriotsRB1.setLastName("Blount");
patriotsRB1.setPosition("RB");
Player patriotsRB2 = new Player();
patriotsRB2.setFirstName("Dion");
patriotsRB2.setLastName("Lewis");
patriotsRB2.setPosition("RB");
Player patriotsWR1 = new Player();
patriotsWR1.setFirstName("Julian");
patriotsWR1.setLastName("Edelman");
patriotsWR1.setPosition("WR");
Player patriotsWR2 = new Player();
patriotsWR2.setFirstName("Danny");
patriotsWR2.setLastName("Amendola");
patriotsWR2.setPosition("WR");
//Bills
Player billsQB = new Player();
billsQB.setFirstName("Tyrod");
billsQB.setLastName("Taylor");
billsQB.setPosition("QB");
Player billsRB1 = new Player();
billsRB1.setFirstName("LeSean");
billsRB1.setLastName("McCoy");
billsRB1.setPosition("RB");
Player billsRB2 = new Player();
billsRB2.setFirstName("Karlos");
billsRB2.setLastName("Williams");
billsRB2.setPosition("RB");
Player billsWR1 = new Player();
billsWR1.setFirstName("Sammy");
billsWR1.setLastName("Watkins");
billsWR1.setPosition("WR");
Player billsWR2 = new Player();
billsWR2.setFirstName("Robert");
billsWR2.setLastName("Woods");
billsWR2.setPosition("WR");
//Jets
Player jetsQB = new Player();
jetsQB.setFirstName("Ryan");
jetsQB.setLastName("Fitzpatrick");
jetsQB.setPosition("QB");
Player jetsRB1 = new Player();
jetsRB1.setFirstName("Chris");
jetsRB1.setLastName("Ivory");
jetsRB1.setPosition("RB");
Player jetsRB2 = new Player();
jetsRB2.setFirstName("Bilal");
jetsRB2.setLastName("Powell");
jetsRB2.setPosition("RB");
Player jetsWR1 = new Player();
jetsWR1.setFirstName("Brandon");
jetsWR1.setLastName("Marshall");
jetsWR1.setPosition("WR");
Player jetsWR2 = new Player();
jetsWR2.setFirstName("Eric");
jetsWR2.setLastName("Decker");
jetsWR2.setPosition("WR");
//Dolphins
Player dolphinsQB = new Player();
dolphinsQB.setFirstName("Ryan");
dolphinsQB.setLastName("Tannehill");
dolphinsQB.setPosition("QB");
Player dolphinsRB1 = new Player();
dolphinsRB1.setFirstName("Lamar");
dolphinsRB1.setLastName("Miller");
dolphinsRB1.setPosition("RB");
Player dolphinsRB2 = new Player();
dolphinsRB2.setFirstName("Jay");
dolphinsRB2.setLastName("Ajayi");
dolphinsRB2.setPosition("RB");
Player dolphinsWR1 = new Player();
dolphinsWR1.setFirstName("Jarvis");
dolphinsWR1.setLastName("Landry");
dolphinsWR1.setPosition("WR");
Player dolphinsWR2 = new Player();
dolphinsWR2.setFirstName("Rishard");
dolphinsWR2.setLastName("Matthews");
dolphinsWR2.setPosition("WR");
patriots.setPlayers(Arrays.asList(patriotsQB, patriotsRB1, patriotsRB2, patriotsWR1, patriotsWR2));
bills.setPlayers(Arrays.asList(billsQB, billsRB1, billsRB2, billsWR1, billsWR2));
jets.setPlayers(Arrays.asList(jetsQB, jetsRB1, jetsRB2, jetsWR1, jetsWR2));
dolphins.setPlayers(Arrays.asList(dolphinsQB, dolphinsRB1, dolphinsRB2, dolphinsWR1, dolphinsWR2));
//AFC SOUTH
//Texans
Player texansQB = new Player();
texansQB.setFirstName("Brian");
texansQB.setLastName("Hoyer");
texansQB.setPosition("QB");
Player texansRB1 = new Player();
texansRB1.setFirstName("Alfred");
texansRB1.setLastName("Blue");
texansRB1.setPosition("RB");
Player texansRB2 = new Player();
texansRB2.setFirstName("Chris");
texansRB2.setLastName("Polk");
texansRB2.setPosition("RB");
Player texansWR1 = new Player();
texansWR1.setFirstName("DeAndre");
texansWR1.setLastName("Hopkins");
texansWR1.setPosition("WR");
Player texansWR2 = new Player();
texansWR2.setFirstName("Nate");
texansWR2.setLastName("Washington");
texansWR2.setPosition("WR");
//Colts
Player coltsQB = new Player();
coltsQB.setFirstName("Andrew");
coltsQB.setLastName("Luck");
coltsQB.setPosition("QB");
Player coltsRB1 = new Player();
coltsRB1.setFirstName("Frank");
coltsRB1.setLastName("Gore");
coltsRB1.setPosition("RB");
Player coltsRB2 = new Player();
coltsRB2.setFirstName("Ahmad");
coltsRB2.setLastName("Bradshaw");
coltsRB2.setPosition("RB");
Player coltsWR1 = new Player();
coltsWR1.setFirstName("T.Y.");
coltsWR1.setLastName("Hilton");
coltsWR1.setPosition("WR");
Player coltsWR2 = new Player();
coltsWR2.setFirstName("Donte");
coltsWR2.setLastName("Moncrief");
coltsWR2.setPosition("WR");
//Titans
Player titansQB = new Player();
titansQB.setFirstName("Marcus");
titansQB.setLastName("Mariota");
titansQB.setPosition("QB");
Player titansRB1 = new Player();
titansRB1.setFirstName("Antonio");
titansRB1.setLastName("Andrews");
titansRB1.setPosition("RB");
Player titansRB2 = new Player();
titansRB2.setFirstName("Dexter");
titansRB2.setLastName("McCluster");
titansRB2.setPosition("RB");
Player titansWR1 = new Player();
titansWR1.setFirstName("Doral");
titansWR1.setLastName("Green-Beckham");
titansWR1.setPosition("WR");
Player titansWR2 = new Player();
titansWR2.setFirstName("Harry");
titansWR2.setLastName("Douglas");
titansWR2.setPosition("WR");
//Jags
Player jaguarsQB = new Player();
jaguarsQB.setFirstName("Blake");
jaguarsQB.setLastName("Bortles");
jaguarsQB.setPosition("QB");
Player jaguarsRB1 = new Player();
jaguarsRB1.setFirstName("T.J.");
jaguarsRB1.setLastName("Yeldon");
jaguarsRB1.setPosition("RB");
Player jaguarsRB2 = new Player();
jaguarsRB2.setFirstName("Denard");
jaguarsRB2.setLastName("Robinson");
jaguarsRB2.setPosition("RB");
Player jaguarsWR1 = new Player();
jaguarsWR1.setFirstName("Allen");
jaguarsWR1.setLastName("Robinson");
jaguarsWR1.setPosition("WR");
Player jaguarsWR2 = new Player();
jaguarsWR2.setFirstName("Allen");
jaguarsWR2.setLastName("Hurns");
jaguarsWR2.setPosition("WR");
texans.setPlayers(Arrays.asList(texansQB, texansRB1, texansRB2, texansWR1, texansWR2));
colts.setPlayers(Arrays.asList(coltsQB, coltsRB1, coltsRB2, coltsWR1, coltsWR2));
titans.setPlayers(Arrays.asList(titansQB, titansRB1, titansRB2, titansWR1, titansWR2));
jaguars.setPlayers(Arrays.asList(jaguarsQB, jaguarsRB1, jaguarsRB2, jaguarsWR1, jaguarsWR2));
//AFC NORTH
//Steelers
Player steelersQB = new Player();
steelersQB.setFirstName("Ben");
steelersQB.setLastName("Roethlisberger");
steelersQB.setPosition("QB");
Player steelersRB1 = new Player();
steelersRB1.setFirstName("DeAngelo");
steelersRB1.setLastName("Williams");
steelersRB1.setPosition("RB");
Player steelersRB2 = new Player();
steelersRB2.setFirstName("Le'Veon");
steelersRB2.setLastName("Bell");
steelersRB2.setPosition("RB");
Player steelersWR1 = new Player();
steelersWR1.setFirstName("Antonio");
steelersWR1.setLastName("Brown");
steelersWR1.setPosition("WR");
Player steelersWR2 = new Player();
steelersWR2.setFirstName("Martavis");
steelersWR2.setLastName("Bryant");
steelersWR2.setPosition("WR");
//Bengals
Player bengalsQB = new Player();
bengalsQB.setFirstName("Andy");
bengalsQB.setLastName("Dalton");
bengalsQB.setPosition("QB");
Player bengalsRB1 = new Player();
bengalsRB1.setFirstName("Jeremy");
bengalsRB1.setLastName("Hill");
bengalsRB1.setPosition("RB");
Player bengalsRB2 = new Player();
bengalsRB2.setFirstName("Giovani");
bengalsRB2.setLastName("Bernard");
bengalsRB2.setPosition("RB");
Player bengalsWR1 = new Player();
bengalsWR1.setFirstName("A.J.");
bengalsWR1.setLastName("Green");
bengalsWR1.setPosition("WR");
Player bengalsWR2 = new Player();
bengalsWR2.setFirstName("Marvin");
bengalsWR2.setLastName("Jones");
bengalsWR2.setPosition("WR");
//Browns
Player brownsQB = new Player();
brownsQB.setFirstName("Josh");
brownsQB.setLastName("McCown");
brownsQB.setPosition("QB");
Player brownsRB1 = new Player();
brownsRB1.setFirstName("Isaiah");
brownsRB1.setLastName("Crowell");
brownsRB1.setPosition("RB");
Player brownsRB2 = new Player();
brownsRB2.setFirstName("Duke");
brownsRB2.setLastName("Johnson Jr.");
brownsRB2.setPosition("RB");
Player brownsWR1 = new Player();
brownsWR1.setFirstName("Travis");
brownsWR1.setLastName("Benjamin");
brownsWR1.setPosition("WR");
Player brownsWR2 = new Player();
brownsWR2.setFirstName("Brian");
brownsWR2.setLastName("Hartline");
brownsWR2.setPosition("WR");
//Ravens
Player ravensQB = new Player();
ravensQB.setFirstName("Joe");
ravensQB.setLastName("Flacco");
ravensQB.setPosition("QB");
Player ravensRB1 = new Player();
ravensRB1.setFirstName("Justin");
ravensRB1.setLastName("Forsett");
ravensRB1.setPosition("RB");
Player ravensRB2 = new Player();
ravensRB2.setFirstName("Javorius");
ravensRB2.setLastName("Allen");
ravensRB2.setPosition("RB");
Player ravensWR1 = new Player();
ravensWR1.setFirstName("Kamar");
ravensWR1.setLastName("Allen");
ravensWR1.setPosition("WR");
Player ravensWR2 = new Player();
ravensWR2.setFirstName("Steve");
ravensWR2.setLastName("Smith Sr.");
ravensWR2.setPosition("WR");
steelers.setPlayers(Arrays.asList(steelersQB, steelersRB1, steelersRB2, steelersWR1, steelersWR2));
bengals.setPlayers(Arrays.asList(bengalsQB, bengalsRB1, bengalsRB2, bengalsWR1, bengalsWR2));
browns.setPlayers(Arrays.asList(brownsQB, brownsRB1, brownsRB2, brownsWR1, brownsWR2));
ravens.setPlayers(Arrays.asList(ravensQB, ravensRB1, ravensRB2, ravensWR1, ravensWR2));
//NFC WEST
//Seahawks
Player seahawksQB = new Player();
seahawksQB.setFirstName("Russell");
seahawksQB.setLastName("Wilson");
seahawksQB.setPosition("QB");
Player seahawksRB1 = new Player();
seahawksRB1.setFirstName("Thomas");
seahawksRB1.setLastName("Rawls");
seahawksRB1.setPosition("RB");
Player seahawksRB2 = new Player();
seahawksRB2.setFirstName("Marshawn");
seahawksRB2.setLastName("Lynch");
seahawksRB2.setPosition("RB");
Player seahawksWR1 = new Player();
seahawksWR1.setFirstName("Doug");
seahawksWR1.setLastName("Baldwin");
seahawksWR1.setPosition("WR");
Player seahawksWR2 = new Player();
seahawksWR2.setFirstName("Jermaine");
seahawksWR2.setLastName("Kearse");
seahawksWR2.setPosition("WR");
//Cardinals
Player cardinalsQB = new Player();
cardinalsQB.setFirstName("Carson");
cardinalsQB.setLastName("Palmer");
cardinalsQB.setPosition("QB");
Player cardinalsRB1 = new Player();
cardinalsRB1.setFirstName("Chris");
cardinalsRB1.setLastName("Johnson");
cardinalsRB1.setPosition("RB");
Player cardinalsRB2 = new Player();
cardinalsRB2.setFirstName("David");
cardinalsRB2.setLastName("Johnson");
cardinalsRB2.setPosition("RB");
Player cardinalsWR1 = new Player();
cardinalsWR1.setFirstName("Larry");
cardinalsWR1.setLastName("Fitzgerald");
cardinalsWR1.setPosition("WR");
Player cardinalsWR2 = new Player();
cardinalsWR2.setFirstName("John");
cardinalsWR2.setLastName("Brown");
cardinalsWR2.setPosition("WR");
//Rams
Player ramsQB = new Player();
ramsQB.setFirstName("Nick");
ramsQB.setLastName("Foles");
ramsQB.setPosition("QB");
Player ramsRB1 = new Player();
ramsRB1.setFirstName("Todd");
ramsRB1.setLastName("Gurley");
ramsRB1.setPosition("RB");
Player ramsRB2 = new Player();
ramsRB2.setFirstName("Tavon");
ramsRB2.setLastName("Austin");
ramsRB2.setPosition("RB");
Player ramsWR1 = new Player();
ramsWR1.setFirstName("Kenny");
ramsWR1.setLastName("Britt");
ramsWR1.setPosition("WR");
Player ramsWR2 = new Player();
ramsWR2.setFirstName("Benjamin");
ramsWR2.setLastName("Cunningham");
ramsWR2.setPosition("WR");
//49ers
Player ninersQB = new Player();
ninersQB.setFirstName("Blaine");
ninersQB.setLastName("Gabbert");
ninersQB.setPosition("QB");
Player ninersRB1 = new Player();
ninersRB1.setFirstName("Carlos");
ninersRB1.setLastName("Hyde");
ninersRB1.setPosition("RB");
Player ninersRB2 = new Player();
ninersRB2.setFirstName("Shaun");
ninersRB2.setLastName("Draughn");
ninersRB2.setPosition("RB");
Player ninersWR1 = new Player();
ninersWR1.setFirstName("Anquan");
ninersWR1.setLastName("Boldin");
ninersWR1.setPosition("WR");
Player ninersWR2 = new Player();
ninersWR2.setFirstName("Torrey");
ninersWR2.setLastName("Smith");
ninersWR2.setPosition("WR");
seahawks.setPlayers(Arrays.asList(seahawksQB, seahawksRB1, seahawksRB2, seahawksWR1, seahawksWR2));
cardinals.setPlayers(Arrays.asList(cardinalsQB, cardinalsRB1, cardinalsRB2, cardinalsWR1, cardinalsWR2));
rams.setPlayers(Arrays.asList(ramsQB, ramsRB1, ramsRB2, ramsWR1, ramsWR2));
niners.setPlayers(Arrays.asList(ninersQB, ninersRB1, ninersRB2, ninersWR1, ninersWR2));
//NFC SOUTH
//Panthers
Player panthersQB = new Player();
panthersQB.setFirstName("Cam");
panthersQB.setLastName("Newton");
panthersQB.setPosition("QB");
Player panthersRB1 = new Player();
panthersRB1.setFirstName("Jonathan");
panthersRB1.setLastName("Stewart");
panthersRB1.setPosition("RB");
Player panthersRB2 = new Player();
panthersRB2.setFirstName("Mike");
panthersRB2.setLastName("Tolbert");
panthersRB2.setPosition("RB");
Player panthersWR1 = new Player();
panthersWR1.setFirstName("Ted");
panthersWR1.setLastName("Ginn Jr.");
panthersWR1.setPosition("WR");
Player panthersWR2 = new Player();
panthersWR2.setFirstName("Jerricho");
panthersWR2.setLastName("Cotchery");
panthersWR2.setPosition("WR");
//Falcons
Player falconsQB = new Player();
falconsQB.setFirstName("Matt");
falconsQB.setLastName("Ryan");
falconsQB.setPosition("QB");
Player falconsRB1 = new Player();
falconsRB1.setFirstName("Devonta");
falconsRB1.setLastName("Freeman");
falconsRB1.setPosition("RB");
Player falconsRB2 = new Player();
falconsRB2.setFirstName("Tevin");
falconsRB2.setLastName("Coleman");
falconsRB2.setPosition("RB");
Player falconsWR1 = new Player();
falconsWR1.setFirstName("Julio");
falconsWR1.setLastName("Jones");
falconsWR1.setPosition("WR");
Player falconsWR2 = new Player();
falconsWR2.setFirstName("Roddy");
falconsWR2.setLastName("White");
falconsWR2.setPosition("WR");
//Saints
Player saintsQB = new Player();
saintsQB.setFirstName("Drew");
saintsQB.setLastName("Brees");
saintsQB.setPosition("QB");
Player saintsRB1 = new Player();
saintsRB1.setFirstName("Mark");
saintsRB1.setLastName("Ingram");
saintsRB1.setPosition("RB");
Player saintsRB2 = new Player();
saintsRB2.setFirstName("Tim");
saintsRB2.setLastName("Hightower");
saintsRB2.setPosition("RB");
Player saintsWR1 = new Player();
saintsWR1.setFirstName("Brandin");
saintsWR1.setLastName("Cooks");
saintsWR1.setPosition("WR");
Player saintsWR2 = new Player();
saintsWR2.setFirstName("Willie");
saintsWR2.setLastName("Snead");
saintsWR2.setPosition("WR");
//Buccaneers
Player buccaneersQB = new Player();
buccaneersQB.setFirstName("Jameis");
buccaneersQB.setLastName("Winston");
buccaneersQB.setPosition("QB");
Player buccaneersRB1 = new Player();
buccaneersRB1.setFirstName("Doug");
buccaneersRB1.setLastName("Martin");
buccaneersRB1.setPosition("RB");
Player buccaneersRB2 = new Player();
buccaneersRB2.setFirstName("Charles");
buccaneersRB2.setLastName("Sims");
buccaneersRB2.setPosition("RB");
Player buccaneersWR1 = new Player();
buccaneersWR1.setFirstName("Mike");
buccaneersWR1.setLastName("Evans");
buccaneersWR1.setPosition("WR");
Player buccaneersWR2 = new Player();
buccaneersWR2.setFirstName("Vincent");
buccaneersWR2.setLastName("Jackson");
buccaneersWR2.setPosition("WR");
panthers.setPlayers(Arrays.asList(panthersQB, panthersRB1, panthersRB2, panthersWR1, panthersWR2));
falcons.setPlayers(Arrays.asList(falconsQB, falconsRB1, falconsRB2, falconsWR1, falconsWR2));
saints.setPlayers(Arrays.asList(saintsQB, saintsRB1, saintsRB2, saintsWR1, saintsWR2));
buccaneers.setPlayers(Arrays.asList(buccaneersQB, buccaneersRB1, buccaneersRB2, buccaneersWR1, buccaneersWR2));
//NFC EAST
//Cowboys
Player cowboysQB = new Player();
cowboysQB.setFirstName("Matt");
cowboysQB.setLastName("Cassel");
cowboysQB.setPosition("QB");
Player cowboysRB1 = new Player();
cowboysRB1.setFirstName("Darren");
cowboysRB1.setLastName("McFadden");
cowboysRB1.setPosition("RB");
Player cowboysRB2 = new Player();
cowboysRB2.setFirstName("Joseph");
cowboysRB2.setLastName("Randle");
cowboysRB2.setPosition("RB");
Player cowboysWR1 = new Player();
cowboysWR1.setFirstName("Terrance");
cowboysWR1.setLastName("Williams");
cowboysWR1.setPosition("WR");
Player cowboysWR2 = new Player();
cowboysWR2.setFirstName("Cole");
cowboysWR2.setLastName("Beasley");
cowboysWR2.setPosition("WR");
//Eagles
Player eaglesQB = new Player();
eaglesQB.setFirstName("Sam");
eaglesQB.setLastName("Bradford");
eaglesQB.setPosition("QB");
Player eaglesRB1 = new Player();
eaglesRB1.setFirstName("DeMarco");
eaglesRB1.setLastName("Murray");
eaglesRB1.setPosition("RB");
Player eaglesRB2 = new Player();
eaglesRB2.setFirstName("Ryan");
eaglesRB2.setLastName("Matthews");
eaglesRB2.setPosition("RB");
Player eaglesWR1 = new Player();
eaglesWR1.setFirstName("Jordan");
eaglesWR1.setLastName("Matthews");
eaglesWR1.setPosition("WR");
Player eaglesWR2 = new Player();
eaglesWR2.setFirstName("Riley");
eaglesWR2.setLastName("Cooper");
eaglesWR2.setPosition("WR");
//Giants
Player giantsQB = new Player();
giantsQB.setFirstName("Eli");
giantsQB.setLastName("Manning");
giantsQB.setPosition("QB");
Player giantsRB1 = new Player();
giantsRB1.setFirstName("Rashad");
giantsRB1.setLastName("Jennings");
giantsRB1.setPosition("RB");
Player giantsRB2 = new Player();
giantsRB2.setFirstName("Shane");
giantsRB2.setLastName("Vereen");
giantsRB2.setPosition("RB");
Player giantsWR1 = new Player();
giantsWR1.setFirstName("Odell");
giantsWR1.setLastName("Beckham Jr.");
giantsWR1.setPosition("WR");
Player giantsWR2 = new Player();
giantsWR2.setFirstName("Ruben");
giantsWR2.setLastName("Randle");
giantsWR2.setPosition("WR");
//Redskins
Player redskinsQB = new Player();
redskinsQB.setFirstName("Kirk");
redskinsQB.setLastName("Cousins");
redskinsQB.setPosition("QB");
Player redskinsRB1 = new Player();
redskinsRB1.setFirstName("Alfred");
redskinsRB1.setLastName("Morris");
redskinsRB1.setPosition("RB");
Player redskinsRB2 = new Player();
redskinsRB2.setFirstName("Matt");
redskinsRB2.setLastName("Jones");
redskinsRB2.setPosition("RB");
Player redskinsWR1 = new Player();
redskinsWR1.setFirstName("Pierre");
redskinsWR1.setLastName("Garcon");
redskinsWR1.setPosition("WR");
Player redskinsWR2 = new Player();
redskinsWR2.setFirstName("Jamison");
redskinsWR2.setLastName("Crowder");
redskinsWR2.setPosition("WR");
cowboys.setPlayers(Arrays.asList(cowboysQB, cowboysRB1, cowboysRB2, cowboysWR1, cowboysWR2));
eagles.setPlayers(Arrays.asList(eaglesQB, eaglesRB1, eaglesRB2, eaglesWR1, eaglesWR2));
giants.setPlayers(Arrays.asList(giantsQB, giantsRB1, giantsRB2, giantsWR1, giantsWR2));
redskins.setPlayers(Arrays.asList(redskinsQB, redskinsRB1, redskinsRB2, redskinsWR1, redskinsWR2));
//NFC NORT
//Bears
Player bearsQB = new Player();
bearsQB.setFirstName("Jay");
bearsQB.setLastName("Cutler");
bearsQB.setPosition("QB");
Player bearsRB1 = new Player();
bearsRB1.setFirstName("Matt");
bearsRB1.setLastName("Forte");
bearsRB1.setPosition("RB");
Player bearsRB2 = new Player();
bearsRB2.setFirstName("Jeremy");
bearsRB2.setLastName("Langford");
bearsRB2.setPosition("RB");
Player bearsWR1 = new Player();
bearsWR1.setFirstName("Alson");
bearsWR1.setLastName("Jeffery");
bearsWR1.setPosition("WR");
Player bearsWR2 = new Player();
bearsWR2.setFirstName("Marquess");
bearsWR2.setLastName("Wilson");
bearsWR2.setPosition("WR");
//Lions
Player lionsQB = new Player();
lionsQB.setFirstName("Matthew");
lionsQB.setLastName("Stafford");
lionsQB.setPosition("QB");
Player lionsRB1 = new Player();
lionsRB1.setFirstName("Ameer");
lionsRB1.setLastName("Abdullah");
lionsRB1.setPosition("RB");
Player lionsRB2 = new Player();
lionsRB2.setFirstName("Joique");
lionsRB2.setLastName("Bell");
lionsRB2.setPosition("RB");
Player lionsWR1 = new Player();
lionsWR1.setFirstName("Calvin");
lionsWR1.setLastName("Johnson");
lionsWR1.setPosition("WR");
lionsWR1.setActive(false);
Player lionsWR2 = new Player();
lionsWR2.setFirstName("Golden");
lionsWR2.setLastName("Tate");
lionsWR2.setPosition("WR");
//Packers
Player packersQB = new Player();
packersQB.setFirstName("Aaron");
packersQB.setLastName("Rodgers");
packersQB.setPosition("QB");
Player packersRB1 = new Player();
packersRB1.setFirstName("Eddie");
packersRB1.setLastName("Lacy");
packersRB1.setPosition("RB");
Player packersRB2 = new Player();
packersRB2.setFirstName("James");
packersRB2.setLastName("Starks");
packersRB2.setPosition("RB");
Player packersWR1 = new Player();
packersWR1.setFirstName("James");
packersWR1.setLastName("Jones");
packersWR1.setPosition("WR");
Player packersWR2 = new Player();
packersWR2.setFirstName("Randall");
packersWR2.setLastName("Cobb");
packersWR2.setPosition("WR");
//Vikings
Player vikingsQB = new Player();
vikingsQB.setFirstName("Teddy");
vikingsQB.setLastName("Bridgewater");
vikingsQB.setPosition("QB");
Player vikingsRB1 = new Player();
vikingsRB1.setFirstName("Adrian");
vikingsRB1.setLastName("Peterson");
vikingsRB1.setPosition("RB");
Player vikingsRB2 = new Player();
vikingsRB2.setFirstName("Jerick");
vikingsRB2.setLastName("McKinnon");
vikingsRB2.setPosition("RB");
Player vikingsWR1 = new Player();
vikingsWR1.setFirstName("Stefon");
vikingsWR1.setLastName("Diggs");
vikingsWR1.setPosition("WR");
Player vikingsWR2 = new Player();
vikingsWR2.setFirstName("Kyle");
vikingsWR2.setLastName("Rudolph");
vikingsWR2.setPosition("WR");
bears.setPlayers(Arrays.asList(bearsQB, bearsRB1, bearsRB2, bearsWR1, bearsWR2));
lions.setPlayers(Arrays.asList(lionsQB, lionsRB1, lionsRB2, lionsWR1, lionsWR2));
packers.setPlayers(Arrays.asList(packersQB, packersRB1, packersRB2, packersWR1, packersWR2));
vikings.setPlayers(Arrays.asList(vikingsQB, vikingsRB1, vikingsRB2, vikingsWR1, vikingsWR2));
//add stats
//Raiders
//Carr
Stats raidersQBStats = new Stats();
raidersQBStats.setSeason(season2015);
raidersQBStats.setPlayer(raidersQB);
raidersQBStats.setPassAttempts(573);
raidersQBStats.setPassCompletions(350);
raidersQBStats.setPassingYards(3987);
raidersQBStats.setPassingTouchdowns(7);
raidersQBStats.setReceptions(0);
raidersQBStats.setReceivingYards(0);
raidersQBStats.setReceivingTouchdowns(0);
raidersQBStats.setRushingAttempts(33);
raidersQBStats.setRushingYards(138);
raidersQBStats.setRushingTouchdowns(0);
raidersQB.getStats().add(raidersQBStats);
//Murray
Stats raidersRB1Stats = new Stats();
raidersRB1Stats.setSeason(season2015);
raidersRB1Stats.setPlayer(raidersRB1);
raidersRB1Stats.setPassAttempts(0);
raidersRB1Stats.setPassCompletions(0);
raidersRB1Stats.setPassingYards(0);
raidersRB1Stats.setPassingTouchdowns(0);
raidersRB1Stats.setReceptions(41);
raidersRB1Stats.setReceivingYards(232);
raidersRB1Stats.setReceivingTouchdowns(0);
raidersRB1Stats.setRushingAttempts(266);
raidersRB1Stats.setRushingYards(1066);
raidersRB1Stats.setRushingTouchdowns(6);
raidersRB1.getStats().add(raidersRB1Stats);
//Jones
Stats raidersRB2Stats = new Stats();
raidersRB2Stats.setSeason(season2015);
raidersRB2Stats.setPlayer(raidersRB1);
raidersRB2Stats.setPassAttempts(0);
raidersRB2Stats.setPassCompletions(0);
raidersRB2Stats.setPassingYards(0);
raidersRB2Stats.setPassingTouchdowns(0);
raidersRB2Stats.setReceptions(41);
raidersRB2Stats.setReceivingYards(106);
raidersRB2Stats.setReceivingTouchdowns(1);
raidersRB2Stats.setRushingAttempts(16);
raidersRB2Stats.setRushingYards(74);
raidersRB2Stats.setRushingTouchdowns(6);
raidersRB2.getStats().add(raidersRB2Stats);
//Crabtree
Stats raidersWR1Stats = new Stats();
raidersWR1Stats.setSeason(season2015);
raidersWR1Stats.setPlayer(raidersWR1);
raidersWR1Stats.setPassAttempts(0);
raidersWR1Stats.setPassCompletions(0);
raidersWR1Stats.setPassingYards(0);
raidersWR1Stats.setPassingTouchdowns(0);
raidersWR1Stats.setReceptions(85);
raidersWR1Stats.setReceivingYards(922);
raidersWR1Stats.setReceivingTouchdowns(9);
raidersWR1Stats.setRushingAttempts(0);
raidersWR1Stats.setRushingYards(0);
raidersWR1Stats.setRushingTouchdowns(0);
raidersWR1.getStats().add(raidersWR1Stats);
//Cooper
Stats raidersWR2Stats = new Stats();
raidersWR2Stats.setSeason(season2015);
raidersWR2Stats.setPlayer(raidersWR1);
raidersWR2Stats.setPassAttempts(0);
raidersWR2Stats.setPassCompletions(0);
raidersWR2Stats.setPassingYards(0);
raidersWR2Stats.setPassingTouchdowns(0);
raidersWR2Stats.setReceptions(72);
raidersWR2Stats.setReceivingYards(1070);
raidersWR2Stats.setReceivingTouchdowns(6);
raidersWR2Stats.setRushingAttempts(3);
raidersWR2Stats.setRushingYards(-3);
raidersWR2Stats.setRushingTouchdowns(0);
raidersWR2.getStats().add(raidersWR2Stats);
//Broncos
//Manning
Stats broncosQBStats = new Stats();
broncosQBStats.setSeason(season2015);
broncosQBStats.setPlayer(broncosQB);
broncosQBStats.setPassAttempts(331);
broncosQBStats.setPassCompletions(198);
broncosQBStats.setPassingYards(2249);
broncosQBStats.setPassingTouchdowns(9);
broncosQBStats.setReceptions(0);
broncosQBStats.setRushingAttempts(6);
broncosQBStats.setRushingYards(-6);
broncosQBStats.setRushingTouchdowns(0);
broncosQB.getStats().add(broncosQBStats);
//Hillman
Stats broncosRB1Stats = new Stats();
broncosRB1Stats.setSeason(season2015);
broncosRB1Stats.setPlayer(broncosRB1);
broncosRB1Stats.setPassAttempts(0);
broncosRB1Stats.setPassCompletions(0);
broncosRB1Stats.setPassingYards(0);
broncosRB1Stats.setPassingTouchdowns(0);
broncosRB1Stats.setReceptions(24);
broncosRB1Stats.setReceivingYards(111);
broncosRB1Stats.setReceivingTouchdowns(0);
broncosRB1Stats.setRushingAttempts(207);
broncosRB1Stats.setRushingYards(863);
broncosRB1Stats.setRushingTouchdowns(7);
broncosRB1.getStats().add(broncosRB1Stats);
//Anderson
Stats broncosRB2Stats = new Stats();
broncosRB2Stats.setSeason(season2015);
broncosRB2Stats.setPlayer(broncosRB1);
broncosRB2Stats.setPassAttempts(0);
broncosRB2Stats.setPassCompletions(0);
broncosRB2Stats.setPassingYards(0);
broncosRB2Stats.setPassingTouchdowns(0);
broncosRB2Stats.setReceptions(25);
broncosRB2Stats.setReceivingYards(36);
broncosRB2Stats.setReceivingYards(183);
broncosRB2Stats.setReceivingTouchdowns(0);
broncosRB2Stats.setRushingAttempts(152);
broncosRB2Stats.setRushingYards(720);
broncosRB2Stats.setRushingTouchdowns(5);
broncosRB2.getStats().add(broncosRB2Stats);
//Thomas
Stats broncosWR1Stats = new Stats();
broncosWR1Stats.setSeason(season2015);
broncosWR1Stats.setPlayer(broncosWR1);
broncosWR1Stats.setPassAttempts(0);
broncosWR1Stats.setPassCompletions(0);
broncosWR1Stats.setPassingYards(0);
broncosWR1Stats.setPassingTouchdowns(0);
broncosWR1Stats.setReceptions(105);
broncosWR1Stats.setReceivingYards(1304);
broncosWR1Stats.setReceivingTouchdowns(6);
broncosWR1Stats.setRushingAttempts(0);
broncosWR1Stats.setRushingYards(0);
broncosWR1Stats.setRushingTouchdowns(0);
broncosWR1.getStats().add(broncosWR1Stats);
//Sanders
Stats broncosWR2Stats = new Stats();
broncosWR2Stats.setSeason(season2015);
broncosWR2Stats.setPlayer(broncosWR1);
broncosWR2Stats.setPassAttempts(0);
broncosWR2Stats.setPassCompletions(0);
broncosWR2Stats.setPassingYards(0);
broncosWR2Stats.setPassingTouchdowns(0);
broncosWR2Stats.setReceptions(72);
broncosWR2Stats.setReceivingYards(1135);
broncosWR2Stats.setReceivingTouchdowns(6);
broncosWR2Stats.setRushingAttempts(3);
broncosWR2Stats.setRushingYards(29);
broncosWR2Stats.setRushingTouchdowns(0);
broncosWR2.getStats().add(broncosWR2Stats);
//Cheifs
//Smith
Stats cheifsQBStats = new Stats();
cheifsQBStats.setSeason(season2015);
cheifsQBStats.setPlayer(cheifsQB);
cheifsQBStats.setPassAttempts(470);
cheifsQBStats.setPassCompletions(307);
cheifsQBStats.setPassingYards(3486);
cheifsQBStats.setPassingTouchdowns(20);
cheifsQBStats.setReceptions(1);
cheifsQBStats.setRushingAttempts(84);
cheifsQBStats.setRushingYards(498);
cheifsQBStats.setRushingTouchdowns(2);
cheifsQB.getStats().add(cheifsQBStats);
//West
Stats cheifsRB1Stats = new Stats();
cheifsRB1Stats.setSeason(season2015);
cheifsRB1Stats.setPlayer(cheifsRB1);
cheifsRB1Stats.setPassAttempts(0);
cheifsRB1Stats.setPassCompletions(0);
cheifsRB1Stats.setPassingYards(0);
cheifsRB1Stats.setPassingTouchdowns(0);
cheifsRB1Stats.setReceptions(20);
cheifsRB1Stats.setReceivingYards(214);
cheifsRB1Stats.setReceivingTouchdowns(1);
cheifsRB1Stats.setRushingAttempts(160);
cheifsRB1Stats.setRushingYards(634);
cheifsRB1Stats.setRushingTouchdowns(4);
cheifsRB1.getStats().add(cheifsRB1Stats);
//Ware
Stats cheifsRB2Stats = new Stats();
cheifsRB2Stats.setSeason(season2015);
cheifsRB2Stats.setPlayer(cheifsRB1);
cheifsRB2Stats.setPassAttempts(0);
cheifsRB2Stats.setPassCompletions(0);
cheifsRB2Stats.setPassingYards(0);
cheifsRB2Stats.setPassingTouchdowns(0);
cheifsRB2Stats.setReceptions(6);
cheifsRB2Stats.setReceivingYards(5);
cheifsRB2Stats.setReceivingTouchdowns(1);
cheifsRB2Stats.setRushingAttempts(72);
cheifsRB2Stats.setRushingYards(403);
cheifsRB2Stats.setRushingTouchdowns(6);
cheifsRB2.getStats().add(cheifsRB2Stats);
//Maclin
Stats cheifsWR1Stats = new Stats();
cheifsWR1Stats.setSeason(season2015);
cheifsWR1Stats.setPlayer(cheifsWR1);
cheifsWR1Stats.setPassAttempts(0);
cheifsWR1Stats.setPassCompletions(0);
cheifsWR1Stats.setPassingYards(0);
cheifsWR1Stats.setPassingTouchdowns(0);
cheifsWR1Stats.setReceptions(87);
cheifsWR1Stats.setReceivingYards(1088);
cheifsWR1Stats.setReceivingTouchdowns(8);
cheifsWR1Stats.setRushingAttempts(3);
cheifsWR1Stats.setRushingYards(14);
cheifsWR1Stats.setRushingTouchdowns(0);
cheifsWR1.getStats().add(cheifsWR1Stats);
//Wilson
Stats cheifsWR2Stats = new Stats();
cheifsWR2Stats.setSeason(season2015);
cheifsWR2Stats.setPlayer(cheifsWR1);
cheifsWR2Stats.setPassAttempts(0);
cheifsWR2Stats.setPassCompletions(0);
cheifsWR2Stats.setPassingYards(0);
cheifsWR2Stats.setPassingTouchdowns(0);
cheifsWR2Stats.setReceptions(35);
cheifsWR2Stats.setReceivingYards(451);
cheifsWR2Stats.setReceivingTouchdowns(2);
cheifsWR2Stats.setRushingAttempts(5);
cheifsWR2Stats.setRushingYards(26);
cheifsWR2Stats.setRushingTouchdowns(0);
cheifsWR2.getStats().add(cheifsWR2Stats);
//Chargers
//Rivers
Stats chargersQBStats = new Stats();
chargersQBStats.setSeason(season2015);
chargersQBStats.setPlayer(chargersQB);
chargersQBStats.setPassAttempts(661);
chargersQBStats.setPassCompletions(437);
chargersQBStats.setPassingYards(4792);
chargersQBStats.setPassingTouchdowns(29);
chargersQBStats.setReceptions(0);
chargersQBStats.setRushingAttempts(17);
chargersQBStats.setRushingYards(28);
chargersQBStats.setRushingTouchdowns(0);
chargersQB.getStats().add(chargersQBStats);
//Gordon
Stats chargersRB1Stats = new Stats();
chargersRB1Stats.setSeason(season2015);
chargersRB1Stats.setPlayer(chargersRB1);
chargersRB1Stats.setPassAttempts(0);
chargersRB1Stats.setPassCompletions(0);
chargersRB1Stats.setPassingYards(0);
chargersRB1Stats.setPassingTouchdowns(0);
chargersRB1Stats.setReceptions(33);
chargersRB1Stats.setReceivingYards(37);
chargersRB1Stats.setReceivingTouchdowns(0);
chargersRB1Stats.setRushingAttempts(184);
chargersRB1Stats.setRushingYards(641);
chargersRB1Stats.setRushingTouchdowns(0);
chargersRB1.getStats().add(chargersRB1Stats);
//Woodhead
Stats chargersRB2Stats = new Stats();
chargersRB2Stats.setSeason(season2015);
chargersRB2Stats.setPlayer(chargersRB1);
chargersRB2Stats.setPassAttempts(0);
chargersRB2Stats.setPassCompletions(0);
chargersRB2Stats.setPassingYards(0);
chargersRB2Stats.setPassingTouchdowns(0);
chargersRB2Stats.setReceptions(80);
chargersRB2Stats.setReceivingYards(106);
chargersRB2Stats.setReceivingTouchdowns(6);
chargersRB2Stats.setRushingAttempts(98);
chargersRB2Stats.setRushingYards(336);
chargersRB2Stats.setRushingTouchdowns(3);
chargersRB2.getStats().add(chargersRB2Stats);
//Allen
Stats chargersWR1Stats = new Stats();
chargersWR1Stats.setSeason(season2015);
chargersWR1Stats.setPlayer(chargersWR1);
chargersWR1Stats.setPassAttempts(0);
chargersWR1Stats.setPassCompletions(0);
chargersWR1Stats.setPassingYards(0);
chargersWR1Stats.setPassingTouchdowns(0);
chargersWR1Stats.setReceptions(67);
chargersWR1Stats.setReceivingYards(725);
chargersWR1Stats.setReceivingTouchdowns(4);
chargersWR1Stats.setRushingAttempts(0);
chargersWR1Stats.setRushingYards(0);
chargersWR1Stats.setRushingTouchdowns(0);
chargersWR1.getStats().add(chargersWR1Stats);
//Floyd
Stats chargersWR2Stats = new Stats();
chargersWR2Stats.setSeason(season2015);
chargersWR2Stats.setPlayer(chargersWR1);
chargersWR2Stats.setPassAttempts(0);
chargersWR2Stats.setPassCompletions(0);
chargersWR2Stats.setPassingYards(0);
chargersWR2Stats.setPassingTouchdowns(0);
chargersWR2Stats.setReceptions(30);
chargersWR2Stats.setReceivingYards(561);
chargersWR2Stats.setReceivingTouchdowns(3);
chargersWR2Stats.setRushingAttempts(0);
chargersWR2Stats.setRushingYards(0);
chargersWR2Stats.setRushingTouchdowns(0);
chargersWR2.getStats().add(chargersWR2Stats);
//Raiders
//Brady
Stats patriotsQBStats = new Stats();
patriotsQBStats.setSeason(season2015);
patriotsQBStats.setPlayer(patriotsQB);
patriotsQBStats.setPassAttempts(624);
patriotsQBStats.setPassCompletions(402);
patriotsQBStats.setPassingYards(4770);
patriotsQBStats.setPassingTouchdowns(36);
patriotsQBStats.setReceptions(1);
patriotsQBStats.setRushingAttempts(34);
patriotsQBStats.setRushingYards(53);
patriotsQBStats.setRushingTouchdowns(3);
patriotsQB.getStats().add(patriotsQBStats);
//Blount
Stats patriotsRB1Stats = new Stats();
patriotsRB1Stats.setSeason(season2015);
patriotsRB1Stats.setPlayer(patriotsRB1);
patriotsRB1Stats.setPassAttempts(0);
patriotsRB1Stats.setPassCompletions(0);
patriotsRB1Stats.setPassingYards(0);
patriotsRB1Stats.setPassingTouchdowns(0);
patriotsRB1Stats.setReceptions(6);
patriotsRB1Stats.setReceivingYards(7);
patriotsRB1Stats.setReceivingTouchdowns(1);
patriotsRB1Stats.setRushingAttempts(165);
patriotsRB1Stats.setRushingYards(703);
patriotsRB1Stats.setRushingTouchdowns(6);
patriotsRB1.getStats().add(patriotsRB1Stats);
//Lewis
Stats patriotsRB2Stats = new Stats();
patriotsRB2Stats.setSeason(season2015);
patriotsRB2Stats.setPlayer(patriotsRB1);
patriotsRB2Stats.setPassAttempts(0);
patriotsRB2Stats.setPassCompletions(0);
patriotsRB2Stats.setPassingYards(0);
patriotsRB2Stats.setPassingTouchdowns(0);
patriotsRB2Stats.setReceptions(36);
patriotsRB2Stats.setReceivingYards(388);
patriotsRB2Stats.setReceivingTouchdowns(2);
patriotsRB2Stats.setRushingAttempts(49);
patriotsRB2Stats.setRushingYards(234);
patriotsRB2Stats.setRushingTouchdowns(2);
patriotsRB2.getStats().add(patriotsRB2Stats);
//Edelman
Stats patriotsWR1Stats = new Stats();
patriotsWR1Stats.setSeason(season2015);
patriotsWR1Stats.setPlayer(patriotsWR1);
patriotsWR1Stats.setPassAttempts(0);
patriotsWR1Stats.setPassCompletions(0);
patriotsWR1Stats.setPassingYards(0);
patriotsWR1Stats.setPassingTouchdowns(0);
patriotsWR1Stats.setReceptions(61);
patriotsWR1Stats.setReceivingYards(692);
patriotsWR1Stats.setReceivingTouchdowns(7);
patriotsWR1Stats.setRushingAttempts(3);
patriotsWR1Stats.setRushingYards(23);
patriotsWR1Stats.setRushingTouchdowns(0);
patriotsWR1.getStats().add(patriotsWR1Stats);
//Amendola
Stats patriotsWR2Stats = new Stats();
patriotsWR2Stats.setSeason(season2015);
patriotsWR2Stats.setPlayer(patriotsWR1);
patriotsWR2Stats.setPassAttempts(0);
patriotsWR2Stats.setPassCompletions(0);
patriotsWR2Stats.setPassingYards(0);
patriotsWR2Stats.setPassingTouchdowns(0);
patriotsWR2Stats.setReceptions(65);
patriotsWR2Stats.setReceivingYards(648);
patriotsWR2Stats.setReceivingTouchdowns(3);
patriotsWR2Stats.setRushingAttempts(2);
patriotsWR2Stats.setRushingYards(11);
patriotsWR2Stats.setRushingTouchdowns(0);
patriotsWR2.getStats().add(patriotsWR2Stats);
//Bills
//Taylor
Stats billsQBStats = new Stats();
billsQBStats.setSeason(season2015);
billsQBStats.setPlayer(billsQB);
billsQBStats.setPassAttempts(380);
billsQBStats.setPassCompletions(242);
billsQBStats.setPassingYards(3035);
billsQBStats.setPassingTouchdowns(20);
billsQBStats.setReceptions(1);
billsQBStats.setReceivingYards(4);
billsQBStats.setReceivingTouchdowns(0);
billsQBStats.setRushingAttempts(104);
billsQBStats.setRushingYards(568);
billsQBStats.setRushingTouchdowns(4);
billsQB.getStats().add(billsQBStats);
//McCoy
Stats billsRB1Stats = new Stats();
billsRB1Stats.setSeason(season2015);
billsRB1Stats.setPlayer(billsRB1);
billsRB1Stats.setPassAttempts(0);
billsRB1Stats.setPassCompletions(0);
billsRB1Stats.setPassingYards(0);
billsRB1Stats.setPassingTouchdowns(0);
billsRB1Stats.setReceptions(32);
billsRB1Stats.setReceivingYards(292);
billsRB1Stats.setReceivingTouchdowns(2);
billsRB1Stats.setRushingAttempts(203);
billsRB1Stats.setRushingYards(895);
billsRB1Stats.setRushingTouchdowns(3);
billsRB1.getStats().add(billsRB1Stats);
//Williams
Stats billsRB2Stats = new Stats();
billsRB2Stats.setSeason(season2015);
billsRB2Stats.setPlayer(billsRB1);
billsRB2Stats.setPassAttempts(0);
billsRB2Stats.setPassCompletions(0);
billsRB2Stats.setPassingYards(0);
billsRB2Stats.setPassingTouchdowns(0);
billsRB2Stats.setReceptions(11);
billsRB2Stats.setReceivingYards(14);
billsRB2Stats.setReceivingTouchdowns(2);
billsRB2Stats.setRushingAttempts(93);
billsRB2Stats.setRushingYards(517);
billsRB2Stats.setRushingTouchdowns(7);
billsRB2.getStats().add(billsRB2Stats);
//Watkins
Stats billsWR1Stats = new Stats();
billsWR1Stats.setSeason(season2015);
billsWR1Stats.setPlayer(billsWR1);
billsWR1Stats.setPassAttempts(0);
billsWR1Stats.setPassCompletions(0);
billsWR1Stats.setPassingYards(0);
billsWR1Stats.setPassingTouchdowns(0);
billsWR1Stats.setReceptions(60);
billsWR1Stats.setReceivingYards(1047);
billsWR1Stats.setReceivingTouchdowns(9);
billsWR1Stats.setRushingAttempts(1);
billsWR1Stats.setRushingYards(1);
billsWR1Stats.setRushingTouchdowns(0);
billsWR1.getStats().add(billsWR1Stats);
//Woods
Stats billsWR2Stats = new Stats();
billsWR2Stats.setSeason(season2015);
billsWR2Stats.setPlayer(billsWR1);
billsWR2Stats.setPassAttempts(0);
billsWR2Stats.setPassCompletions(0);
billsWR2Stats.setPassingYards(0);
billsWR2Stats.setPassingTouchdowns(0);
billsWR2Stats.setReceptions(47);
billsWR2Stats.setReceivingYards(552);
billsWR2Stats.setReceivingTouchdowns(3);
billsWR2Stats.setRushingAttempts(1);
billsWR2Stats.setRushingYards(0);
billsWR2Stats.setRushingTouchdowns(0);
billsWR2.getStats().add(billsWR2Stats);
//Jets
//Fitzpatrick
Stats jetsQBStats = new Stats();
jetsQBStats.setSeason(season2015);
jetsQBStats.setPlayer(jetsQB);
jetsQBStats.setPassAttempts(562);
jetsQBStats.setPassCompletions(335);
jetsQBStats.setPassingYards(3905);
jetsQBStats.setPassingTouchdowns(31);
jetsQBStats.setReceptions(0);
jetsQBStats.setReceivingYards(0);
jetsQBStats.setReceivingTouchdowns(0);
jetsQBStats.setRushingAttempts(60);
jetsQBStats.setRushingYards(270);
jetsQBStats.setRushingTouchdowns(2);
jetsQB.getStats().add(jetsQBStats);
//Ivory
Stats jetsRB1Stats = new Stats();
jetsRB1Stats.setSeason(season2015);
jetsRB1Stats.setPlayer(jetsRB1);
jetsRB1Stats.setPassAttempts(0);
jetsRB1Stats.setPassCompletions(0);
jetsRB1Stats.setPassingYards(0);
jetsRB1Stats.setPassingTouchdowns(0);
jetsRB1Stats.setReceptions(30);
jetsRB1Stats.setReceivingYards(217);
jetsRB1Stats.setReceivingTouchdowns(1);
jetsRB1Stats.setRushingAttempts(247);
jetsRB1Stats.setRushingYards(1070);
jetsRB1Stats.setRushingTouchdowns(7);
jetsRB1.getStats().add(jetsRB1Stats);
//Powell
Stats jetsRB2Stats = new Stats();
jetsRB2Stats.setSeason(season2015);
jetsRB2Stats.setPlayer(jetsRB1);
jetsRB2Stats.setPassAttempts(0);
jetsRB2Stats.setPassCompletions(0);
jetsRB2Stats.setPassingYards(0);
jetsRB2Stats.setPassingTouchdowns(0);
jetsRB2Stats.setReceptions(47);
jetsRB2Stats.setReceivingYards(388);
jetsRB2Stats.setReceivingTouchdowns(2);
jetsRB2Stats.setRushingAttempts(70);
jetsRB2Stats.setRushingYards(313);
jetsRB2Stats.setRushingTouchdowns(1);
jetsRB2.getStats().add(jetsRB2Stats);
//Marshall
Stats jetsWR1Stats = new Stats();
jetsWR1Stats.setSeason(season2015);
jetsWR1Stats.setPlayer(jetsWR1);
jetsWR1Stats.setPassAttempts(0);
jetsWR1Stats.setPassCompletions(0);
jetsWR1Stats.setPassingYards(0);
jetsWR1Stats.setPassingTouchdowns(0);
jetsWR1Stats.setReceptions(109);
jetsWR1Stats.setReceivingYards(1502);
jetsWR1Stats.setReceivingTouchdowns(14);
jetsWR1Stats.setRushingAttempts(0);
jetsWR1Stats.setRushingYards(0);
jetsWR1Stats.setRushingTouchdowns(0);
jetsWR1.getStats().add(jetsWR1Stats);
//Decker
Stats jetsWR2Stats = new Stats();
jetsWR2Stats.setSeason(season2015);
jetsWR2Stats.setPlayer(jetsWR1);
jetsWR2Stats.setPassAttempts(0);
jetsWR2Stats.setPassCompletions(0);
jetsWR2Stats.setPassingYards(0);
jetsWR2Stats.setPassingTouchdowns(0);
jetsWR2Stats.setReceptions(80);
jetsWR2Stats.setReceivingYards(1027);
jetsWR2Stats.setReceivingTouchdowns(12);
jetsWR2Stats.setRushingAttempts(0);
jetsWR2Stats.setRushingYards(0);
jetsWR2Stats.setRushingTouchdowns(0);
jetsWR2.getStats().add(jetsWR2Stats);
//Dolphins
//Tannehill
Stats dolphinsQBStats = new Stats();
dolphinsQBStats.setSeason(season2015);
dolphinsQBStats.setPlayer(dolphinsQB);
dolphinsQBStats.setPassAttempts(586);
dolphinsQBStats.setPassCompletions(363);
dolphinsQBStats.setPassingYards(3987);
dolphinsQBStats.setPassingTouchdowns(24);
dolphinsQBStats.setReceptions(0);
dolphinsQBStats.setReceivingYards(0);
dolphinsQBStats.setReceivingTouchdowns(0);
dolphinsQBStats.setRushingAttempts(32);
dolphinsQBStats.setRushingYards(141);
dolphinsQBStats.setRushingTouchdowns(1);
dolphinsQB.getStats().add(dolphinsQBStats);
//Miller
Stats dolphinsRB1Stats = new Stats();
dolphinsRB1Stats.setSeason(season2015);
dolphinsRB1Stats.setPlayer(dolphinsRB1);
dolphinsRB1Stats.setPassAttempts(0);
dolphinsRB1Stats.setPassCompletions(0);
dolphinsRB1Stats.setPassingYards(0);
dolphinsRB1Stats.setPassingTouchdowns(0);
dolphinsRB1Stats.setReceptions(47);
dolphinsRB1Stats.setReceivingYards(397);
dolphinsRB1Stats.setReceivingTouchdowns(2);
dolphinsRB1Stats.setRushingAttempts(194);
dolphinsRB1Stats.setRushingYards(872);
dolphinsRB1Stats.setRushingTouchdowns(8);
dolphinsRB1.getStats().add(dolphinsRB1Stats);
//Ajayi
Stats dolphinsRB2Stats = new Stats();
dolphinsRB2Stats.setSeason(season2015);
dolphinsRB2Stats.setPlayer(dolphinsRB1);
dolphinsRB2Stats.setPassAttempts(0);
dolphinsRB2Stats.setPassCompletions(0);
dolphinsRB2Stats.setPassingYards(0);
dolphinsRB2Stats.setPassingTouchdowns(0);
dolphinsRB2Stats.setReceptions(7);
dolphinsRB2Stats.setReceivingYards(90);
dolphinsRB2Stats.setReceivingTouchdowns(0);
dolphinsRB2Stats.setRushingAttempts(49);
dolphinsRB2Stats.setRushingYards(187);
dolphinsRB2Stats.setRushingTouchdowns(1);
dolphinsRB2.getStats().add(dolphinsRB2Stats);
//Landry
Stats dolphinsWR1Stats = new Stats();
dolphinsWR1Stats.setSeason(season2015);
dolphinsWR1Stats.setPlayer(dolphinsWR1);
dolphinsWR1Stats.setPassAttempts(0);
dolphinsWR1Stats.setPassCompletions(0);
dolphinsWR1Stats.setPassingYards(0);
dolphinsWR1Stats.setPassingTouchdowns(0);
dolphinsWR1Stats.setReceptions(110);
dolphinsWR1Stats.setReceivingYards(1157);
dolphinsWR1Stats.setReceivingTouchdowns(4);
dolphinsWR1Stats.setRushingAttempts(18);
dolphinsWR1Stats.setRushingYards(113);
dolphinsWR1Stats.setRushingTouchdowns(1);
dolphinsWR1.getStats().add(dolphinsWR1Stats);
//Matthews
Stats dolphinsWR2Stats = new Stats();
dolphinsWR2Stats.setSeason(season2015);
dolphinsWR2Stats.setPlayer(dolphinsWR1);
dolphinsWR2Stats.setPassAttempts(0);
dolphinsWR2Stats.setPassCompletions(0);
dolphinsWR2Stats.setPassingYards(0);
dolphinsWR2Stats.setPassingTouchdowns(0);
dolphinsWR2Stats.setReceptions(43);
dolphinsWR2Stats.setReceivingYards(662);
dolphinsWR2Stats.setReceivingTouchdowns(4);
dolphinsWR2Stats.setRushingAttempts(1);
dolphinsWR2Stats.setRushingYards(4);
dolphinsWR2Stats.setRushingTouchdowns(0);
dolphinsWR2.getStats().add(dolphinsWR2Stats);
//Texans
//Hoyer
Stats texansQBStats = new Stats();
texansQBStats.setSeason(season2015);
texansQBStats.setPlayer(texansQB);
texansQBStats.setPassAttempts(369);
texansQBStats.setPassCompletions(224);
texansQBStats.setPassingYards(2606);
texansQBStats.setPassingTouchdowns(19);
texansQBStats.setReceptions(0);
texansQBStats.setReceivingYards(0);
texansQBStats.setReceivingTouchdowns(0);
texansQBStats.setRushingAttempts(15);
texansQBStats.setRushingYards(44);
texansQBStats.setRushingTouchdowns(0);
texansQB.getStats().add(texansQBStats);
//Blue
Stats texansRB1Stats = new Stats();
texansRB1Stats.setSeason(season2015);
texansRB1Stats.setPlayer(texansRB1);
texansRB1Stats.setPassAttempts(0);
texansRB1Stats.setPassCompletions(0);
texansRB1Stats.setPassingYards(0);
texansRB1Stats.setPassingTouchdowns(0);
texansRB1Stats.setReceptions(15);
texansRB1Stats.setReceivingYards(109);
texansRB1Stats.setReceivingTouchdowns(1);
texansRB1Stats.setRushingAttempts(183);
texansRB1Stats.setRushingYards(698);
texansRB1Stats.setRushingTouchdowns(2);
texansRB1.getStats().add(texansRB1Stats);
//Polk
Stats texansRB2Stats = new Stats();
texansRB2Stats.setSeason(season2015);
texansRB2Stats.setPlayer(texansRB1);
texansRB2Stats.setPassAttempts(0);
texansRB2Stats.setPassCompletions(0);
texansRB2Stats.setPassingYards(0);
texansRB2Stats.setPassingTouchdowns(0);
texansRB2Stats.setReceptions(16);
texansRB2Stats.setReceivingYards(109);
texansRB2Stats.setReceivingTouchdowns(1);
texansRB2Stats.setRushingAttempts(99);
texansRB2Stats.setRushingYards(334);
texansRB2Stats.setRushingTouchdowns(1);
texansRB2.getStats().add(texansRB2Stats);
//Hopkins
Stats texansWR1Stats = new Stats();
texansWR1Stats.setSeason(season2015);
texansWR1Stats.setPlayer(texansWR1);
texansWR1Stats.setPassAttempts(0);
texansWR1Stats.setPassCompletions(0);
texansWR1Stats.setPassingYards(0);
texansWR1Stats.setPassingTouchdowns(0);
texansWR1Stats.setReceptions(111);
texansWR1Stats.setReceivingYards(1521);
texansWR1Stats.setReceivingTouchdowns(11);
texansWR1Stats.setRushingAttempts(0);
texansWR1Stats.setRushingYards(0);
texansWR1Stats.setRushingTouchdowns(0);
texansWR1.getStats().add(texansWR1Stats);
//Washington
Stats texansWR2Stats = new Stats();
texansWR2Stats.setSeason(season2015);
texansWR2Stats.setPlayer(texansWR1);
texansWR2Stats.setPassAttempts(0);
texansWR2Stats.setPassCompletions(0);
texansWR2Stats.setPassingYards(0);
texansWR2Stats.setPassingTouchdowns(0);
texansWR2Stats.setReceptions(47);
texansWR2Stats.setReceivingYards(658);
texansWR2Stats.setReceivingTouchdowns(4);
texansWR2Stats.setRushingAttempts(0);
texansWR2Stats.setRushingYards(0);
texansWR2Stats.setRushingTouchdowns(0);
texansWR2.getStats().add(texansWR2Stats);
//Colts
//Luck
Stats coltsQBStats = new Stats();
coltsQBStats.setSeason(season2015);
coltsQBStats.setPlayer(coltsQB);
coltsQBStats.setPassAttempts(293);
coltsQBStats.setPassCompletions(162);
coltsQBStats.setPassingYards(1881);
coltsQBStats.setPassingTouchdowns(15);
coltsQBStats.setReceptions(0);
coltsQBStats.setReceivingYards(0);
coltsQBStats.setReceivingTouchdowns(0);
coltsQBStats.setRushingAttempts(33);
coltsQBStats.setRushingYards(196);
coltsQBStats.setRushingTouchdowns(0);
coltsQB.getStats().add(coltsQBStats);
//Gore
Stats coltsRB1Stats = new Stats();
coltsRB1Stats.setSeason(season2015);
coltsRB1Stats.setPlayer(coltsRB1);
coltsRB1Stats.setPassAttempts(0);
coltsRB1Stats.setPassCompletions(0);
coltsRB1Stats.setPassingYards(0);
coltsRB1Stats.setPassingTouchdowns(0);
coltsRB1Stats.setReceptions(34);
coltsRB1Stats.setReceivingYards(267);
coltsRB1Stats.setReceivingTouchdowns(1);
coltsRB1Stats.setRushingAttempts(260);
coltsRB1Stats.setRushingYards(967);
coltsRB1Stats.setRushingTouchdowns(6);
coltsRB1.getStats().add(coltsRB1Stats);
//Bradshaw
Stats coltsRB2Stats = new Stats();
coltsRB2Stats.setSeason(season2015);
coltsRB2Stats.setPlayer(coltsRB1);
coltsRB2Stats.setPassAttempts(0);
coltsRB2Stats.setPassCompletions(0);
coltsRB2Stats.setPassingYards(0);
coltsRB2Stats.setPassingTouchdowns(0);
coltsRB2Stats.setReceptions(0);
coltsRB2Stats.setReceivingYards(0);
coltsRB2Stats.setReceivingTouchdowns(0);
coltsRB2Stats.setRushingAttempts(31);
coltsRB2Stats.setRushingYards(85);
coltsRB2Stats.setRushingTouchdowns(1);
coltsRB2.getStats().add(coltsRB2Stats);
//Hilton
Stats coltsWR1Stats = new Stats();
coltsWR1Stats.setSeason(season2015);
coltsWR1Stats.setPlayer(coltsWR1);
coltsWR1Stats.setPassAttempts(0);
coltsWR1Stats.setPassCompletions(0);
coltsWR1Stats.setPassingYards(0);
coltsWR1Stats.setPassingTouchdowns(0);
coltsWR1Stats.setReceptions(69);
coltsWR1Stats.setReceivingYards(1124);
coltsWR1Stats.setReceivingTouchdowns(5);
coltsWR1Stats.setRushingAttempts(0);
coltsWR1Stats.setRushingYards(0);
coltsWR1Stats.setRushingTouchdowns(0);
coltsWR1.getStats().add(coltsWR1Stats);
//Moncrief
Stats coltsWR2Stats = new Stats();
coltsWR2Stats.setSeason(season2015);
coltsWR2Stats.setPlayer(coltsWR1);
coltsWR2Stats.setPassAttempts(0);
coltsWR2Stats.setPassCompletions(0);
coltsWR2Stats.setPassingYards(0);
coltsWR2Stats.setPassingTouchdowns(0);
coltsWR2Stats.setReceptions(47);
coltsWR2Stats.setReceivingYards(733);
coltsWR2Stats.setReceivingTouchdowns(4);
coltsWR2Stats.setRushingAttempts(0);
coltsWR2Stats.setRushingYards(0);
coltsWR2Stats.setRushingTouchdowns(0);
coltsWR2.getStats().add(coltsWR2Stats);
//Steelers
//Roethlisberger
Stats steelersQBStats = new Stats();
steelersQBStats.setSeason(season2015);
steelersQBStats.setPlayer(steelersQB);
steelersQBStats.setPassAttempts(469);
steelersQBStats.setPassCompletions(319);
steelersQBStats.setPassingYards(3938);
steelersQBStats.setPassingTouchdowns(21);
steelersQBStats.setReceptions(0);
steelersQBStats.setReceivingYards(0);
steelersQBStats.setReceivingTouchdowns(0);
steelersQBStats.setRushingAttempts(15);
steelersQBStats.setRushingYards(29);
steelersQBStats.setRushingTouchdowns(0);
steelersQB.getStats().add(steelersQBStats);
//Williams
Stats steelersRB1Stats = new Stats();
steelersRB1Stats.setSeason(season2015);
steelersRB1Stats.setPlayer(steelersRB1);
steelersRB1Stats.setPassAttempts(0);
steelersRB1Stats.setPassCompletions(0);
steelersRB1Stats.setPassingYards(0);
steelersRB1Stats.setPassingTouchdowns(0);
steelersRB1Stats.setReceptions(40);
steelersRB1Stats.setReceivingYards(367);
steelersRB1Stats.setReceivingTouchdowns(0);
steelersRB1Stats.setRushingAttempts(200);
steelersRB1Stats.setRushingYards(907);
steelersRB1Stats.setRushingTouchdowns(11);
steelersRB1.getStats().add(steelersRB1Stats);
//Bell
Stats steelersRB2Stats = new Stats();
steelersRB2Stats.setSeason(season2015);
steelersRB2Stats.setPlayer(steelersRB1);
steelersRB2Stats.setPassAttempts(0);
steelersRB2Stats.setPassCompletions(0);
steelersRB2Stats.setPassingYards(0);
steelersRB2Stats.setPassingTouchdowns(0);
steelersRB2Stats.setReceptions(0);
steelersRB2Stats.setReceivingYards(0);
steelersRB2Stats.setReceivingTouchdowns(0);
steelersRB2Stats.setRushingAttempts(24);
steelersRB2Stats.setRushingYards(136);
steelersRB2Stats.setRushingTouchdowns(0);
steelersRB2.getStats().add(steelersRB2Stats);
//Brown
Stats steelersWR1Stats = new Stats();
steelersWR1Stats.setSeason(season2015);
steelersWR1Stats.setPlayer(steelersWR1);
steelersWR1Stats.setPassAttempts(0);
steelersWR1Stats.setPassCompletions(0);
steelersWR1Stats.setPassingYards(0);
steelersWR1Stats.setPassingTouchdowns(0);
steelersWR1Stats.setReceptions(136);
steelersWR1Stats.setReceivingYards(1834);
steelersWR1Stats.setReceivingTouchdowns(10);
steelersWR1Stats.setRushingAttempts(3);
steelersWR1Stats.setRushingYards(28);
steelersWR1Stats.setRushingTouchdowns(0);
steelersWR1.getStats().add(steelersWR1Stats);
//Bryan
Stats steelersWR2Stats = new Stats();
steelersWR2Stats.setSeason(season2015);
steelersWR2Stats.setPlayer(steelersWR1);
steelersWR2Stats.setPassAttempts(0);
steelersWR2Stats.setPassCompletions(0);
steelersWR2Stats.setPassingYards(0);
steelersWR2Stats.setPassingTouchdowns(0);
steelersWR2Stats.setReceptions(50);
steelersWR2Stats.setReceivingYards(764);
steelersWR2Stats.setReceivingTouchdowns(6);
steelersWR2Stats.setRushingAttempts(0);
steelersWR2Stats.setRushingYards(0);
steelersWR2Stats.setRushingTouchdowns(0);
steelersWR2.getStats().add(steelersWR2Stats);
//Bengals
//Dalton
Stats bengalsQBStats = new Stats();
bengalsQBStats.setSeason(season2015);
bengalsQBStats.setPlayer(bengalsQB);
bengalsQBStats.setPassAttempts(386);
bengalsQBStats.setPassCompletions(255);
bengalsQBStats.setPassingYards(3250);
bengalsQBStats.setPassingTouchdowns(25);
bengalsQBStats.setReceptions(0);
bengalsQBStats.setReceivingYards(0);
bengalsQBStats.setReceivingTouchdowns(0);
bengalsQBStats.setRushingAttempts(57);
bengalsQBStats.setRushingYards(142);
bengalsQBStats.setRushingTouchdowns(3);
bengalsQB.getStats().add(bengalsQBStats);
//Hill
Stats bengalsRB1Stats = new Stats();
bengalsRB1Stats.setSeason(season2015);
bengalsRB1Stats.setPlayer(bengalsRB1);
bengalsRB1Stats.setPassAttempts(0);
bengalsRB1Stats.setPassCompletions(0);
bengalsRB1Stats.setPassingYards(0);
bengalsRB1Stats.setPassingTouchdowns(0);
bengalsRB1Stats.setReceptions(15);
bengalsRB1Stats.setReceivingYards(79);
bengalsRB1Stats.setReceivingTouchdowns(1);
bengalsRB1Stats.setRushingAttempts(223);
bengalsRB1Stats.setRushingYards(794);
bengalsRB1Stats.setRushingTouchdowns(11);
bengalsRB1.getStats().add(bengalsRB1Stats);
//Bernard
Stats bengalsRB2Stats = new Stats();
bengalsRB2Stats.setSeason(season2015);
bengalsRB2Stats.setPlayer(bengalsRB1);
bengalsRB2Stats.setPassAttempts(0);
bengalsRB2Stats.setPassCompletions(0);
bengalsRB2Stats.setPassingYards(0);
bengalsRB2Stats.setPassingTouchdowns(0);
bengalsRB2Stats.setReceptions(49);
bengalsRB2Stats.setReceivingYards(472);
bengalsRB2Stats.setReceivingTouchdowns(0);
bengalsRB2Stats.setRushingAttempts(154);
bengalsRB2Stats.setRushingYards(730);
bengalsRB2Stats.setRushingTouchdowns(2);
bengalsRB2.getStats().add(bengalsRB2Stats);
//Green
Stats bengalsWR1Stats = new Stats();
bengalsWR1Stats.setSeason(season2015);
bengalsWR1Stats.setPlayer(bengalsWR1);
bengalsWR1Stats.setPassAttempts(0);
bengalsWR1Stats.setPassCompletions(0);
bengalsWR1Stats.setPassingYards(0);
bengalsWR1Stats.setPassingTouchdowns(0);
bengalsWR1Stats.setReceptions(86);
bengalsWR1Stats.setReceivingYards(1297);
bengalsWR1Stats.setReceivingTouchdowns(10);
bengalsWR1Stats.setRushingAttempts(0);
bengalsWR1Stats.setRushingYards(0);
bengalsWR1Stats.setRushingTouchdowns(0);
bengalsWR1.getStats().add(bengalsWR1Stats);
//Jones
Stats bengalsWR2Stats = new Stats();
bengalsWR2Stats.setSeason(season2015);
bengalsWR2Stats.setPlayer(bengalsWR1);
bengalsWR2Stats.setPassAttempts(0);
bengalsWR2Stats.setPassCompletions(0);
bengalsWR2Stats.setPassingYards(0);
bengalsWR2Stats.setPassingTouchdowns(0);
bengalsWR2Stats.setReceptions(65);
bengalsWR2Stats.setReceivingYards(816);
bengalsWR2Stats.setReceivingTouchdowns(4);
bengalsWR2Stats.setRushingAttempts(5);
bengalsWR2Stats.setRushingYards(33);
bengalsWR2Stats.setRushingTouchdowns(0);
bengalsWR2.getStats().add(bengalsWR2Stats);
//Browns
//McCown
Stats brownsQBStats = new Stats();
brownsQBStats.setSeason(season2015);
brownsQBStats.setPlayer(brownsQB);
brownsQBStats.setPassAttempts(292);
brownsQBStats.setPassCompletions(186);
brownsQBStats.setPassingYards(2109);
brownsQBStats.setPassingTouchdowns(12);
brownsQBStats.setReceptions(0);
brownsQBStats.setReceivingYards(0);
brownsQBStats.setReceivingTouchdowns(0);
brownsQBStats.setRushingAttempts(20);
brownsQBStats.setRushingYards(98);
brownsQBStats.setRushingTouchdowns(1);
brownsQB.getStats().add(brownsQBStats);
//Crowell
Stats brownsRB1Stats = new Stats();
brownsRB1Stats.setSeason(season2015);
brownsRB1Stats.setPlayer(brownsRB1);
brownsRB1Stats.setPassAttempts(0);
brownsRB1Stats.setPassCompletions(0);
brownsRB1Stats.setPassingYards(0);
brownsRB1Stats.setPassingTouchdowns(0);
brownsRB1Stats.setReceptions(19);
brownsRB1Stats.setReceivingYards(182);
brownsRB1Stats.setReceivingTouchdowns(1);
brownsRB1Stats.setRushingAttempts(185);
brownsRB1Stats.setRushingYards(706);
brownsRB1Stats.setRushingTouchdowns(4);
brownsRB1.getStats().add(brownsRB1Stats);
//Johnson Jr.
Stats brownsRB2Stats = new Stats();
brownsRB2Stats.setSeason(season2015);
brownsRB2Stats.setPlayer(brownsRB1);
brownsRB2Stats.setPassAttempts(0);
brownsRB2Stats.setPassCompletions(0);
brownsRB2Stats.setPassingYards(0);
brownsRB2Stats.setPassingTouchdowns(0);
brownsRB2Stats.setReceptions(61);
brownsRB2Stats.setReceivingYards(534);
brownsRB2Stats.setReceivingTouchdowns(2);
brownsRB2Stats.setRushingAttempts(104);
brownsRB2Stats.setRushingYards(379);
brownsRB2Stats.setRushingTouchdowns(2);
brownsRB2.getStats().add(brownsRB2Stats);
//Benjamin
Stats brownsWR1Stats = new Stats();
brownsWR1Stats.setSeason(season2015);
brownsWR1Stats.setPlayer(brownsWR1);
brownsWR1Stats.setPassAttempts(0);
brownsWR1Stats.setPassCompletions(0);
brownsWR1Stats.setPassingYards(0);
brownsWR1Stats.setPassingTouchdowns(0);
brownsWR1Stats.setReceptions(68);
brownsWR1Stats.setReceivingYards(966);
brownsWR1Stats.setReceivingTouchdowns(5);
brownsWR1Stats.setRushingAttempts(4);
brownsWR1Stats.setRushingYards(12);
brownsWR1Stats.setRushingTouchdowns(0);
brownsWR1.getStats().add(brownsWR1Stats);
//Hartline
Stats brownsWR2Stats = new Stats();
brownsWR2Stats.setSeason(season2015);
brownsWR2Stats.setPlayer(brownsWR1);
brownsWR2Stats.setPassAttempts(0);
brownsWR2Stats.setPassCompletions(0);
brownsWR2Stats.setPassingYards(0);
brownsWR2Stats.setPassingTouchdowns(0);
brownsWR2Stats.setReceptions(46);
brownsWR2Stats.setReceivingYards(523);
brownsWR2Stats.setReceivingTouchdowns(2);
brownsWR2Stats.setRushingAttempts(0);
brownsWR2Stats.setRushingYards(0);
brownsWR2Stats.setRushingTouchdowns(0);
brownsWR2.getStats().add(brownsWR2Stats);
//Jaguars
//Bortles
Stats jaguarsQBStats = new Stats();
jaguarsQBStats.setSeason(season2015);
jaguarsQBStats.setPlayer(jaguarsQB);
jaguarsQBStats.setPassAttempts(606);
jaguarsQBStats.setPassCompletions(355);
jaguarsQBStats.setPassingYards(4428);
jaguarsQBStats.setPassingTouchdowns(35);
jaguarsQBStats.setReceptions(0);
jaguarsQBStats.setReceivingYards(0);
jaguarsQBStats.setReceivingTouchdowns(0);
jaguarsQBStats.setRushingAttempts(52);
jaguarsQBStats.setRushingYards(310);
jaguarsQBStats.setRushingTouchdowns(2);
jaguarsQB.getStats().add(jaguarsQBStats);
//Yeldon
Stats jaguarsRB1Stats = new Stats();
jaguarsRB1Stats.setSeason(season2015);
jaguarsRB1Stats.setPlayer(jaguarsRB1);
jaguarsRB1Stats.setPassAttempts(0);
jaguarsRB1Stats.setPassCompletions(0);
jaguarsRB1Stats.setPassingYards(0);
jaguarsRB1Stats.setPassingTouchdowns(0);
jaguarsRB1Stats.setReceptions(36);
jaguarsRB1Stats.setReceivingYards(279);
jaguarsRB1Stats.setReceivingTouchdowns(1);
jaguarsRB1Stats.setRushingAttempts(182);
jaguarsRB1Stats.setRushingYards(740);
jaguarsRB1Stats.setRushingTouchdowns(2);
jaguarsRB1.getStats().add(jaguarsRB1Stats);
//Robinson
Stats jaguarsRB2Stats = new Stats();
jaguarsRB2Stats.setSeason(season2015);
jaguarsRB2Stats.setPlayer(jaguarsRB1);
jaguarsRB2Stats.setPassAttempts(0);
jaguarsRB2Stats.setPassCompletions(0);
jaguarsRB2Stats.setPassingYards(0);
jaguarsRB2Stats.setPassingTouchdowns(0);
jaguarsRB2Stats.setReceptions(21);
jaguarsRB2Stats.setReceivingYards(164);
jaguarsRB2Stats.setReceivingTouchdowns(0);
jaguarsRB2Stats.setRushingAttempts(67);
jaguarsRB2Stats.setRushingYards(266);
jaguarsRB2Stats.setRushingTouchdowns(1);
jaguarsRB2.getStats().add(jaguarsRB2Stats);
//Robinson
Stats jaguarsWR1Stats = new Stats();
jaguarsWR1Stats.setSeason(season2015);
jaguarsWR1Stats.setPlayer(jaguarsWR1);
jaguarsWR1Stats.setPassAttempts(0);
jaguarsWR1Stats.setPassCompletions(0);
jaguarsWR1Stats.setPassingYards(0);
jaguarsWR1Stats.setPassingTouchdowns(0);
jaguarsWR1Stats.setReceptions(80);
jaguarsWR1Stats.setReceivingYards(1400);
jaguarsWR1Stats.setReceivingTouchdowns(14);
jaguarsWR1Stats.setRushingAttempts(0);
jaguarsWR1Stats.setRushingYards(0);
jaguarsWR1Stats.setRushingTouchdowns(0);
jaguarsWR1.getStats().add(jaguarsWR1Stats);
//Herns
Stats jaguarsWR2Stats = new Stats();
jaguarsWR2Stats.setSeason(season2015);
jaguarsWR2Stats.setPlayer(jaguarsWR1);
jaguarsWR2Stats.setPassAttempts(0);
jaguarsWR2Stats.setPassCompletions(0);
jaguarsWR2Stats.setPassingYards(0);
jaguarsWR2Stats.setPassingTouchdowns(0);
jaguarsWR2Stats.setReceptions(64);
jaguarsWR2Stats.setReceivingYards(1031);
jaguarsWR2Stats.setReceivingTouchdowns(10);
jaguarsWR2Stats.setRushingAttempts(0);
jaguarsWR2Stats.setRushingYards(0);
jaguarsWR2Stats.setRushingTouchdowns(0);
jaguarsWR2.getStats().add(jaguarsWR2Stats);
//Titans
//Mariota
Stats titansQBStats = new Stats();
titansQBStats.setSeason(season2015);
titansQBStats.setPlayer(titansQB);
titansQBStats.setPassAttempts(370);
titansQBStats.setPassCompletions(230);
titansQBStats.setPassingYards(2818);
titansQBStats.setPassingTouchdowns(19);
titansQBStats.setReceptions(0);
titansQBStats.setReceivingYards(0);
titansQBStats.setReceivingTouchdowns(0);
titansQBStats.setRushingAttempts(34);
titansQBStats.setRushingYards(252);
titansQBStats.setRushingTouchdowns(2);
titansQB.getStats().add(titansQBStats);
//Andrews
Stats titansRB1Stats = new Stats();
titansRB1Stats.setSeason(season2015);
titansRB1Stats.setPlayer(titansRB1);
titansRB1Stats.setPassAttempts(0);
titansRB1Stats.setPassCompletions(0);
titansRB1Stats.setPassingYards(0);
titansRB1Stats.setPassingTouchdowns(0);
titansRB1Stats.setReceptions(21);
titansRB1Stats.setReceivingYards(174);
titansRB1Stats.setReceivingTouchdowns(0);
titansRB1Stats.setRushingAttempts(143);
titansRB1Stats.setRushingYards(520);
titansRB1Stats.setRushingTouchdowns(3);
titansRB1.getStats().add(titansRB1Stats);
//McCluster
Stats titansRB2Stats = new Stats();
titansRB2Stats.setSeason(season2015);
titansRB2Stats.setPlayer(titansRB1);
titansRB2Stats.setPassAttempts(0);
titansRB2Stats.setPassCompletions(0);
titansRB2Stats.setPassingYards(0);
titansRB2Stats.setPassingTouchdowns(0);
titansRB2Stats.setReceptions(31);
titansRB2Stats.setReceivingYards(260);
titansRB2Stats.setReceivingTouchdowns(1);
titansRB2Stats.setRushingAttempts(55);
titansRB2Stats.setRushingYards(247);
titansRB2Stats.setRushingTouchdowns(1);
titansRB2.getStats().add(titansRB2Stats);
//Green-Beckham
Stats titansWR1Stats = new Stats();
titansWR1Stats.setSeason(season2015);
titansWR1Stats.setPlayer(titansWR1);
titansWR1Stats.setPassAttempts(0);
titansWR1Stats.setPassCompletions(0);
titansWR1Stats.setPassingYards(0);
titansWR1Stats.setPassingTouchdowns(0);
titansWR1Stats.setReceptions(32);
titansWR1Stats.setReceivingYards(549);
titansWR1Stats.setReceivingTouchdowns(4);
titansWR1Stats.setRushingAttempts(0);
titansWR1Stats.setRushingYards(0);
titansWR1Stats.setRushingTouchdowns(0);
titansWR1.getStats().add(titansWR1Stats);
//Douglas
Stats titansWR2Stats = new Stats();
titansWR2Stats.setSeason(season2015);
titansWR2Stats.setPlayer(titansWR1);
titansWR2Stats.setPassAttempts(0);
titansWR2Stats.setPassCompletions(0);
titansWR2Stats.setPassingYards(0);
titansWR2Stats.setPassingTouchdowns(0);
titansWR2Stats.setReceptions(36);
titansWR2Stats.setReceivingYards(411);
titansWR2Stats.setReceivingTouchdowns(2);
titansWR2Stats.setRushingAttempts(0);
titansWR2Stats.setRushingYards(0);
titansWR2Stats.setRushingTouchdowns(0);
titansWR2.getStats().add(titansWR2Stats);
//Seahawks
//Wilson
Stats seahawksQBStats = new Stats();
seahawksQBStats.setSeason(season2015);
seahawksQBStats.setPlayer(seahawksQB);
seahawksQBStats.setPassAttempts(483);
seahawksQBStats.setPassCompletions(329);
seahawksQBStats.setPassingYards(4024);
seahawksQBStats.setPassingTouchdowns(34);
seahawksQBStats.setReceptions(0);
seahawksQBStats.setReceivingYards(0);
seahawksQBStats.setReceivingTouchdowns(0);
seahawksQBStats.setRushingAttempts(103);
seahawksQBStats.setRushingYards(553);
seahawksQBStats.setRushingTouchdowns(1);
seahawksQB.getStats().add(seahawksQBStats);
//Rawls
Stats seahawksRB1Stats = new Stats();
seahawksRB1Stats.setSeason(season2015);
seahawksRB1Stats.setPlayer(seahawksRB1);
seahawksRB1Stats.setPassAttempts(0);
seahawksRB1Stats.setPassCompletions(0);
seahawksRB1Stats.setPassingYards(0);
seahawksRB1Stats.setPassingTouchdowns(0);
seahawksRB1Stats.setReceptions(9);
seahawksRB1Stats.setReceivingYards(11);
seahawksRB1Stats.setReceivingTouchdowns(1);
seahawksRB1Stats.setRushingAttempts(147);
seahawksRB1Stats.setRushingYards(830);
seahawksRB1Stats.setRushingTouchdowns(4);
seahawksRB1.getStats().add(seahawksRB1Stats);
//Lynch
Stats seahawksRB2Stats = new Stats();
seahawksRB2Stats.setSeason(season2015);
seahawksRB2Stats.setPlayer(seahawksRB1);
seahawksRB2Stats.setPassAttempts(0);
seahawksRB2Stats.setPassCompletions(0);
seahawksRB2Stats.setPassingYards(0);
seahawksRB2Stats.setPassingTouchdowns(0);
seahawksRB2Stats.setReceptions(13);
seahawksRB2Stats.setReceivingYards(80);
seahawksRB2Stats.setReceivingTouchdowns(0);
seahawksRB2Stats.setRushingAttempts(111);
seahawksRB2Stats.setRushingYards(417);
seahawksRB2Stats.setRushingTouchdowns(3);
seahawksRB2.getStats().add(seahawksRB2Stats);
//Baldwin
Stats seahawksWR1Stats = new Stats();
seahawksWR1Stats.setSeason(season2015);
seahawksWR1Stats.setPlayer(seahawksWR1);
seahawksWR1Stats.setPassAttempts(0);
seahawksWR1Stats.setPassCompletions(0);
seahawksWR1Stats.setPassingYards(0);
seahawksWR1Stats.setPassingTouchdowns(0);
seahawksWR1Stats.setReceptions(78);
seahawksWR1Stats.setReceivingYards(1069);
seahawksWR1Stats.setReceivingTouchdowns(14);
seahawksWR1Stats.setRushingAttempts(0);
seahawksWR1Stats.setRushingYards(0);
seahawksWR1Stats.setRushingTouchdowns(0);
seahawksWR1.getStats().add(seahawksWR1Stats);
//Kearse
Stats seahawksWR2Stats = new Stats();
seahawksWR2Stats.setSeason(season2015);
seahawksWR2Stats.setPlayer(seahawksWR1);
seahawksWR2Stats.setPassAttempts(0);
seahawksWR2Stats.setPassCompletions(0);
seahawksWR2Stats.setPassingYards(0);
seahawksWR2Stats.setPassingTouchdowns(0);
seahawksWR2Stats.setReceptions(49);
seahawksWR2Stats.setReceivingYards(685);
seahawksWR2Stats.setReceivingTouchdowns(5);
seahawksWR2Stats.setRushingAttempts(0);
seahawksWR2Stats.setRushingYards(0);
seahawksWR2Stats.setRushingTouchdowns(0);
seahawksWR2.getStats().add(seahawksWR2Stats);
//Rams
//Foles
Stats ramsQBStats = new Stats();
ramsQBStats.setSeason(season2015);
ramsQBStats.setPlayer(ramsQB);
ramsQBStats.setPassAttempts(337);
ramsQBStats.setPassCompletions(190);
ramsQBStats.setPassingYards(2052);
ramsQBStats.setPassingTouchdowns(7);
ramsQBStats.setReceptions(0);
ramsQBStats.setReceivingYards(0);
ramsQBStats.setReceivingTouchdowns(0);
ramsQBStats.setRushingAttempts(17);
ramsQBStats.setRushingYards(20);
ramsQBStats.setRushingTouchdowns(1);
ramsQB.getStats().add(ramsQBStats);
//Gurley
Stats ramsRB1Stats = new Stats();
ramsRB1Stats.setSeason(season2015);
ramsRB1Stats.setPlayer(ramsRB1);
ramsRB1Stats.setPassAttempts(0);
ramsRB1Stats.setPassCompletions(0);
ramsRB1Stats.setPassingYards(0);
ramsRB1Stats.setPassingTouchdowns(0);
ramsRB1Stats.setReceptions(21);
ramsRB1Stats.setReceivingYards(188);
ramsRB1Stats.setReceivingTouchdowns(0);
ramsRB1Stats.setRushingAttempts(229);
ramsRB1Stats.setRushingYards(1106);
ramsRB1Stats.setRushingTouchdowns(10);
ramsRB1.getStats().add(ramsRB1Stats);
//Austin
Stats ramsRB2Stats = new Stats();
ramsRB2Stats.setSeason(season2015);
ramsRB2Stats.setPlayer(ramsRB1);
ramsRB2Stats.setPassAttempts(0);
ramsRB2Stats.setPassCompletions(0);
ramsRB2Stats.setPassingYards(0);
ramsRB2Stats.setPassingTouchdowns(0);
ramsRB2Stats.setReceptions(52);
ramsRB2Stats.setReceivingYards(473);
ramsRB2Stats.setReceivingTouchdowns(5);
ramsRB2Stats.setRushingAttempts(52);
ramsRB2Stats.setRushingYards(434);
ramsRB2Stats.setRushingTouchdowns(4);
ramsRB2.getStats().add(ramsRB2Stats);
//Britt
Stats ramsWR1Stats = new Stats();
ramsWR1Stats.setSeason(season2015);
ramsWR1Stats.setPlayer(ramsWR1);
ramsWR1Stats.setPassAttempts(0);
ramsWR1Stats.setPassCompletions(0);
ramsWR1Stats.setPassingYards(0);
ramsWR1Stats.setPassingTouchdowns(0);
ramsWR1Stats.setReceptions(36);
ramsWR1Stats.setReceivingYards(681);
ramsWR1Stats.setReceivingTouchdowns(3);
ramsWR1Stats.setRushingAttempts(0);
ramsWR1Stats.setRushingYards(0);
ramsWR1Stats.setRushingTouchdowns(0);
ramsWR1.getStats().add(ramsWR1Stats);
//Cunningham
Stats ramsWR2Stats = new Stats();
ramsWR2Stats.setSeason(season2015);
ramsWR2Stats.setPlayer(ramsWR1);
ramsWR2Stats.setPassAttempts(0);
ramsWR2Stats.setPassCompletions(0);
ramsWR2Stats.setPassingYards(0);
ramsWR2Stats.setPassingTouchdowns(0);
ramsWR2Stats.setReceptions(26);
ramsWR2Stats.setReceivingYards(250);
ramsWR2Stats.setReceivingTouchdowns(0);
ramsWR2Stats.setRushingAttempts(0);
ramsWR2Stats.setRushingYards(0);
ramsWR2Stats.setRushingTouchdowns(0);
ramsWR2.getStats().add(ramsWR2Stats);
//49ers
//Gabbert
Stats ninersQBStats = new Stats();
ninersQBStats.setSeason(season2015);
ninersQBStats.setPlayer(ninersQB);
ninersQBStats.setPassAttempts(282);
ninersQBStats.setPassCompletions(178);
ninersQBStats.setPassingYards(2031);
ninersQBStats.setPassingTouchdowns(10);
ninersQBStats.setReceptions(0);
ninersQBStats.setReceivingYards(0);
ninersQBStats.setReceivingTouchdowns(0);
ninersQBStats.setRushingAttempts(32);
ninersQBStats.setRushingYards(185);
ninersQBStats.setRushingTouchdowns(1);
ninersQB.getStats().add(ninersQBStats);
//Hyde
Stats ninersRB1Stats = new Stats();
ninersRB1Stats.setSeason(season2015);
ninersRB1Stats.setPlayer(ninersRB1);
ninersRB1Stats.setPassAttempts(0);
ninersRB1Stats.setPassCompletions(0);
ninersRB1Stats.setPassingYards(0);
ninersRB1Stats.setPassingTouchdowns(0);
ninersRB1Stats.setReceptions(11);
ninersRB1Stats.setReceivingYards(15);
ninersRB1Stats.setReceivingTouchdowns(0);
ninersRB1Stats.setRushingAttempts(115);
ninersRB1Stats.setRushingYards(470);
ninersRB1Stats.setRushingTouchdowns(3);
ninersRB1.getStats().add(ninersRB1Stats);
//Draughn
Stats ninersRB2Stats = new Stats();
ninersRB2Stats.setSeason(season2015);
ninersRB2Stats.setPlayer(ninersRB1);
ninersRB2Stats.setPassAttempts(0);
ninersRB2Stats.setPassCompletions(0);
ninersRB2Stats.setPassingYards(0);
ninersRB2Stats.setPassingTouchdowns(0);
ninersRB2Stats.setReceptions(25);
ninersRB2Stats.setReceivingYards(32);
ninersRB2Stats.setReceivingTouchdowns(0);
ninersRB2Stats.setRushingAttempts(76);
ninersRB2Stats.setRushingYards(263);
ninersRB2Stats.setRushingTouchdowns(1);
ninersRB2.getStats().add(ninersRB2Stats);
//Boldin
Stats ninersWR1Stats = new Stats();
ninersWR1Stats.setSeason(season2015);
ninersWR1Stats.setPlayer(ninersWR1);
ninersWR1Stats.setPassAttempts(0);
ninersWR1Stats.setPassCompletions(0);
ninersWR1Stats.setPassingYards(0);
ninersWR1Stats.setPassingTouchdowns(0);
ninersWR1Stats.setReceptions(69);
ninersWR1Stats.setReceivingYards(789);
ninersWR1Stats.setReceivingTouchdowns(4);
ninersWR1Stats.setRushingAttempts(0);
ninersWR1Stats.setRushingYards(0);
ninersWR1Stats.setRushingTouchdowns(0);
ninersWR1.getStats().add(ninersWR1Stats);
//Smith
Stats ninersWR2Stats = new Stats();
ninersWR2Stats.setSeason(season2015);
ninersWR2Stats.setPlayer(ninersWR1);
ninersWR2Stats.setPassAttempts(0);
ninersWR2Stats.setPassCompletions(0);
ninersWR2Stats.setPassingYards(0);
ninersWR2Stats.setPassingTouchdowns(0);
ninersWR2Stats.setReceptions(33);
ninersWR2Stats.setReceivingYards(663);
ninersWR2Stats.setReceivingTouchdowns(4);
ninersWR2Stats.setRushingAttempts(0);
ninersWR2Stats.setRushingYards(0);
ninersWR2Stats.setRushingTouchdowns(0);
ninersWR2.getStats().add(ninersWR2Stats);
//Cardinals
//Palmer
Stats cardinalsQBStats = new Stats();
cardinalsQBStats.setSeason(season2015);
cardinalsQBStats.setPlayer(cardinalsQB);
cardinalsQBStats.setPassAttempts(537);
cardinalsQBStats.setPassCompletions(342);
cardinalsQBStats.setPassingYards(2031);
cardinalsQBStats.setPassingTouchdowns(35);
cardinalsQBStats.setReceptions(0);
cardinalsQBStats.setReceivingYards(0);
cardinalsQBStats.setReceivingTouchdowns(0);
cardinalsQBStats.setRushingAttempts(25);
cardinalsQBStats.setRushingYards(14);
cardinalsQBStats.setRushingTouchdowns(1);
cardinalsQB.getStats().add(cardinalsQBStats);
//Chris Johnson
Stats cardinalsRB1Stats = new Stats();
cardinalsRB1Stats.setSeason(season2015);
cardinalsRB1Stats.setPlayer(cardinalsRB1);
cardinalsRB1Stats.setPassAttempts(0);
cardinalsRB1Stats.setPassCompletions(0);
cardinalsRB1Stats.setPassingYards(0);
cardinalsRB1Stats.setPassingTouchdowns(0);
cardinalsRB1Stats.setReceptions(6);
cardinalsRB1Stats.setReceivingYards(58);
cardinalsRB1Stats.setReceivingTouchdowns(0);
cardinalsRB1Stats.setRushingAttempts(196);
cardinalsRB1Stats.setRushingYards(814);
cardinalsRB1Stats.setRushingTouchdowns(3);
cardinalsRB1.getStats().add(cardinalsRB1Stats);
//David Johnson
Stats cardinalsRB2Stats = new Stats();
cardinalsRB2Stats.setSeason(season2015);
cardinalsRB2Stats.setPlayer(cardinalsRB1);
cardinalsRB2Stats.setPassAttempts(0);
cardinalsRB2Stats.setPassCompletions(0);
cardinalsRB2Stats.setPassingYards(0);
cardinalsRB2Stats.setPassingTouchdowns(0);
cardinalsRB2Stats.setReceptions(36);
cardinalsRB2Stats.setReceivingYards(457);
cardinalsRB2Stats.setReceivingTouchdowns(4);
cardinalsRB2Stats.setRushingAttempts(125);
cardinalsRB2Stats.setRushingYards(581);
cardinalsRB2Stats.setRushingTouchdowns(8);
cardinalsRB2.getStats().add(cardinalsRB2Stats);
//Fitzgerald
Stats cardinalsWR1Stats = new Stats();
cardinalsWR1Stats.setSeason(season2015);
cardinalsWR1Stats.setPlayer(cardinalsRB1);
cardinalsWR1Stats.setPassAttempts(0);
cardinalsWR1Stats.setPassCompletions(0);
cardinalsWR1Stats.setPassingYards(0);
cardinalsWR1Stats.setPassingTouchdowns(0);
cardinalsWR1Stats.setReceptions(109);
cardinalsWR1Stats.setReceivingYards(1215);
cardinalsWR1Stats.setReceivingTouchdowns(9);
cardinalsWR1Stats.setRushingAttempts(0);
cardinalsWR1Stats.setRushingYards(0);
cardinalsWR1Stats.setRushingTouchdowns(0);
cardinalsWR1.getStats().add(cardinalsWR1Stats);
//Brown
Stats cardinalsWR2Stats = new Stats();
cardinalsWR2Stats.setSeason(season2015);
cardinalsWR2Stats.setPlayer(cardinalsWR1);
cardinalsWR2Stats.setPassAttempts(0);
cardinalsWR2Stats.setPassCompletions(0);
cardinalsWR2Stats.setPassingYards(0);
cardinalsWR2Stats.setPassingTouchdowns(0);
cardinalsWR2Stats.setReceptions(65);
cardinalsWR2Stats.setReceivingYards(1003);
cardinalsWR2Stats.setReceivingTouchdowns(7);
cardinalsWR2Stats.setRushingAttempts(0);
cardinalsWR2Stats.setRushingYards(0);
cardinalsWR2Stats.setRushingTouchdowns(0);
cardinalsWR2.getStats().add(cardinalsWR2Stats);
//Panthers
//Newton
Stats panthersQBStats = new Stats();
panthersQBStats.setSeason(season2015);
panthersQBStats.setPlayer(panthersQB);
panthersQBStats.setPassAttempts(495);
panthersQBStats.setPassCompletions(296);
panthersQBStats.setPassingYards(3837);
panthersQBStats.setPassingTouchdowns(35);
panthersQBStats.setReceptions(0);
panthersQBStats.setReceivingYards(0);
panthersQBStats.setReceivingTouchdowns(0);
panthersQBStats.setRushingAttempts(132);
panthersQBStats.setRushingYards(636);
panthersQBStats.setRushingTouchdowns(10);
panthersQB.getStats().add(panthersQBStats);
//Stewart
Stats panthersRB1Stats = new Stats();
panthersRB1Stats.setSeason(season2015);
panthersRB1Stats.setPlayer(panthersRB1);
panthersRB1Stats.setPassAttempts(0);
panthersRB1Stats.setPassCompletions(0);
panthersRB1Stats.setPassingYards(0);
panthersRB1Stats.setPassingTouchdowns(0);
panthersRB1Stats.setReceptions(16);
panthersRB1Stats.setReceivingYards(99);
panthersRB1Stats.setReceivingTouchdowns(1);
panthersRB1Stats.setRushingAttempts(242);
panthersRB1Stats.setRushingYards(989);
panthersRB1Stats.setRushingTouchdowns(6);
panthersRB1.getStats().add(panthersRB1Stats);
//Tolbert
Stats panthersRB2Stats = new Stats();
panthersRB2Stats.setSeason(season2015);
panthersRB2Stats.setPlayer(panthersRB1);
panthersRB2Stats.setPassAttempts(0);
panthersRB2Stats.setPassCompletions(0);
panthersRB2Stats.setPassingYards(0);
panthersRB2Stats.setPassingTouchdowns(0);
panthersRB2Stats.setReceptions(18);
panthersRB2Stats.setReceivingYards(154);
panthersRB2Stats.setReceivingTouchdowns(3);
panthersRB2Stats.setRushingAttempts(62);
panthersRB2Stats.setRushingYards(256);
panthersRB2Stats.setRushingTouchdowns(1);
panthersRB2.getStats().add(panthersRB2Stats);
//Ginn Jr.
Stats panthersWR1Stats = new Stats();
panthersWR1Stats.setSeason(season2015);
panthersWR1Stats.setPlayer(panthersRB1);
panthersWR1Stats.setPassAttempts(0);
panthersWR1Stats.setPassCompletions(0);
panthersWR1Stats.setPassingYards(0);
panthersWR1Stats.setPassingTouchdowns(0);
panthersWR1Stats.setReceptions(44);
panthersWR1Stats.setReceivingYards(739);
panthersWR1Stats.setReceivingTouchdowns(10);
panthersWR1Stats.setRushingAttempts(4);
panthersWR1Stats.setRushingYards(60);
panthersWR1Stats.setRushingTouchdowns(0);
panthersWR1.getStats().add(panthersWR1Stats);
//Cotchery
Stats panthersWR2Stats = new Stats();
panthersWR2Stats.setSeason(season2015);
panthersWR2Stats.setPlayer(panthersWR1);
panthersWR2Stats.setPassAttempts(0);
panthersWR2Stats.setPassCompletions(0);
panthersWR2Stats.setPassingYards(0);
panthersWR2Stats.setPassingTouchdowns(0);
panthersWR2Stats.setReceptions(39);
panthersWR2Stats.setReceivingYards(485);
panthersWR2Stats.setReceivingTouchdowns(3);
panthersWR2Stats.setRushingAttempts(1);
panthersWR2Stats.setRushingYards(0);
panthersWR2Stats.setRushingTouchdowns(0);
panthersWR2.getStats().add(panthersWR2Stats);
//Falcons
//Ryan
Stats falconsQBStats = new Stats();
falconsQBStats.setSeason(season2015);
falconsQBStats.setPlayer(falconsQB);
falconsQBStats.setPassAttempts(614);
falconsQBStats.setPassCompletions(407);
falconsQBStats.setPassingYards(4591);
falconsQBStats.setPassingTouchdowns(21);
falconsQBStats.setReceptions(0);
falconsQBStats.setReceivingYards(0);
falconsQBStats.setReceivingTouchdowns(0);
falconsQBStats.setRushingAttempts(37);
falconsQBStats.setRushingYards(63);
falconsQBStats.setRushingTouchdowns(0);
falconsQB.getStats().add(falconsQBStats);
//Freeman
Stats falconsRB1Stats = new Stats();
falconsRB1Stats.setSeason(season2015);
falconsRB1Stats.setPlayer(falconsRB1);
falconsRB1Stats.setPassAttempts(0);
falconsRB1Stats.setPassCompletions(0);
falconsRB1Stats.setPassingYards(0);
falconsRB1Stats.setPassingTouchdowns(0);
falconsRB1Stats.setReceptions(73);
falconsRB1Stats.setReceivingYards(578);
falconsRB1Stats.setReceivingTouchdowns(3);
falconsRB1Stats.setRushingAttempts(264);
falconsRB1Stats.setRushingYards(1061);
falconsRB1Stats.setRushingTouchdowns(11);
falconsRB1.getStats().add(falconsRB1Stats);
//Colman
Stats falconsRB2Stats = new Stats();
falconsRB2Stats.setSeason(season2015);
falconsRB2Stats.setPlayer(falconsRB1);
falconsRB2Stats.setPassAttempts(0);
falconsRB2Stats.setPassCompletions(0);
falconsRB2Stats.setPassingYards(0);
falconsRB2Stats.setPassingTouchdowns(0);
falconsRB2Stats.setReceptions(18);
falconsRB2Stats.setReceivingYards(154);
falconsRB2Stats.setReceivingTouchdowns(3);
falconsRB2Stats.setRushingAttempts(2);
falconsRB2Stats.setRushingYards(14);
falconsRB2Stats.setRushingTouchdowns(0);
falconsRB2.getStats().add(falconsRB2Stats);
//Jones
Stats falconsWR1Stats = new Stats();
falconsWR1Stats.setSeason(season2015);
falconsWR1Stats.setPlayer(falconsRB1);
falconsWR1Stats.setPassAttempts(0);
falconsWR1Stats.setPassCompletions(0);
falconsWR1Stats.setPassingYards(0);
falconsWR1Stats.setPassingTouchdowns(0);
falconsWR1Stats.setReceptions(136);
falconsWR1Stats.setReceivingYards(1871);
falconsWR1Stats.setReceivingTouchdowns(8);
falconsWR1Stats.setRushingAttempts(0);
falconsWR1Stats.setRushingYards(0);
falconsWR1Stats.setRushingTouchdowns(0);
falconsWR1.getStats().add(falconsWR1Stats);
//White
Stats falconsWR2Stats = new Stats();
falconsWR2Stats.setSeason(season2015);
falconsWR2Stats.setPlayer(falconsWR1);
falconsWR2Stats.setPassAttempts(0);
falconsWR2Stats.setPassCompletions(0);
falconsWR2Stats.setPassingYards(0);
falconsWR2Stats.setPassingTouchdowns(0);
falconsWR2Stats.setReceptions(43);
falconsWR2Stats.setReceivingYards(506);
falconsWR2Stats.setReceivingTouchdowns(1);
falconsWR2Stats.setRushingAttempts(0);
falconsWR2Stats.setRushingYards(0);
falconsWR2Stats.setRushingTouchdowns(0);
falconsWR2.getStats().add(falconsWR2Stats);
//Bucks
//Winston
Stats buccaneersQBStats = new Stats();
buccaneersQBStats.setSeason(season2015);
buccaneersQBStats.setPlayer(buccaneersQB);
buccaneersQBStats.setPassAttempts(535);
buccaneersQBStats.setPassCompletions(312);
buccaneersQBStats.setPassingYards(4042);
buccaneersQBStats.setPassingTouchdowns(22);
buccaneersQBStats.setReceptions(0);
buccaneersQBStats.setReceivingYards(0);
buccaneersQBStats.setReceivingTouchdowns(6);
buccaneersQBStats.setRushingAttempts(54);
buccaneersQBStats.setRushingYards(213);
buccaneersQBStats.setRushingTouchdowns(1);
buccaneersQB.getStats().add(buccaneersQBStats);
//Martin
Stats buccaneersRB1Stats = new Stats();
buccaneersRB1Stats.setSeason(season2015);
buccaneersRB1Stats.setPlayer(buccaneersRB1);
buccaneersRB1Stats.setPassAttempts(0);
buccaneersRB1Stats.setPassCompletions(0);
buccaneersRB1Stats.setPassingYards(0);
buccaneersRB1Stats.setPassingTouchdowns(0);
buccaneersRB1Stats.setReceptions(33);
buccaneersRB1Stats.setReceivingYards(271);
buccaneersRB1Stats.setReceivingTouchdowns(1);
buccaneersRB1Stats.setRushingAttempts(288);
buccaneersRB1Stats.setRushingYards(1402);
buccaneersRB1Stats.setRushingTouchdowns(6);
buccaneersRB1.getStats().add(buccaneersRB1Stats);
//Sims
Stats buccaneersRB2Stats = new Stats();
buccaneersRB2Stats.setSeason(season2015);
buccaneersRB2Stats.setPlayer(buccaneersRB1);
buccaneersRB2Stats.setPassAttempts(0);
buccaneersRB2Stats.setPassCompletions(0);
buccaneersRB2Stats.setPassingYards(0);
buccaneersRB2Stats.setPassingTouchdowns(0);
buccaneersRB2Stats.setReceptions(51);
buccaneersRB2Stats.setReceivingYards(561);
buccaneersRB2Stats.setReceivingTouchdowns(4);
buccaneersRB2Stats.setRushingAttempts(107);
buccaneersRB2Stats.setRushingYards(529);
buccaneersRB2Stats.setRushingTouchdowns(4);
buccaneersRB2.getStats().add(buccaneersRB2Stats);
//Evans
Stats buccaneersWR1Stats = new Stats();
buccaneersWR1Stats.setSeason(season2015);
buccaneersWR1Stats.setPlayer(buccaneersRB1);
buccaneersWR1Stats.setPassAttempts(0);
buccaneersWR1Stats.setPassCompletions(0);
buccaneersWR1Stats.setPassingYards(0);
buccaneersWR1Stats.setPassingTouchdowns(0);
buccaneersWR1Stats.setReceptions(74);
buccaneersWR1Stats.setReceivingYards(1206);
buccaneersWR1Stats.setReceivingTouchdowns(3);
buccaneersWR1Stats.setRushingAttempts(0);
buccaneersWR1Stats.setRushingYards(0);
buccaneersWR1Stats.setRushingTouchdowns(0);
buccaneersWR1.getStats().add(buccaneersWR1Stats);
//Jackson
Stats buccaneersWR2Stats = new Stats();
buccaneersWR2Stats.setSeason(season2015);
buccaneersWR2Stats.setPlayer(buccaneersWR1);
buccaneersWR2Stats.setPassAttempts(0);
buccaneersWR2Stats.setPassCompletions(0);
buccaneersWR2Stats.setPassingYards(0);
buccaneersWR2Stats.setPassingTouchdowns(0);
buccaneersWR2Stats.setReceptions(33);
buccaneersWR2Stats.setReceivingYards(543);
buccaneersWR2Stats.setReceivingTouchdowns(3);
buccaneersWR2Stats.setRushingAttempts(0);
buccaneersWR2Stats.setRushingYards(0);
buccaneersWR2Stats.setRushingTouchdowns(0);
buccaneersWR2.getStats().add(buccaneersWR2Stats);
//Saints
//Brees
Stats saintsQBStats = new Stats();
saintsQBStats.setSeason(season2015);
saintsQBStats.setPlayer(saintsQB);
saintsQBStats.setPassAttempts(627);
saintsQBStats.setPassCompletions(428);
saintsQBStats.setPassingYards(4870);
saintsQBStats.setPassingTouchdowns(32);
saintsQBStats.setReceptions(0);
saintsQBStats.setReceivingYards(0);
saintsQBStats.setReceivingTouchdowns(0);
saintsQBStats.setRushingAttempts(24);
saintsQBStats.setRushingYards(14);
saintsQBStats.setRushingTouchdowns(1);
saintsQB.getStats().add(saintsQBStats);
//Ingram
Stats saintsRB1Stats = new Stats();
saintsRB1Stats.setSeason(season2015);
saintsRB1Stats.setPlayer(saintsRB1);
saintsRB1Stats.setPassAttempts(0);
saintsRB1Stats.setPassCompletions(0);
saintsRB1Stats.setPassingYards(0);
saintsRB1Stats.setPassingTouchdowns(0);
saintsRB1Stats.setReceptions(50);
saintsRB1Stats.setReceivingYards(405);
saintsRB1Stats.setReceivingTouchdowns(3);
saintsRB1Stats.setRushingAttempts(166);
saintsRB1Stats.setRushingYards(769);
saintsRB1Stats.setRushingTouchdowns(6);
saintsRB1.getStats().add(saintsRB1Stats);
//Hightower
Stats saintsRB2Stats = new Stats();
saintsRB2Stats.setSeason(season2015);
saintsRB2Stats.setPlayer(saintsRB1);
saintsRB2Stats.setPassAttempts(0);
saintsRB2Stats.setPassCompletions(0);
saintsRB2Stats.setPassingYards(0);
saintsRB2Stats.setPassingTouchdowns(0);
saintsRB2Stats.setReceptions(12);
saintsRB2Stats.setReceivingYards(179);
saintsRB2Stats.setReceivingTouchdowns(0);
saintsRB2Stats.setRushingAttempts(96);
saintsRB2Stats.setRushingYards(375);
saintsRB2Stats.setRushingTouchdowns(4);
saintsRB2.getStats().add(saintsRB2Stats);
//Cooks
Stats saintsWR1Stats = new Stats();
saintsWR1Stats.setSeason(season2015);
saintsWR1Stats.setPlayer(saintsRB1);
saintsWR1Stats.setPassAttempts(0);
saintsWR1Stats.setPassCompletions(0);
saintsWR1Stats.setPassingYards(0);
saintsWR1Stats.setPassingTouchdowns(0);
saintsWR1Stats.setReceptions(84);
saintsWR1Stats.setReceivingYards(1138);
saintsWR1Stats.setReceivingTouchdowns(9);
saintsWR1Stats.setRushingAttempts(8);
saintsWR1Stats.setRushingYards(18);
saintsWR1Stats.setRushingTouchdowns(0);
saintsWR1.getStats().add(saintsWR1Stats);
//Snead
Stats saintsWR2Stats = new Stats();
saintsWR2Stats.setSeason(season2015);
saintsWR2Stats.setPlayer(saintsWR1);
saintsWR2Stats.setPassAttempts(0);
saintsWR2Stats.setPassCompletions(0);
saintsWR2Stats.setPassingYards(0);
saintsWR2Stats.setPassingTouchdowns(0);
saintsWR2Stats.setReceptions(84);
saintsWR2Stats.setReceivingYards(1138);
saintsWR2Stats.setReceivingTouchdowns(9);
saintsWR2Stats.setRushingAttempts(0);
saintsWR2Stats.setRushingYards(0);
saintsWR2Stats.setRushingTouchdowns(0);
saintsWR2.getStats().add(saintsWR2Stats);
//Cowboys
//Cassel
Stats cowboysQBStats = new Stats();
cowboysQBStats.setSeason(season2015);
cowboysQBStats.setPlayer(cowboysQB);
cowboysQBStats.setPassAttempts(204);
cowboysQBStats.setPassCompletions(119);
cowboysQBStats.setPassingYards(1276);
cowboysQBStats.setPassingTouchdowns(5);
cowboysQBStats.setReceptions(0);
cowboysQBStats.setReceivingYards(0);
cowboysQBStats.setReceivingTouchdowns(0);
cowboysQBStats.setRushingAttempts(15);
cowboysQBStats.setRushingYards(78);
cowboysQBStats.setRushingTouchdowns(0);
cowboysQB.getStats().add(cowboysQBStats);
//McFadden
Stats cowboysRB1Stats = new Stats();
cowboysRB1Stats.setSeason(season2015);
cowboysRB1Stats.setPlayer(cowboysRB1);
cowboysRB1Stats.setPassAttempts(0);
cowboysRB1Stats.setPassCompletions(0);
cowboysRB1Stats.setPassingYards(0);
cowboysRB1Stats.setPassingTouchdowns(0);
cowboysRB1Stats.setReceptions(40);
cowboysRB1Stats.setReceivingYards(328);
cowboysRB1Stats.setReceivingTouchdowns(0);
cowboysRB1Stats.setRushingAttempts(239);
cowboysRB1Stats.setRushingYards(1089);
cowboysRB1Stats.setRushingTouchdowns(3);
cowboysRB1.getStats().add(cowboysRB1Stats);
//Randall
Stats cowboysRB2Stats = new Stats();
cowboysRB2Stats.setSeason(season2015);
cowboysRB2Stats.setPlayer(cowboysRB1);
cowboysRB2Stats.setPassAttempts(0);
cowboysRB2Stats.setPassCompletions(0);
cowboysRB2Stats.setPassingYards(0);
cowboysRB2Stats.setPassingTouchdowns(0);
cowboysRB2Stats.setReceptions(10);
cowboysRB2Stats.setReceivingYards(86);
cowboysRB2Stats.setReceivingTouchdowns(0);
cowboysRB2Stats.setRushingAttempts(76);
cowboysRB2Stats.setRushingYards(315);
cowboysRB2Stats.setRushingTouchdowns(4);
cowboysRB2.getStats().add(cowboysRB2Stats);
//Williams
Stats cowboysWR1Stats = new Stats();
cowboysWR1Stats.setSeason(season2015);
cowboysWR1Stats.setPlayer(cowboysRB1);
cowboysWR1Stats.setPassAttempts(0);
cowboysWR1Stats.setPassCompletions(0);
cowboysWR1Stats.setPassingYards(0);
cowboysWR1Stats.setPassingTouchdowns(0);
cowboysWR1Stats.setReceptions(52);
cowboysWR1Stats.setReceivingYards(840);
cowboysWR1Stats.setReceivingTouchdowns(3);
cowboysWR1Stats.setRushingAttempts(0);
cowboysWR1Stats.setRushingYards(0);
cowboysWR1Stats.setRushingTouchdowns(0);
cowboysWR1.getStats().add(cowboysWR1Stats);
//Beasley
Stats cowboysWR2Stats = new Stats();
cowboysWR2Stats.setSeason(season2015);
cowboysWR2Stats.setPlayer(cowboysWR1);
cowboysWR2Stats.setPassAttempts(0);
cowboysWR2Stats.setPassCompletions(0);
cowboysWR2Stats.setPassingYards(0);
cowboysWR2Stats.setPassingTouchdowns(0);
cowboysWR2Stats.setReceptions(52);
cowboysWR2Stats.setReceivingYards(536);
cowboysWR2Stats.setReceivingTouchdowns(5);
cowboysWR2Stats.setRushingAttempts(0);
cowboysWR2Stats.setRushingYards(0);
cowboysWR2Stats.setRushingTouchdowns(0);
cowboysWR2.getStats().add(cowboysWR2Stats);
//Eagles
//Bradford
Stats eaglesQBStats = new Stats();
eaglesQBStats.setSeason(season2015);
eaglesQBStats.setPlayer(eaglesQB);
eaglesQBStats.setPassAttempts(532);
eaglesQBStats.setPassCompletions(346);
eaglesQBStats.setPassingYards(3725);
eaglesQBStats.setPassingTouchdowns(19);
eaglesQBStats.setReceptions(0);
eaglesQBStats.setReceivingYards(0);
eaglesQBStats.setReceivingTouchdowns(0);
eaglesQBStats.setRushingAttempts(26);
eaglesQBStats.setRushingYards(39);
eaglesQBStats.setRushingTouchdowns(0);
eaglesQB.getStats().add(eaglesQBStats);
//Murray
Stats eaglesRB1Stats = new Stats();
eaglesRB1Stats.setSeason(season2015);
eaglesRB1Stats.setPlayer(eaglesRB1);
eaglesRB1Stats.setPassAttempts(0);
eaglesRB1Stats.setPassCompletions(0);
eaglesRB1Stats.setPassingYards(0);
eaglesRB1Stats.setPassingTouchdowns(0);
eaglesRB1Stats.setReceptions(44);
eaglesRB1Stats.setReceivingYards(322);
eaglesRB1Stats.setReceivingTouchdowns(1);
eaglesRB1Stats.setRushingAttempts(193);
eaglesRB1Stats.setRushingYards(702);
eaglesRB1Stats.setRushingTouchdowns(6);
eaglesRB1.getStats().add(eaglesRB1Stats);
//R. Mathews
Stats eaglesRB2Stats = new Stats();
eaglesRB2Stats.setSeason(season2015);
eaglesRB2Stats.setPlayer(eaglesRB1);
eaglesRB2Stats.setPassAttempts(0);
eaglesRB2Stats.setPassCompletions(0);
eaglesRB2Stats.setPassingYards(0);
eaglesRB2Stats.setPassingTouchdowns(0);
eaglesRB2Stats.setReceptions(20);
eaglesRB2Stats.setReceivingYards(146);
eaglesRB2Stats.setReceivingTouchdowns(1);
eaglesRB2Stats.setRushingAttempts(106);
eaglesRB2Stats.setRushingYards(539);
eaglesRB2Stats.setRushingTouchdowns(6);
eaglesRB2.getStats().add(eaglesRB2Stats);
//J. Matthews
Stats eaglesWR1Stats = new Stats();
eaglesWR1Stats.setSeason(season2015);
eaglesWR1Stats.setPlayer(eaglesRB1);
eaglesWR1Stats.setPassAttempts(0);
eaglesWR1Stats.setPassCompletions(0);
eaglesWR1Stats.setPassingYards(0);
eaglesWR1Stats.setPassingTouchdowns(0);
eaglesWR1Stats.setReceptions(85);
eaglesWR1Stats.setReceivingYards(997);
eaglesWR1Stats.setReceivingTouchdowns(8);
eaglesWR1Stats.setRushingAttempts(0);
eaglesWR1Stats.setRushingYards(0);
eaglesWR1Stats.setRushingTouchdowns(0);
eaglesWR1.getStats().add(eaglesWR1Stats);
//Cooper
Stats eaglesWR2Stats = new Stats();
eaglesWR2Stats.setSeason(season2015);
eaglesWR2Stats.setPlayer(eaglesWR1);
eaglesWR2Stats.setPassAttempts(0);
eaglesWR2Stats.setPassCompletions(0);
eaglesWR2Stats.setPassingYards(0);
eaglesWR2Stats.setPassingTouchdowns(0);
eaglesWR2Stats.setReceptions(21);
eaglesWR2Stats.setReceivingYards(327);
eaglesWR2Stats.setReceivingTouchdowns(2);
eaglesWR2Stats.setRushingAttempts(0);
eaglesWR2Stats.setRushingYards(0);
eaglesWR2Stats.setRushingTouchdowns(0);
eaglesWR2.getStats().add(eaglesWR2Stats);
//Giants
//Manning
Stats giantsQBStats = new Stats();
giantsQBStats.setSeason(season2015);
giantsQBStats.setPlayer(giantsQB);
giantsQBStats.setPassAttempts(618);
giantsQBStats.setPassCompletions(387);
giantsQBStats.setPassingYards(4436);
giantsQBStats.setPassingTouchdowns(35);
giantsQBStats.setReceptions(0);
giantsQBStats.setReceivingYards(0);
giantsQBStats.setReceivingTouchdowns(0);
giantsQBStats.setRushingAttempts(20);
giantsQBStats.setRushingYards(61);
giantsQBStats.setRushingTouchdowns(0);
giantsQB.getStats().add(giantsQBStats);
//Jennings
Stats giantsRB1Stats = new Stats();
giantsRB1Stats.setSeason(season2015);
giantsRB1Stats.setPlayer(giantsRB1);
giantsRB1Stats.setPassAttempts(0);
giantsRB1Stats.setPassCompletions(0);
giantsRB1Stats.setPassingYards(0);
giantsRB1Stats.setPassingTouchdowns(0);
giantsRB1Stats.setReceptions(29);
giantsRB1Stats.setReceivingYards(296);
giantsRB1Stats.setReceivingTouchdowns(1);
giantsRB1Stats.setRushingAttempts(193);
giantsRB1Stats.setRushingYards(702);
giantsRB1Stats.setRushingTouchdowns(6);
giantsRB1.getStats().add(giantsRB1Stats);
//Vareen
Stats giantsRB2Stats = new Stats();
giantsRB2Stats.setSeason(season2015);
giantsRB2Stats.setPlayer(giantsRB1);
giantsRB2Stats.setPassAttempts(0);
giantsRB2Stats.setPassCompletions(0);
giantsRB2Stats.setPassingYards(0);
giantsRB2Stats.setPassingTouchdowns(0);
giantsRB2Stats.setReceptions(59);
giantsRB2Stats.setReceivingYards(495);
giantsRB2Stats.setReceivingTouchdowns(4);
giantsRB2Stats.setRushingAttempts(61);
giantsRB2Stats.setRushingYards(260);
giantsRB2Stats.setRushingTouchdowns(0);
giantsRB2.getStats().add(giantsRB2Stats);
//Beckham Jr.
Stats giantsWR1Stats = new Stats();
giantsWR1Stats.setSeason(season2015);
giantsWR1Stats.setPlayer(giantsRB1);
giantsWR1Stats.setPassAttempts(0);
giantsWR1Stats.setPassCompletions(0);
giantsWR1Stats.setPassingYards(0);
giantsWR1Stats.setPassingTouchdowns(0);
giantsWR1Stats.setReceptions(96);
giantsWR1Stats.setReceivingYards(1450);
giantsWR1Stats.setReceivingTouchdowns(13);
giantsWR1Stats.setRushingAttempts(1);
giantsWR1Stats.setRushingYards(3);
giantsWR1Stats.setRushingTouchdowns(0);
giantsWR1.getStats().add(giantsWR1Stats);
//Randle
Stats giantsWR2Stats = new Stats();
giantsWR2Stats.setSeason(season2015);
giantsWR2Stats.setPlayer(giantsWR1);
giantsWR2Stats.setPassAttempts(0);
giantsWR2Stats.setPassCompletions(0);
giantsWR2Stats.setPassingYards(0);
giantsWR2Stats.setPassingTouchdowns(0);
giantsWR2Stats.setReceptions(57);
giantsWR2Stats.setReceivingYards(797);
giantsWR2Stats.setReceivingTouchdowns(8);
giantsWR2Stats.setRushingAttempts(0);
giantsWR2Stats.setRushingYards(0);
giantsWR2Stats.setRushingTouchdowns(0);
giantsWR2.getStats().add(giantsWR2Stats);
//Redskins
//Cousins
Stats redskinsQBStats = new Stats();
redskinsQBStats.setSeason(season2015);
redskinsQBStats.setPlayer(redskinsQB);
redskinsQBStats.setPassAttempts(543);
redskinsQBStats.setPassCompletions(379);
redskinsQBStats.setPassingYards(4166);
redskinsQBStats.setPassingTouchdowns(29);
redskinsQBStats.setReceptions(0);
redskinsQBStats.setReceivingYards(0);
redskinsQBStats.setReceivingTouchdowns(0);
redskinsQBStats.setRushingAttempts(26);
redskinsQBStats.setRushingYards(48);
redskinsQBStats.setRushingTouchdowns(5);
redskinsQB.getStats().add(redskinsQBStats);
//Morris
Stats redskinsRB1Stats = new Stats();
redskinsRB1Stats.setSeason(season2015);
redskinsRB1Stats.setPlayer(redskinsRB1);
redskinsRB1Stats.setPassAttempts(0);
redskinsRB1Stats.setPassCompletions(0);
redskinsRB1Stats.setPassingYards(0);
redskinsRB1Stats.setPassingTouchdowns(0);
redskinsRB1Stats.setReceptions(10);
redskinsRB1Stats.setReceivingYards(55);
redskinsRB1Stats.setReceivingTouchdowns(0);
redskinsRB1Stats.setRushingAttempts(202);
redskinsRB1Stats.setRushingYards(751);
redskinsRB1Stats.setRushingTouchdowns(1);
redskinsRB1.getStats().add(redskinsRB1Stats);
//Jones
Stats redskinsRB2Stats = new Stats();
redskinsRB2Stats.setSeason(season2015);
redskinsRB2Stats.setPlayer(redskinsRB1);
redskinsRB2Stats.setPassAttempts(0);
redskinsRB2Stats.setPassCompletions(0);
redskinsRB2Stats.setPassingYards(0);
redskinsRB2Stats.setPassingTouchdowns(0);
redskinsRB2Stats.setReceptions(19);
redskinsRB2Stats.setReceivingYards(304);
redskinsRB2Stats.setReceivingTouchdowns(1);
redskinsRB2Stats.setRushingAttempts(59);
redskinsRB2Stats.setRushingYards(490);
redskinsRB2Stats.setRushingTouchdowns(3);
redskinsRB2.getStats().add(redskinsRB2Stats);
//Garson
Stats redskinsWR1Stats = new Stats();
redskinsWR1Stats.setSeason(season2015);
redskinsWR1Stats.setPlayer(redskinsRB1);
redskinsWR1Stats.setPassAttempts(0);
redskinsWR1Stats.setPassCompletions(0);
redskinsWR1Stats.setPassingYards(0);
redskinsWR1Stats.setPassingTouchdowns(0);
redskinsWR1Stats.setReceptions(72);
redskinsWR1Stats.setReceivingYards(777);
redskinsWR1Stats.setReceivingTouchdowns(6);
redskinsWR1Stats.setRushingAttempts(0);
redskinsWR1Stats.setRushingYards(0);
redskinsWR1Stats.setRushingTouchdowns(0);
redskinsWR1.getStats().add(redskinsWR1Stats);
//Crowder
Stats redskinsWR2Stats = new Stats();
redskinsWR2Stats.setSeason(season2015);
redskinsWR2Stats.setPlayer(redskinsWR1);
redskinsWR2Stats.setPassAttempts(1);
redskinsWR2Stats.setPassCompletions(0);
redskinsWR2Stats.setPassingYards(0);
redskinsWR2Stats.setPassingTouchdowns(0);
redskinsWR2Stats.setReceptions(59);
redskinsWR2Stats.setReceivingYards(604);
redskinsWR2Stats.setReceivingTouchdowns(2);
redskinsWR2Stats.setRushingAttempts(2);
redskinsWR2Stats.setRushingYards(2);
redskinsWR2Stats.setRushingTouchdowns(0);
redskinsWR2.getStats().add(redskinsWR2Stats);
//Bears
//Cutler
Stats bearsQBStats = new Stats();
bearsQBStats.setSeason(season2015);
bearsQBStats.setPlayer(bearsQB);
bearsQBStats.setPassAttempts(483);
bearsQBStats.setPassCompletions(311);
bearsQBStats.setPassingYards(3659);
bearsQBStats.setPassingTouchdowns(21);
bearsQBStats.setReceptions(0);
bearsQBStats.setReceivingYards(0);
bearsQBStats.setReceivingTouchdowns(0);
bearsQBStats.setRushingAttempts(38);
bearsQBStats.setRushingYards(201);
bearsQBStats.setRushingTouchdowns(1);
bearsQB.getStats().add(bearsQBStats);
//Forte
Stats bearsRB1Stats = new Stats();
bearsRB1Stats.setSeason(season2015);
bearsRB1Stats.setPlayer(bearsRB1);
bearsRB1Stats.setPassAttempts(0);
bearsRB1Stats.setPassCompletions(0);
bearsRB1Stats.setPassingYards(0);
bearsRB1Stats.setPassingTouchdowns(0);
bearsRB1Stats.setReceptions(44);
bearsRB1Stats.setReceivingYards(389);
bearsRB1Stats.setReceivingTouchdowns(3);
bearsRB1Stats.setRushingAttempts(218);
bearsRB1Stats.setRushingYards(898);
bearsRB1Stats.setRushingTouchdowns(4);
bearsRB1.getStats().add(bearsRB1Stats);
//Langford
Stats bearsRB2Stats = new Stats();
bearsRB2Stats.setSeason(season2015);
bearsRB2Stats.setPlayer(bearsRB1);
bearsRB2Stats.setPassAttempts(0);
bearsRB2Stats.setPassCompletions(0);
bearsRB2Stats.setPassingYards(0);
bearsRB2Stats.setPassingTouchdowns(0);
bearsRB2Stats.setReceptions(19);
bearsRB2Stats.setReceivingYards(304);
bearsRB2Stats.setReceivingTouchdowns(1);
bearsRB2Stats.setRushingAttempts(22);
bearsRB2Stats.setRushingYards(279);
bearsRB2Stats.setRushingTouchdowns(1);
bearsRB2.getStats().add(bearsRB2Stats);
//Jeffery
Stats bearsWR1Stats = new Stats();
bearsWR1Stats.setSeason(season2015);
bearsWR1Stats.setPlayer(bearsRB1);
bearsWR1Stats.setPassAttempts(0);
bearsWR1Stats.setPassCompletions(0);
bearsWR1Stats.setPassingYards(0);
bearsWR1Stats.setPassingTouchdowns(0);
bearsWR1Stats.setReceptions(54);
bearsWR1Stats.setReceivingYards(807);
bearsWR1Stats.setReceivingTouchdowns(4);
bearsWR1Stats.setRushingAttempts(0);
bearsWR1Stats.setRushingYards(0);
bearsWR1Stats.setRushingTouchdowns(0);
bearsWR1.getStats().add(bearsWR1Stats);
//Wilson
Stats bearsWR2Stats = new Stats();
bearsWR2Stats.setSeason(season2015);
bearsWR2Stats.setPlayer(bearsWR1);
bearsWR2Stats.setPassAttempts(0);
bearsWR2Stats.setPassCompletions(0);
bearsWR2Stats.setPassingYards(0);
bearsWR2Stats.setPassingTouchdowns(0);
bearsWR2Stats.setReceptions(28);
bearsWR2Stats.setReceivingYards(464);
bearsWR2Stats.setReceivingTouchdowns(1);
bearsWR2Stats.setRushingAttempts(0);
bearsWR2Stats.setRushingYards(0);
bearsWR2Stats.setRushingTouchdowns(0);
bearsWR2.getStats().add(bearsWR2Stats);
//Lions
//Stafford
Stats lionsQBStats = new Stats();
lionsQBStats.setSeason(season2015);
lionsQBStats.setPlayer(lionsQB);
lionsQBStats.setPassAttempts(592);
lionsQBStats.setPassCompletions(398);
lionsQBStats.setPassingYards(4262);
lionsQBStats.setPassingTouchdowns(32);
lionsQBStats.setReceptions(0);
lionsQBStats.setReceivingYards(0);
lionsQBStats.setReceivingTouchdowns(0);
lionsQBStats.setRushingAttempts(44);
lionsQBStats.setRushingYards(201);
lionsQBStats.setRushingTouchdowns(1);
lionsQB.getStats().add(lionsQBStats);
//Abdullah
Stats lionsRB1Stats = new Stats();
lionsRB1Stats.setSeason(season2015);
lionsRB1Stats.setPlayer(lionsRB1);
lionsRB1Stats.setPassAttempts(0);
lionsRB1Stats.setPassCompletions(0);
lionsRB1Stats.setPassingYards(0);
lionsRB1Stats.setPassingTouchdowns(0);
lionsRB1Stats.setReceptions(25);
lionsRB1Stats.setReceivingYards(183);
lionsRB1Stats.setReceivingTouchdowns(1);
lionsRB1Stats.setRushingAttempts(143);
lionsRB1Stats.setRushingYards(597);
lionsRB1Stats.setRushingTouchdowns(2);
lionsRB1.getStats().add(lionsRB1Stats);
//Bell
Stats lionsRB2Stats = new Stats();
lionsRB2Stats.setSeason(season2015);
lionsRB2Stats.setPlayer(lionsRB1);
lionsRB2Stats.setPassAttempts(0);
lionsRB2Stats.setPassCompletions(0);
lionsRB2Stats.setPassingYards(0);
lionsRB2Stats.setPassingTouchdowns(0);
lionsRB2Stats.setReceptions(22);
lionsRB2Stats.setReceivingYards(286);
lionsRB2Stats.setReceivingTouchdowns(0);
lionsRB2Stats.setRushingAttempts(90);
lionsRB2Stats.setRushingYards(311);
lionsRB2Stats.setRushingTouchdowns(4);
lionsRB2.getStats().add(lionsRB2Stats);
//Johnson
Stats lionsWR1Stats = new Stats();
lionsWR1Stats.setSeason(season2015);
lionsWR1Stats.setPlayer(lionsRB1);
lionsWR1Stats.setPassAttempts(0);
lionsWR1Stats.setPassCompletions(0);
lionsWR1Stats.setPassingYards(0);
lionsWR1Stats.setPassingTouchdowns(0);
lionsWR1Stats.setReceptions(1214);
lionsWR1Stats.setReceivingYards(1214);
lionsWR1Stats.setReceivingTouchdowns(9);
lionsWR1Stats.setRushingAttempts(0);
lionsWR1Stats.setRushingYards(0);
lionsWR1Stats.setRushingTouchdowns(0);
lionsWR1.getStats().add(lionsWR1Stats);
//Tate
Stats lionsWR2Stats = new Stats();
lionsWR2Stats.setSeason(season2015);
lionsWR2Stats.setPlayer(lionsWR1);
lionsWR2Stats.setPassAttempts(0);
lionsWR2Stats.setPassCompletions(0);
lionsWR2Stats.setPassingYards(0);
lionsWR2Stats.setPassingTouchdowns(0);
lionsWR2Stats.setReceptions(90);
lionsWR2Stats.setReceivingYards(813);
lionsWR2Stats.setReceivingTouchdowns(6);
lionsWR2Stats.setRushingAttempts(6);
lionsWR2Stats.setRushingYards(41);
lionsWR2Stats.setRushingTouchdowns(0);
lionsWR2.getStats().add(lionsWR2Stats);
//Packers
//Rodgers
Stats packersQBStats = new Stats();
packersQBStats.setSeason(season2015);
packersQBStats.setPlayer(packersQB);
packersQBStats.setPassAttempts(572);
packersQBStats.setPassCompletions(347);
packersQBStats.setPassingYards(3821);
packersQBStats.setPassingTouchdowns(31);
packersQBStats.setReceptions(0);
packersQBStats.setReceivingYards(0);
packersQBStats.setReceivingTouchdowns(0);
packersQBStats.setRushingAttempts(58);
packersQBStats.setRushingYards(344);
packersQBStats.setRushingTouchdowns(1);
packersQB.getStats().add(packersQBStats);
//Lacy
Stats packersRB1Stats = new Stats();
packersRB1Stats.setSeason(season2015);
packersRB1Stats.setPlayer(packersRB1);
packersRB1Stats.setPassAttempts(0);
packersRB1Stats.setPassCompletions(0);
packersRB1Stats.setPassingYards(0);
packersRB1Stats.setPassingTouchdowns(0);
packersRB1Stats.setReceptions(20);
packersRB1Stats.setReceivingYards(188);
packersRB1Stats.setReceivingTouchdowns(2);
packersRB1Stats.setRushingAttempts(187);
packersRB1Stats.setRushingYards(758);
packersRB1Stats.setRushingTouchdowns(3);
packersRB1.getStats().add(packersRB1Stats);
//Starks
Stats packersRB2Stats = new Stats();
packersRB2Stats.setSeason(season2015);
packersRB2Stats.setPlayer(packersRB1);
packersRB2Stats.setPassAttempts(0);
packersRB2Stats.setPassCompletions(0);
packersRB2Stats.setPassingYards(0);
packersRB2Stats.setPassingTouchdowns(0);
packersRB2Stats.setReceptions(43);
packersRB2Stats.setReceivingYards(392);
packersRB2Stats.setReceivingTouchdowns(3);
packersRB2Stats.setRushingAttempts(148);
packersRB2Stats.setRushingYards(601);
packersRB2Stats.setRushingTouchdowns(2);
packersRB2.getStats().add(packersRB2Stats);
//Jones
Stats packersWR1Stats = new Stats();
packersWR1Stats.setSeason(season2015);
packersWR1Stats.setPlayer(packersRB1);
packersWR1Stats.setPassAttempts(0);
packersWR1Stats.setPassCompletions(0);
packersWR1Stats.setPassingYards(0);
packersWR1Stats.setPassingTouchdowns(0);
packersWR1Stats.setReceptions(50);
packersWR1Stats.setReceivingYards(890);
packersWR1Stats.setReceivingTouchdowns(9);
packersWR1Stats.setRushingAttempts(0);
packersWR1Stats.setRushingYards(0);
packersWR1Stats.setRushingTouchdowns(0);
packersWR1.getStats().add(packersWR1Stats);
//Cobb
Stats packersWR2Stats = new Stats();
packersWR2Stats.setSeason(season2015);
packersWR2Stats.setPlayer(packersWR1);
packersWR2Stats.setPassAttempts(0);
packersWR2Stats.setPassCompletions(0);
packersWR2Stats.setPassingYards(0);
packersWR2Stats.setPassingTouchdowns(0);
packersWR2Stats.setReceptions(79);
packersWR2Stats.setReceivingYards(829);
packersWR2Stats.setReceivingTouchdowns(6);
packersWR2Stats.setRushingAttempts(13);
packersWR2Stats.setRushingYards(50);
packersWR2Stats.setRushingTouchdowns(0);
packersWR2.getStats().add(packersWR2Stats);
//Vikings
//Bridgewater
Stats vikingsQBStats = new Stats();
vikingsQBStats.setSeason(season2015);
vikingsQBStats.setPlayer(vikingsQB);
vikingsQBStats.setPassAttempts(447);
vikingsQBStats.setPassCompletions(292);
vikingsQBStats.setPassingYards(3231);
vikingsQBStats.setPassingTouchdowns(14);
vikingsQBStats.setReceptions(0);
vikingsQBStats.setReceivingYards(0);
vikingsQBStats.setReceivingTouchdowns(0);
vikingsQBStats.setRushingAttempts(44);
vikingsQBStats.setRushingYards(192);
vikingsQBStats.setRushingTouchdowns(3);
vikingsQB.getStats().add(vikingsQBStats);
//Peterson
Stats vikingsRB1Stats = new Stats();
vikingsRB1Stats.setSeason(season2015);
vikingsRB1Stats.setPlayer(vikingsRB1);
vikingsRB1Stats.setPassAttempts(0);
vikingsRB1Stats.setPassCompletions(0);
vikingsRB1Stats.setPassingYards(0);
vikingsRB1Stats.setPassingTouchdowns(0);
vikingsRB1Stats.setReceptions(30);
vikingsRB1Stats.setReceivingYards(222);
vikingsRB1Stats.setReceivingTouchdowns(0);
vikingsRB1Stats.setRushingAttempts(327);
vikingsRB1Stats.setRushingYards(1485);
vikingsRB1Stats.setRushingTouchdowns(11);
vikingsRB1.getStats().add(vikingsRB1Stats);
//McKinnon
Stats vikingsRB2Stats = new Stats();
vikingsRB2Stats.setSeason(season2015);
vikingsRB2Stats.setPlayer(vikingsRB1);
vikingsRB2Stats.setPassAttempts(0);
vikingsRB2Stats.setPassCompletions(0);
vikingsRB2Stats.setPassingYards(0);
vikingsRB2Stats.setPassingTouchdowns(0);
vikingsRB2Stats.setReceptions(43);
vikingsRB2Stats.setReceivingYards(392);
vikingsRB2Stats.setReceivingTouchdowns(3);
vikingsRB2Stats.setRushingAttempts(52);
vikingsRB2Stats.setRushingYards(271);
vikingsRB2Stats.setRushingTouchdowns(2);
vikingsRB2.getStats().add(vikingsRB2Stats);
//Diggs
Stats vikingsWR1Stats = new Stats();
vikingsWR1Stats.setSeason(season2015);
vikingsWR1Stats.setPlayer(vikingsWR1);
vikingsWR1Stats.setPassAttempts(0);
vikingsWR1Stats.setPassCompletions(0);
vikingsWR1Stats.setPassingYards(0);
vikingsWR1Stats.setPassingTouchdowns(0);
vikingsWR1Stats.setReceptions(52);
vikingsWR1Stats.setReceivingYards(720);
vikingsWR1Stats.setReceivingTouchdowns(4);
vikingsWR1Stats.setRushingAttempts(3);
vikingsWR1Stats.setRushingYards(13);
vikingsWR1Stats.setRushingTouchdowns(0);
vikingsWR1.getStats().add(vikingsWR1Stats);
//Wallace
Stats vikingsWR2Stats = new Stats();
vikingsWR2Stats.setSeason(season2015);
vikingsWR2Stats.setPlayer(vikingsRB1);
vikingsWR2Stats.setPassAttempts(0);
vikingsWR2Stats.setPassCompletions(0);
vikingsWR2Stats.setPassingYards(0);
vikingsWR2Stats.setPassingTouchdowns(0);
vikingsWR2Stats.setReceptions(39);
vikingsWR2Stats.setReceivingYards(473);
vikingsWR2Stats.setReceivingTouchdowns(2);
vikingsWR2Stats.setRushingAttempts(1);
vikingsWR2Stats.setRushingYards(6);
vikingsWR2Stats.setRushingTouchdowns(0);
vikingsWR1.getStats().add(vikingsWR1Stats);
//save everything
manager.saveEntity(nfl);
}
}
| agpl-3.0 |
clintonhealthaccess/lmis-moz-mobile | app/src/main/java/org/openlmis/core/enums/VIAReportType.java | 135 | package org.openlmis.core.enums;
import java.io.Serializable;
public enum VIAReportType implements Serializable {
MALARIA, PTV
}
| agpl-3.0 |
aihua/opennms | features/timeformat/api/src/main/java/org/opennms/features/timeformat/api/TimeformatService.java | 1461 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2018 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2018 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.features.timeformat.api;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
public interface TimeformatService {
String format(Instant instant, ZoneId zoneId);
String format(Date date, ZoneId zoneId);
}
| agpl-3.0 |
sudduth/Aardin | Core/CoreImpl/src/main/java/org/aardin/core/service/notification/NotificationFactory.java | 5148 | /*******************************************************************************
* Distributed under the terms of the GNU AGPL version 3.
* Copyright (c) 2011 Glenn Sudduth
*******************************************************************************/
package org.aardin.core.service.notification;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.aardin.common.messaging.ReturnCode;
import org.aardin.core.CoreServiceConstants;
import org.aardin.core.api.INotificationTemplate;
import org.aardin.core.model.MessageParameter;
import org.aardin.core.service.ICommuniqueFactory;
import org.aardin.core.service.IConfigRepo;
import org.aardin.core.service.IConfiguration;
import org.aardin.dispatch.api.IDispatchService;
import org.aardin.logging.api.ILoggingService;
import org.aardin.npml.IElementFactory;
import org.aardin.npml.InvalidPlanException;
import org.aardin.npml.Plan;
import org.apache.commons.lang.StringUtils;
import org.jdom2.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Provides a {@link Notification} object given a client notification request.
*
* An {@link IConfiguration} must be supplied before notifications can be created.
*/
@Service
public class NotificationFactory
implements INotificationFactory {
@Autowired
private IConfigRepo configRepo;
@Autowired
private IElementFactory elementFactory;
@Autowired
private ICommuniqueFactory communiqueFactory;
@Autowired
private ILoggingService loggingService;
@Autowired
private IDispatchService dispatchService;
public NotificationFactory() {}
/**
* Allow an IConfigurations to be overridden for testing.
* @param configurations An IConfigurations
*/
@Override
public void setConfigurations(IConfigRepo configRepo) {
this.configRepo = configRepo;
}
@Override
public void setElementFactory(IElementFactory factory) {
elementFactory = factory;
}
@Override
public void setCommuniqueFactory(ICommuniqueFactory communiqueFactory) {
this.communiqueFactory = communiqueFactory;
}
@Override
public void setLoggingService(ILoggingService loggingService) {
this.loggingService = loggingService;
}
@Override
public void setDispatchService(IDispatchService dispatchService) {
this.dispatchService = dispatchService;
}
@Override
public Notification createNotification(String partitionCode, String templateCode, Map<String, String> parameters)
throws NotificationException {
if (StringUtils.isEmpty(partitionCode)) {
throw new NotificationException(ReturnCode.INVALID_REQUEST, "Partition code was empty.");
}
if (StringUtils.isEmpty(templateCode)) {
throw new NotificationException(ReturnCode.UNKNOWN_ENTITY,
String.format(ReturnCode.UNKNOWN_ENTITY.getText(), CoreServiceConstants.EntityNames.NOTIFICATION_TEMPLATE, templateCode));
}
if (parameters == null) {
throw new NotificationException(ReturnCode.INVALID_REQUEST, String.format(ReturnCode.INVALID_REQUEST.getText(), "Parameters was null."));
}
INotificationTemplate notificationTemplate = configRepo.getConfig(partitionCode).getNotificationTemplate(templateCode);
if (notificationTemplate == null) {
throw new NotificationException(ReturnCode.UNKNOWN_ENTITY,
String.format(ReturnCode.UNKNOWN_ENTITY.getText(), CoreServiceConstants.EntityNames.NOTIFICATION_TEMPLATE, "null"));
}
SortedSet<MessageParameter> messageParamterSet = new TreeSet<MessageParameter>();
if (parameters != null) {
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
MessageParameter templateParam = notificationTemplate.getMessageParameter(name);
if (templateParam != null) {
messageParamterSet.add(new MessageParameter(name, value, templateParam.isSignificant()));
} else {
throw new NotificationException(ReturnCode.BAD_NOTIFICATION_PARAMETER, String.format("Unknown parameter [%s].", name));
}
}
}
// Create a new Notification.
Notification notification = new Notification(notificationTemplate, messageParamterSet);
// Set the logging client.
notification.setLoggingService(loggingService);
notification.setCommuniqueFactory(communiqueFactory);
notification.setDispatchService(dispatchService);
return notification;
}
@Override
public void finalizeNotification(Notification notification) throws NotificationException {
// Get the plan from the NotificationTemplate and clone it.
Element planElement = notification.getNotificationTemplate().getPlan().xml();
Plan plan = null;
try {
plan = elementFactory.newPlan(notification.getPartitionCode(), planElement);
} catch(InvalidPlanException ipe) {
throw new NotificationException(ReturnCode.INVALD_NOTIFICATION_PLAN,
String.format(ReturnCode.INVALD_NOTIFICATION_PLAN.getText(), notification.getNotificationTemplate().getCode()));
} catch(Exception e) {
throw new NotificationException(ReturnCode.INTERNAL_ERROR, "Unable to create plan.", e);
}
notification.setPlan(plan);
}
}
| agpl-3.0 |
CodeSphere/termitaria | TermitariaOM/JavaSource/ro/cs/om/web/controller/general/UserGroupVerifyNameUniquenessController.java | 3837 | /*******************************************************************************
* This file is part of Termitaria, a project management tool
* Copyright (C) 2008-2013 CodeSphere S.R.L., www.codesphere.ro
*
* Termitaria is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Termitaria. If not, see <http://www.gnu.org/licenses/> .
******************************************************************************/
package ro.cs.om.web.controller.general;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import ro.cs.om.business.BLUserGroup;
import ro.cs.om.common.IConstant;
import ro.cs.om.entity.UserGroup;
import ro.cs.om.exception.BusinessException;
import ro.cs.om.web.security.UserAuth;
/**
* Verify uniqueness of this usergroup name
*
* @author Adelina
*/
public class UserGroupVerifyNameUniquenessController extends AbstractController{
private static String CMD_VERIFIY_UNIQUENESS_OF_USER_GROUP_NAME = "198341";
private static String CMD_VERIFY_UNIQUENESS_OF_USER_GROUP_ORGANISATION = "198342";
private static String ID = "id";
/* (non-Javadoc)
* @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (request.getParameter(CMD_VERIFIY_UNIQUENESS_OF_USER_GROUP_NAME) != null) {
verifiyUserGroupNameUniqueness(request, response);
}
return null;
}
private void verifiyUserGroupNameUniqueness(HttpServletRequest request, HttpServletResponse response) throws IOException {
String name = request.getParameter(CMD_VERIFIY_UNIQUENESS_OF_USER_GROUP_NAME);
String organisation = request.getParameter(CMD_VERIFY_UNIQUENESS_OF_USER_GROUP_ORGANISATION);
logger.debug("OrganisationId: ".concat(organisation));
logger.debug("User Group Name: ".concat(name));
UserGroup userGroup = null;
Integer organisationId = null;
UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(userAuth.isAdminIT()){
organisationId = Integer.valueOf(organisation);
} else {
organisationId = (Integer) request.getSession().getAttribute(IConstant.SESS_ORGANISATION_ID);
}
try{
userGroup = BLUserGroup.getInstance().getUserGroupByNameAndOrg(name, organisationId);
if (request.getParameter(ID) != null && userGroup != null) {
if (Integer.valueOf(request.getParameter(ID)) == userGroup.getUserGroupId()) {
userGroup = null;
}
}
} catch (BusinessException bexc) {
logger.error("", bexc);
response.getOutputStream().write("<p>ERROR</p>".getBytes());
return;
}
if (userGroup != null) {
response.getOutputStream().write("<p>YES</p>".getBytes());
} else {
response.getOutputStream().write("<p>NO</p>".getBytes());
}
}
}
| agpl-3.0 |
CyberCastle/ElectronicSigner | DocumentSigner/src/main/java/cl/cc/signature/sign/SignPDF.java | 5045 | package cl.cc.signature.sign;
import cl.cc.signature.certificate.CertificateProvider;
import cl.cc.signature.date.DateProvider;
import cl.cc.signature.validation.certificate.CertificateValidator;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
/**
*
* @author CyberCastle
*/
public final class SignPDF extends SignDocument {
public static final int CERTIFIED_FORM_FILLING = PdfSignatureAppearance.CERTIFIED_FORM_FILLING;
public static final int CERTIFIED_FORM_FILLING_AND_ANNOTATIONS = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS;
public static final int CERTIFIED_NO_CHANGES_ALLOWED = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;
public static final int NOT_CERTIFIED = PdfSignatureAppearance.NOT_CERTIFIED;
private boolean SignVisible;
private int SingType;
public SignPDF() {
super();
this.SignVisible = false;
this.SingType = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;
}
public SignPDF(CertificateProvider provider) {
this();
this.provider = provider;
}
@Override
public void setSignAttributes(boolean SignVisible, int SingType) {
this.SignVisible = SignVisible;
this.SingType = SingType;
}
@Override
public void setSignAttributes(String TagID, String NSPrefix, String XPathToSign, String xmlSignerInfo) {
throw new NoSuchMethodError("Method not defined");
}
@Override
public void setCertificateProvider(CertificateProvider provider) {
this.provider = provider;
}
@Override
@SuppressWarnings("MismatchedReadAndWriteOfArray")
public void sign() throws SignDocumentException {
try {
PdfReader pdfr = new PdfReader(new FileInputStream(this.inputFile));
FileOutputStream pdfout = new FileOutputStream(this.outputFile);
PdfStamper stp = PdfStamper.createSignature(pdfr, pdfout, '\0', null, this.signerList);
PdfSignatureAppearance sap = stp.getSignatureAppearance();
KeyStore ks = this.provider.getKeyStore();
Certificate[] chain = ks.getCertificateChain(this.provider.getAlias());
switch (SingType) {
case CERTIFIED_NO_CHANGES_ALLOWED:
sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
break;
case CERTIFIED_FORM_FILLING:
sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING);
break;
case CERTIFIED_FORM_FILLING_AND_ANNOTATIONS:
sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS);
break;
case NOT_CERTIFIED:
sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
break;
default:
sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
}
sap.setSignDate(this.signDate);
if (this.SignVisible) {
sap.setVisibleSignature(new Rectangle(50, 50, 150, 100), pdfr.getNumberOfPages(), null);
}
sap.setLocation(this.locationSign);
sap.setReason(this.reasonSign);
ExternalSignature es = new PrivateKeySignature(this.provider.getPrivateKey(), "SHA-256", this.provider.getProviderName());
ExternalDigest digest = new BouncyCastleDigest();
MakeSignature.signDetached(sap, digest, es, chain, null, null, null, 0, CryptoStandard.CMS);
stp.close();
pdfout.flush();
pdfout.close();
pdfr.close();
} catch (KeyStoreException e) {
throw new SignDocumentException("Error al acceder al certificado", "", e);
} catch (DocumentException e) {
throw new SignDocumentException("Formato del documento inválido", "", e);
} catch (IOException e) {
throw new SignDocumentException("Error al acceder al documento", "", e);
} catch (GeneralSecurityException e) {
throw new SignDocumentException("Error al firmar el documento", "", e);
}
}
}
| agpl-3.0 |
AydinSakar/sql-layer | src/main/java/com/foundationdb/sql/optimizer/plan/BaseUpdateStatement.java | 2127 | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* 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.foundationdb.sql.optimizer.plan;
/** A statement that modifies the database.
*/
public class BaseUpdateStatement extends BasePlanWithInput
{
public enum StatementType {
DELETE,
INSERT,
UPDATE
}
private TableNode targetTable;
private TableSource table;
private final StatementType type;
protected BaseUpdateStatement(PlanNode query, StatementType type, TableNode targetTable,
TableSource table) {
super(query);
this.type = type;
this.targetTable = targetTable;
this.table = table;
}
public TableNode getTargetTable() {
return targetTable;
}
public TableSource getTable() {
return table;
}
public StatementType getType() {
return type;
}
@Override
public String summaryString() {
StringBuilder str = new StringBuilder(super.summaryString());
str.append('(');
fillSummaryString(str);
//if (requireStepIsolation)
// str.append(", HALLOWEEN");
str.append(')');
return str.toString();
}
protected void fillSummaryString(StringBuilder str) {
str.append(getTargetTable());
}
@Override
protected void deepCopy(DuplicateMap map) {
super.deepCopy(map);
targetTable = map.duplicate(targetTable);
}
}
| agpl-3.0 |
USAID-DELIVER-PROJECT/elmis | modules/ivd-form/src/test/java/org/openlmis/ivdform/controller/IvdFormControllerTest.java | 7156 | /*
* Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
*
* Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
*
* 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.openlmis.ivdform.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.openlmis.authentication.web.UserAuthenticationSuccessHandler;
import org.openlmis.core.service.FacilityService;
import org.openlmis.core.service.ProgramService;
import org.openlmis.core.service.UserService;
import org.openlmis.core.web.OpenLmisResponse;
import org.openlmis.db.categories.UnitTests;
import org.openlmis.ivdform.builders.reports.VaccineReportBuilder;
import org.openlmis.ivdform.domain.reports.VaccineReport;
import org.openlmis.ivdform.dto.ReportStatusDTO;
import org.openlmis.ivdform.dto.RoutineReportDTO;
import org.openlmis.ivdform.service.IvdFormService;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.natpryce.makeiteasy.MakeItEasy.a;
import static com.natpryce.makeiteasy.MakeItEasy.make;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.whenNew;
@Category(UnitTests.class)
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(MockitoJUnitRunner.class)
@PrepareForTest({Date.class})
public class IvdFormControllerTest {
@Mock
IvdFormService service;
@Mock
ProgramService programService;
@Mock
FacilityService facilityService;
@Mock
UserService userService;
@InjectMocks
IvdFormController controller;
private MockHttpSession session;
private MockHttpServletRequest httpServletRequest;
@Before
public void setUp() throws Exception {
httpServletRequest = new MockHttpServletRequest();
session = new MockHttpSession();
httpServletRequest.setSession(session);
session.setAttribute(UserAuthenticationSuccessHandler.USER_ID, 1L);
}
@Test
public void shouldGetPeriods() throws Exception {
Date currentDate = new Date();
List<ReportStatusDTO> periods = new ArrayList<>();
when(service.getPeriodsFor(1L, 1L, currentDate)).thenReturn(periods);
whenNew(Date.class).withNoArguments().thenReturn(currentDate);
ResponseEntity<OpenLmisResponse> response = controller.getPeriods(1L, 1L);
assertThat(periods, is(response.getBody().getData().get("periods")));
}
@Test
public void shouldInitialize() throws Exception {
VaccineReport report = new VaccineReport();
when(service.initialize(1L, 1L, 1L, 1L, false)).thenReturn(report);
ResponseEntity<OpenLmisResponse> response = controller.initialize(1L, 1L, 1L, httpServletRequest);
verify(service).initialize(1L, 1L, 1L, 1L, false);
assertThat(report, is(response.getBody().getData().get("report")));
}
@Test
public void shouldGetReport() throws Exception {
VaccineReport report = new VaccineReport();
when(service.getById(23L)).thenReturn(report);
ResponseEntity<OpenLmisResponse> response = controller.getReport(23L);
verify(service).getById(23L);
assertThat(report, is(response.getBody().getData().get("report")));
}
@Test
public void shouldSave() throws Exception {
VaccineReport report = new VaccineReport();
doNothing().when(service).save(report, 1L);
ResponseEntity<OpenLmisResponse> response = controller.save(report, httpServletRequest);
verify(service).save(report, 1L);
assertThat(report, is(response.getBody().getData().get("report")));
}
@Test
public void shouldSubmit() throws Exception {
VaccineReport report = new VaccineReport();
doNothing().when(service).submit(report, 1L);
ResponseEntity<OpenLmisResponse> response = controller.submit(report, httpServletRequest);
verify(service).submit(report, 1L);
// the status would have changed.
assertThat(report, is(response.getBody().getData().get("report")));
}
@Test
public void shouldGetViewPeriods() throws Exception {
Date currentDate = new Date();
List<ReportStatusDTO> periods = new ArrayList<>();
when(service.getReportedPeriodsFor(1L, 1L)).thenReturn(periods);
whenNew(Date.class).withNoArguments().thenReturn(currentDate);
ResponseEntity<OpenLmisResponse> response = controller.getViewPeriods(1L, 1L);
assertThat(periods, is(response.getBody().getData().get("periods")));
}
@Test
public void shouldGetPendingFormsForApproval() throws Exception {
RoutineReportDTO dto = new RoutineReportDTO();
dto.setStatus("REPORT_FOUND");
List<RoutineReportDTO> pendingForms = asList(dto);
when(service.getApprovalPendingForms(1L, 1L)).thenReturn( pendingForms );
ResponseEntity<OpenLmisResponse> response = controller.getPendingFormsForApproval(1L, httpServletRequest);
verify(service).getApprovalPendingForms(1L, 1L);
assertThat(pendingForms, is(response.getBody().getData().get("pending_submissions")));
}
@Test
public void shouldApprove() throws Exception {
VaccineReport report = make(a(VaccineReportBuilder.defaultVaccineReport));
doNothing().when(service).approve(report, 1L);
ResponseEntity<OpenLmisResponse> response = controller.approve(report, httpServletRequest);
assertThat(report, is(response.getBody().getData().get("report")));
verify(service).approve(report, 1L);
}
@Test
public void shouldReject() throws Exception {
VaccineReport report = make(a(VaccineReportBuilder.defaultVaccineReport));
doNothing().when(service).reject(report, 1L);
ResponseEntity<OpenLmisResponse> response = controller.reject(report, httpServletRequest);
assertThat(report, is(response.getBody().getData().get("report")));
verify(service).reject(report, 1L);
}
} | agpl-3.0 |
Cinderpup/RoboInsta | src/main/java/eu/deswaef/cinderpup/roboinsta/ApplicationWebXml.java | 428 | package eu.deswaef.cinderpup.roboinsta;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
public class ApplicationWebXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(RoboInstaApplication.class);
}
}
| agpl-3.0 |
JHierrot/openprodoc | ProdocWeb/src/java/prodocServ/ListTerm.java | 2139 | /*
* OpenProdoc
*
* See the help doc files distributed with
* this work for additional information regarding copyright ownership.
* Joaquin Hierro licenses this file to You under:
*
* License GNU GPL v3 http://www.gnu.org/licenses/gpl.html
*
* you may not use this file except in compliance with the License.
* Unless agreed to in writing, software is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* author: Joaquin Hierro 2011
*
*/
package prodocServ;
import java.io.*;
import java.util.HashSet;
import java.util.Iterator;
import javax.servlet.http.*;
import prodoc.DriverGeneric;
import prodoc.PDThesaur;
/**
*
* @author jhierrot
* @version
*/
public class ListTerm extends ServParent
{
//-----------------------------------------------------------------------------------------------
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
out.println("<ListTerm>");
HttpSession Sess=Req.getSession(true);
String Id=(String)Req.getParameter("Id");
DriverGeneric PDSession=(DriverGeneric)Sess.getAttribute("PRODOC_SESS");
PDThesaur RootFolder = new PDThesaur(PDSession);
HashSet Child =RootFolder.getListDirectDescendList(Id);
for (Iterator it = Child.iterator(); it.hasNext();)
{
String ChildId=(String)it.next();
if (ChildId.compareTo(PDThesaur.ROOTTERM)==0)
continue;
PDThesaur ChildFolder=new PDThesaur(PDSession);
ChildFolder.Load(ChildId);
out.println("<Term><id>"+ChildFolder.getPDId()+"</id>");
out.println("<name>"+ChildFolder.getName()+"</name></Term>");
}
out.println("</ListTerm>");
}
/** Returns a short description of the servlet.
*/
public String getServletInfo()
{
return "Servlet AJAX returning list of Term";
}
//-----------------------------------------------------------------------------------------------
static public String getUrlServlet()
{
return("ListTerm");
}
}
| agpl-3.0 |
scionaltera/emergentmud | src/main/java/com/emergentmud/core/command/impl/QuitCommand.java | 2755 | /*
* EmergentMUD - A modern MUD with a procedurally generated world.
* Copyright (C) 2016-2018 Peter Keeler
*
* This file is part of EmergentMUD.
*
* EmergentMUD 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.
*
* EmergentMUD 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.emergentmud.core.command.impl;
import com.emergentmud.core.command.BaseCommand;
import com.emergentmud.core.model.Entity;
import com.emergentmud.core.model.stomp.GameOutput;
import com.emergentmud.core.service.MovementService;
import com.emergentmud.core.service.EntityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
@Component
public class QuitCommand extends BaseCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(QuitCommand.class);
private EntityService entityService;
private MovementService movementService;
@Inject
public QuitCommand(EntityService entityService,
MovementService movementService) {
this.entityService = entityService;
this.movementService = movementService;
setDescription("Leave the game.");
addParameter("now", true);
}
@Override
public GameOutput execute(GameOutput output, Entity entity, String command, String[] tokens, String raw) {
if (!"quit".equals(command.toLowerCase()) || !"now".equals(raw.toLowerCase())) {
output.append("Usage: QUIT <now>");
output.append("Please note that you must type out \"quit now\" in full to avoid doing it accidentally.");
return output;
}
GameOutput enterMessage = new GameOutput(String.format("[yellow]%s has left the game.", entity.getName()));
entityService.sendMessageToRoom(entity, enterMessage);
LOGGER.info("{} has left the game", entity.getName());
output.append("[yellow]Goodbye, " + entity.getName() + "[yellow]! Returning to the main menu...");
output.append("<script type=\"text/javascript\">setTimeout(function(){ window.location=\"/\"; }, 2000);</script>");
movementService.remove(entity);
return output;
}
}
| agpl-3.0 |
omnycms/omny-cms | services/omny-pages-service/src/main/java/ca/omny/pages/mappers/ThemeMapper.java | 1991 | package ca.omny.pages.mappers;
import com.google.gson.Gson;
import ca.omny.pages.models.Page;
import ca.omny.db.IDocumentQuerier;
import ca.omny.storage.StorageSystem;
import java.io.IOException;
import java.net.MalformedURLException;
public class ThemeMapper {
public String getThemeHtml(String themeName, String host, StorageSystem storageSystem, boolean preview) throws MalformedURLException, IOException {
Gson gson = new Gson();
boolean globalTheme = themeName.startsWith("global/");
if(globalTheme) {
themeName = themeName.substring("global/".length());
host = "www";
}
String versionFolder = preview?"drafts":"current";
String themeTemplatePath = String.format("themes/%s/%s/theme.html", versionFolder, themeName);
String themeContent = storageSystem.getFileContents(themeTemplatePath, host);
return themeContent;
}
public String getThemeName(String hostname, Page page, IDocumentQuerier querier) {
if(page.getCustomTheme()!=null) {
return page.getCustomTheme();
}
String themeName = this.getDefaultTheme(hostname,querier);
return themeName;
}
public String getDefaultTheme(String hostname, IDocumentQuerier querier) {
String key = querier.getKey("site_data",hostname,"default_theme");
String themeName = querier.get(key, String.class);
if(themeName==null) {
themeName = querier.get("default_theme", String.class);
}
return themeName;
}
public String getThemeCss(String themeName, String host, StorageSystem storageSystem, boolean preview) throws IOException {
String versionFolder = preview?"drafts":"current";
String themeCssPath = String.format("themes/%s/%s/theme.css", versionFolder, themeName);
String themeCss = storageSystem.getFileContents(themeCssPath, host);
return themeCss;
}
}
| agpl-3.0 |
Antokolos/NLB | NLBB/src/main/java/com/nlbhub/nlb/builder/config/Parameters.java | 2471 | /**
* @(#)Parameters.java
*
* This file is part of the Non-Linear Book project.
* Copyright (c) 2012-2014 Anton P. Kolosov
* Authors: Anton P. Kolosov, et al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
* ANTON P. KOLOSOV. ANTON P. KOLOSOV DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
* OF THIRD PARTY RIGHTS
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the Non-Linear Book software without
* disclosing the source code of your own applications.
*
* For more information, please contact Anton P. Kolosov at this
* address: antokolos@gmail.com
*
* Copyright (c) 2012 Anton P. Kolosov All rights reserved.
*/
package com.nlbhub.nlb.builder.config;
/**
* The Parameters class
*
* @author Anton P. Kolosov
* @version 1.0 7/6/12
*/
public class Parameters {
private static final Parameters SINGLETON = new Parameters();
public static Parameters singleton() {
return SINGLETON;
}
public double getArrowHeightCoef() {
return 0.25;
}
public double getArrowWidthCoef() {
return 30.0;
}
public double getArrowOffsetCoef() {
return 32.0;
}
public double getTextOffsetAboveLink() {
return 10.0;
}
public double getTextOffsetFromPageBorder() {
return 5.0;
}
}
| agpl-3.0 |
heniancheng/FRODO | src/frodo2/algorithms/bnbadopt/BoundsMsg.java | 2333 | /*
FRODO: a FRamework for Open/Distributed Optimization
Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek
FRODO 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.
FRODO 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/>.
How to contact the authors:
<http://frodo2.sourceforge.net/>
*/
package frodo2.algorithms.bnbadopt;
import frodo2.communication.MessageWith3Payloads;
import frodo2.solutionSpaces.Addable;
import frodo2.solutionSpaces.UtilitySolutionSpace;
/** A message containing the heuristics for the lower bound
*
* @param <Val> the type used for variable values
* @param <U> the type used for utility values
*/
public class BoundsMsg <Val extends Addable<Val>, U extends Addable<U> >
extends MessageWith3Payloads<String, String, UtilitySolutionSpace<Val, U>> {
/** Empty constructor used for externalization */
public BoundsMsg () { }
/** Constructor
* @param type the type of the message
* @param variableId variable name
* @param parent the parent of the variable
* @param lb lower bound
*/
public BoundsMsg(String type, String variableId, String parent, UtilitySolutionSpace<Val, U> lb) {
super(type, variableId, parent, lb);
}
/**
* @author Brammert Ottens, 19 mei 2009
* @return the receiving variable
*/
public String getReceiver() {
return this.getPayload2();
}
/**
* @author Brammert Ottens, 19 mei 2009
* @return the sending variable
*/
public String getSender() {
return this.getPayload1();
}
/**
* @author Thomas Leaute
* @return the bounds for the sending variable
*/
public UtilitySolutionSpace<Val, U> getBounds() {
return this.getPayload3();
}
/** @see MessageWith3Payloads#fakeSerialize() */
@Override
public void fakeSerialize () {
super.setPayload3(super.getPayload3().resolve());
}
} | agpl-3.0 |
mint-ntua/Mint-Athena | WEB-INF/src/java/gr/ntua/ivml/athena/harvesting/xml/schema/MetadataFormatType.java | 3457 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-792
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.03.12 at 05:08:17 PM EET
//
package gr.ntua.ivml.athena.harvesting.xml.schema;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for metadataFormatType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="metadataFormatType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="metadataPrefix" type="{http://www.openarchives.org/OAI/2.0/}metadataPrefixType"/>
* <element name="schema" type="{http://www.w3.org/2001/XMLSchema}anyURI"/>
* <element name="metadataNamespace" type="{http://www.w3.org/2001/XMLSchema}anyURI"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "metadataFormatType", propOrder = {
"metadataPrefix",
"schema",
"metadataNamespace"
})
public class MetadataFormatType {
@XmlElement(required = true)
protected String metadataPrefix;
@XmlElement(required = true)
@XmlSchemaType(name = "anyURI")
protected String schema;
@XmlElement(required = true)
@XmlSchemaType(name = "anyURI")
protected String metadataNamespace;
/**
* Gets the value of the metadataPrefix property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMetadataPrefix() {
return metadataPrefix;
}
/**
* Sets the value of the metadataPrefix property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMetadataPrefix(String value) {
this.metadataPrefix = value;
}
/**
* Gets the value of the schema property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSchema() {
return schema;
}
/**
* Sets the value of the schema property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSchema(String value) {
this.schema = value;
}
/**
* Gets the value of the metadataNamespace property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMetadataNamespace() {
return metadataNamespace;
}
/**
* Sets the value of the metadataNamespace property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMetadataNamespace(String value) {
this.metadataNamespace = value;
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_jpush_assemble_control/src/main/java/com/x/jpush/assemble/control/huawei/ValidatorUtils.java | 1304 | /*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei;
/**
* A tool for validating the parameters
*/
public class ValidatorUtils {
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
public static void checkState(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
}
| agpl-3.0 |
docdoku/docdoku-plm-smoke-tests | src/test/java/com/docdoku/test/arquillian/services/TestProductManagerBean.java | 3126 | package com.docdoku.test.arquillian.services;
import com.docdoku.core.configuration.BaselineCreation;
import com.docdoku.core.configuration.ProductBaseline;
import com.docdoku.core.exceptions.*;
import com.docdoku.core.product.ConfigurationItem;
import com.docdoku.core.product.ConfigurationItemKey;
import com.docdoku.core.services.IProductBaselineManagerLocal;
import com.docdoku.core.services.IProductManagerLocal;
import com.docdoku.server.esindexer.ESIndexer;
import com.sun.enterprise.security.ee.auth.login.ProgrammaticLogin;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import java.util.List;
/**
* @author Asmae CHADID
*/
@LocalBean
@Stateless
public class TestProductManagerBean {
@EJB
private IProductManagerLocal productManagerLocal;
@EJB
private IProductBaselineManagerLocal productBaselineManagerLocal;
@EJB
private ESIndexer esIndexer;
private ProgrammaticLogin loginP = new ProgrammaticLogin();
private String password = "password";
public ConfigurationItem createConfigurationItem(String login,String pWorkspaceId, String pId, String pDescription, String pDesignItemNumber) throws NotAllowedException, WorkspaceNotFoundException, CreationException, AccessRightException, PartMasterTemplateAlreadyExistsException, UserNotFoundException, ConfigurationItemAlreadyExistsException, PartMasterNotFoundException {
loginP.login(login, password.toCharArray());
ConfigurationItem configurationItem = productManagerLocal.createConfigurationItem(pWorkspaceId, pId, pDescription,pDesignItemNumber);
loginP.logout();
return configurationItem;
}
public List<ConfigurationItem> getListConfigurationItem(String login,String pWorkspaceId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException {
loginP.login(login, password.toCharArray());
List<ConfigurationItem> configurationItems = productManagerLocal.getConfigurationItems(pWorkspaceId);
loginP.logout();
return configurationItems;
}
public BaselineCreation baselineProduct(String login,ConfigurationItemKey configurationItemKey, String name, ProductBaseline.BaselineType type, String description) throws UserNotActiveException, WorkspaceNotFoundException, ConfigurationItemNotFoundException, UserNotFoundException, PartIterationNotFoundException, NotAllowedException, AccessRightException, ConfigurationItemNotReleasedException {
loginP.login(login, password.toCharArray());
BaselineCreation baselineCreation = productBaselineManagerLocal.createBaseline(configurationItemKey,name,type,description);
loginP.logout();
return baselineCreation;
}
public ProductBaseline getBaseline(String login,int baselineId) throws UserNotFoundException, WorkspaceNotFoundException, UserNotActiveException, BaselineNotFoundException {
loginP.login(login, password.toCharArray());
ProductBaseline baselineCreation = productBaselineManagerLocal.getBaseline(baselineId);
loginP.logout();
return baselineCreation;
}
}
| agpl-3.0 |
medsob/Tanaguru | rules/rgaa3.0/src/main/java/org/tanaguru/rules/rgaa30/Rgaa30Rule110204.java | 1474 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.rgaa30;
import org.tanaguru.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 11.2.4 of the referential Rgaa 3.0.
*
* For more details about the implementation, refer to <a href="http://tanaguru-rules-rgaa3.readthedocs.org/en/latest/Rule-11-2-4">the rule 11.2.4 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-11-2-4"> 11.2.4 rule specification</a>
*/
public class Rgaa30Rule110204 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Rgaa30Rule110204 () {
super();
}
} | agpl-3.0 |
simonzhangsm/voltdb | tests/frontend/org/voltdb/TestInvocationAcceptancePolicy.java | 7293 | /* This file is part of VoltDB.
* Copyright (C) 2008-2018 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb;
import static junit.framework.Assert.assertEquals;
import org.junit.Test;
import org.voltdb.catalog.Procedure;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.voltdb.InvocationPermissionPolicy.PolicyResult;
import org.voltdb.common.Permission;
public class TestInvocationAcceptancePolicy {
private AuthSystem.AuthUser createUser(boolean adhoc, boolean crud, boolean sysproc,
Procedure userProc, boolean readonly, boolean readonlysql, boolean allprocs)
{
AuthSystem.AuthUser user = mock(AuthSystem.AuthUser.class);
when(user.hasPermission(Permission.SQL)).thenReturn(adhoc);
when(user.hasPermission(Permission.SQLREAD)).thenReturn(readonlysql);
when(user.hasPermission(Permission.ADMIN)).thenReturn(sysproc);
when(user.hasPermission(Permission.DEFAULTPROC)).thenReturn(crud);
when(user.hasPermission(Permission.DEFAULTPROCREAD)).thenReturn(readonly);
if (userProc != null) {
when(user.hasUserDefinedProcedurePermission(userProc)).thenReturn(allprocs);
}
return user;
}
@Test
public void testSysprocUserPermission()
{
AuthSystem.AuthUser user = createUser(false, false, true, null, true, false, false);
StoredProcedureInvocation invocation = new StoredProcedureInvocation();
invocation.setProcName("@Pause");
Procedure proc = SystemProcedureCatalog.listing.get("@Pause").asCatalogProcedure();
InvocationPermissionPolicy policy = new InvocationSysprocPermissionPolicy();
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.ALLOW);
// A user that doesn't have admin permission
user = createUser(false, false, false, null, true, false, false);
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.DENY);
}
@Test
public void testAdHocUserPermission()
{
AuthSystem.AuthUser user = createUser(true, false, false, null, true, false, false);
StoredProcedureInvocation invocation = new StoredProcedureInvocation();
invocation.setProcName("@AdHoc_RW_MP");
invocation.setParams("insert into T values (1);");
Procedure proc = SystemProcedureCatalog.listing.get("@AdHoc_RW_MP").asCatalogProcedure();
InvocationPermissionPolicy policy = new InvocationSqlPermissionPolicy();
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.ALLOW);
// A user that doesn't have adhoc permission
user = createUser(false, false, false, null, true, true, true);
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.DENY);
}
@Test
public void testAdHocReadUserPermission()
{
AuthSystem.AuthUser user = createUser(false, false, false, null, true, true, true);
StoredProcedureInvocation invocation = new StoredProcedureInvocation();
invocation.setProcName("@AdHoc_RO_MP");
invocation.setParams("select * from T;");
Procedure proc = SystemProcedureCatalog.listing.get("@AdHoc_RO_MP").asCatalogProcedure();
InvocationPermissionPolicy policy = new InvocationSqlPermissionPolicy();
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.ALLOW);
// A user that doesn't have adhoc permission
user = createUser(false, false, false, null, true, false, false);
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.DENY);
}
@Test
public void testUserDefinedProcPermission()
{
Procedure proc = new Procedure();
StoredProcedureInvocation invocation = new StoredProcedureInvocation();
invocation.setProcName("MyProc");
invocation.setParams("test");
InvocationPermissionPolicy policy = new InvocationUserDefinedProcedurePermissionPolicy();
//WITH allproc access
AuthSystem.AuthUser user2 = createUser(false, false, false, proc, true, true, true);
assertEquals(policy.shouldAccept(user2, invocation, proc), PolicyResult.ALLOW);
//Without allproc
AuthSystem.AuthUser user3 = createUser(false, false, false, proc, false, false, false);
assertEquals(policy.shouldAccept(user3, invocation, proc), PolicyResult.DENY);
//We cant test individual authorized proc here.
}
@Test
public void testUserPermission()
{
Procedure proc = new Procedure();
proc.setDefaultproc(true);
AuthSystem.AuthUser user = createUser(false, true, false, proc, true, false, false);
StoredProcedureInvocation invocation = new StoredProcedureInvocation();
invocation.setProcName("A.insert");
invocation.setParams("test");
InvocationPermissionPolicy policy = new InvocationDefaultProcPermissionPolicy();
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.ALLOW);
// A user that doesn't have crud permission
user = createUser(false, false, false, null, true, false, false);
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.DENY);
}
@Test
public void testUserPermissionReadOnly()
{
Procedure proc = new Procedure();
proc.setDefaultproc(true);
proc.setReadonly(true);
AuthSystem.AuthUser user = createUser(false, false, false, proc, true, false, false);
StoredProcedureInvocation invocation = new StoredProcedureInvocation();
invocation.setProcName("X.select");
invocation.setParams("test");
InvocationPermissionPolicy policy = new InvocationDefaultProcPermissionPolicy();
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.ALLOW);
// A user that doesn't have crud permission
Procedure procw = new Procedure();
procw.setDefaultproc(true);
procw.setReadonly(false);
user = createUser(false, false, false, null, false, false, false);
assertEquals(policy.shouldAccept(user, invocation, proc), PolicyResult.DENY);
}
}
| agpl-3.0 |
hyperbox/client | src/main/java/io/kamax/hboxc/gui/net/MachineNATRulesDialog.java | 3447 | /*
* Hyperbox - Virtual Infrastructure Manager
* Copyright (C) 2015 Max Dor
*
* https://apps.kamax.io/hyperbox
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.kamax.hboxc.gui.net;
import io.kamax.hbox.comm.io.NetService_NAT_IO;
import io.kamax.hbox.comm.io.NetService_NAT_IP4_IO;
import io.kamax.hbox.exception.HyperboxException;
import io.kamax.hbox.hypervisor.vbox.net._NATRule;
import io.kamax.hboxc.gui._Cancelable;
import io.kamax.hboxc.gui._Refreshable;
import io.kamax.hboxc.gui._Saveable;
import io.kamax.hboxc.gui.action.CancelAction;
import io.kamax.hboxc.gui.action.SaveAction;
import io.kamax.hboxc.gui.builder.JDialogBuilder;
import io.kamax.hboxc.gui.utils.RefreshUtil;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.util.List;
public class MachineNATRulesDialog implements _Saveable, _Cancelable, _Refreshable {
/*
private String srvId;
private String vmId;
private String adaptId;
*/
private JDialog dialog;
private NATRulesView ip4;
private JPanel buttonPanel;
private JButton saveButton;
private JButton cancelButton;
private NetService_NAT_IO rules;
public static List<NetService_NAT_IO> getInput(String srvId, String vmId, String adaptId) {
return (new NATNetworkNATRulesDialog(srvId, vmId, adaptId)).getInput();
}
public MachineNATRulesDialog(String srvId, String vmId, String adaptId) {
/*
this.srvId = srvId;
this.vmId = vmId;
this.adaptId = adaptId;
*/
ip4 = new NATRulesView();
RefreshUtil.set(ip4.getComponent(), new _Refreshable() {
@Override
public void refresh() {
refresh();
}
});
saveButton = new JButton(new SaveAction(this));
cancelButton = new JButton(new CancelAction(this));
buttonPanel = new JPanel(new MigLayout("ins 0"));
buttonPanel.add(saveButton);
buttonPanel.add(cancelButton);
dialog = JDialogBuilder.get("NAT Rules", saveButton);
dialog.add(ip4.getComponent(), "grow,push,wrap");
dialog.add(buttonPanel, "growx,pushx,center");
}
public NetService_NAT_IO getInput() {
refresh();
dialog.setSize(538, 278);
dialog.setLocationRelativeTo(dialog.getParent());
dialog.setVisible(true);
return rules;
}
public void hide() {
dialog.setVisible(false);
}
@Override
public void cancel() {
rules = null;
hide();
}
@Override
public void save() throws HyperboxException {
rules = new NetService_NAT_IP4_IO(true);
for (_NATRule rule : ip4.getRules()) {
rules.addRule(rule);
}
hide();
}
@Override
public void refresh() {
// TODO
}
}
| agpl-3.0 |
opengeogroep/safetymaps-server | src/main/java/nl/opengeogroep/safetymaps/utils/DeletePhotoScheduler.java | 3486 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.opengeogroep.safetymaps.utils;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
/**
*
* @author martijn
*/
public class DeletePhotoScheduler implements ServletContextListener {
private static final Log LOG = LogFactory.getLog(DeletePhotoScheduler.class);
private static Scheduler scheduler = null;
private static ServletContext context;
@Override
public void contextInitialized(ServletContextEvent sce) {
this.context = sce.getServletContext();
try {
// get Scheduler (singleton)
scheduler = getInstance();
//Make job that executes the DeletePhotoJob
JobDetail job = JobBuilder.newJob(DeletePhotoJob.class)
.withIdentity("deletePhoto")
.withDescription("deletePhotos after x days")
.build();
//Make a trigger for the job, every sunday at 00:00:00am
CronExpression c = new CronExpression("0 0 0 ? * SUN *");
CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(c);
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("deletePhoto trigger")
.startNow()
.withSchedule(cronSchedule)
.build();
//schedule the job
scheduler.scheduleJob(job, trigger);
LOG.debug("Job deletePhoto created");
} catch (Exception e) {
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
if (scheduler != null) {
try {
scheduler.shutdown(true);
LOG.debug("scheduler stopped");
} catch (SchedulerException ex) {
LOG.error("Cannot shutdown quartz scheduler. ", ex);
}
}
}
public static Scheduler getInstance() throws SchedulerException {
if (scheduler == null) {
try {
Properties props = new Properties();
props.put("org.quartz.scheduler.instanceName", "DeletePhotoScheduler");
props.put("org.quartz.threadPool.threadCount", "1");
props.put("org.quartz.scheduler.interruptJobsOnShutdownWithWait", "true");
// Job store for monitoring does not need to be persistent
props.put("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
scheduler = new StdSchedulerFactory(props).getScheduler();
scheduler.start();
LOG.debug("scheduler created and started");
} catch (SchedulerException ex) {
LOG.error("Cannot create scheduler. ", ex);
}
}
return scheduler;
}
}
| agpl-3.0 |
yichaoS/cbioportal | service/src/main/java/org/cbioportal/service/impl/MutationServiceImpl.java | 3598 | package org.cbioportal.service.impl;
import org.cbioportal.model.Mutation;
import org.cbioportal.model.MutationSampleCountByGene;
import org.cbioportal.model.MutationSampleCountByKeyword;
import org.cbioportal.model.meta.MutationMeta;
import org.cbioportal.persistence.MutationRepository;
import org.cbioportal.service.MutationService;
import org.cbioportal.service.util.ChromosomeCalculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MutationServiceImpl implements MutationService {
@Autowired
private MutationRepository mutationRepository;
@Autowired
private ChromosomeCalculator chromosomeCalculator;
@Override
@PreAuthorize("hasPermission(#geneticProfileId, 'GeneticProfile', 'read')")
public List<Mutation> getMutationsInGeneticProfile(String geneticProfileId, String sampleId, String projection,
Integer pageSize, Integer pageNumber, String sortBy,
String direction) {
List<Mutation> mutationList = mutationRepository.getMutationsInGeneticProfile(geneticProfileId, sampleId,
projection, pageSize, pageNumber, sortBy, direction);
mutationList.forEach(mutation -> chromosomeCalculator.setChromosome(mutation.getGene()));
return mutationList;
}
@Override
@PreAuthorize("hasPermission(#geneticProfileId, 'GeneticProfile', 'read')")
public MutationMeta getMetaMutationsInGeneticProfile(String geneticProfileId, String sampleId) {
return mutationRepository.getMetaMutationsInGeneticProfile(geneticProfileId, sampleId);
}
@Override
@PreAuthorize("hasPermission(#geneticProfileId, 'GeneticProfile', 'read')")
public List<Mutation> fetchMutationsInGeneticProfile(String geneticProfileId, List<String> sampleIds,
String projection, Integer pageSize, Integer pageNumber,
String sortBy, String direction) {
List<Mutation> mutationList = mutationRepository.fetchMutationsInGeneticProfile(geneticProfileId, sampleIds,
projection, pageSize, pageNumber, sortBy, direction);
mutationList.forEach(mutation -> chromosomeCalculator.setChromosome(mutation.getGene()));
return mutationList;
}
@Override
@PreAuthorize("hasPermission(#geneticProfileId, 'GeneticProfile', 'read')")
public MutationMeta fetchMetaMutationsInGeneticProfile(String geneticProfileId, List<String> sampleIds) {
return mutationRepository.fetchMetaMutationsInGeneticProfile(geneticProfileId, sampleIds);
}
@Override
@PreAuthorize("hasPermission(#geneticProfileId, 'GeneticProfile', 'read')")
public List<MutationSampleCountByGene> getSampleCountByEntrezGeneIds(String geneticProfileId,
List<Integer> entrezGeneIds) {
return mutationRepository.getSampleCountByEntrezGeneIds(geneticProfileId, entrezGeneIds);
}
@Override
@PreAuthorize("hasPermission(#geneticProfileId, 'GeneticProfile', 'read')")
public List<MutationSampleCountByKeyword> getSampleCountByKeywords(String geneticProfileId, List<String> keywords) {
return mutationRepository.getSampleCountByKeywords(geneticProfileId, keywords);
}
}
| agpl-3.0 |
needle4j/needle4j | src/test/java/org/needle4j/injection/CurrentUser.java | 231 | package org.needle4j.injection;
import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Qualifier
@Retention(RUNTIME)
public @interface CurrentUser {
}
| lgpl-2.1 |
hal/core | gui/src/main/java/org/jboss/as/console/client/semver/NormalVersion.java | 4935 | /*
* The MIT License
*
* Copyright 2012-2015 Zafar Khaja <zafarkhaja@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jboss.as.console.client.semver;
import com.google.common.base.Joiner;
/**
* The {@code NormalVersion} class represents the version core.
*
* This class is immutable and hence thread-safe.
*
* @author Zafar Khaja <zafarkhaja@gmail.com>
* @since 0.2.0
*/
class NormalVersion implements Comparable<NormalVersion> {
/**
* The major version number.
*/
private final int major;
/**
* The minor version number.
*/
private final int minor;
/**
* The patch version number.
*/
private final int patch;
/**
* Constructs a {@code NormalVersion} with the
* major, minor and patch version numbers.
*
* @param major the major version number
* @param minor the minor version number
* @param patch the patch version number
* @throws IllegalArgumentException if one of the version numbers is a negative integer
*/
NormalVersion(int major, int minor, int patch) {
if (major < 0 || minor < 0 || patch < 0) {
throw new IllegalArgumentException(
"Major, minor and patch versions MUST be non-negative integers."
);
}
this.major = major;
this.minor = minor;
this.patch = patch;
}
/**
* Returns the major version number.
*
* @return the major version number
*/
int getMajor() {
return major;
}
/**
* Returns the minor version number.
*
* @return the minor version number
*/
int getMinor() {
return minor;
}
/**
* Returns the patch version number.
*
* @return the patch version number
*/
int getPatch() {
return patch;
}
/**
* Increments the major version number.
*
* @return a new instance of the {@code NormalVersion} class
*/
NormalVersion incrementMajor() {
return new NormalVersion(major + 1, 0, 0);
}
/**
* Increments the minor version number.
*
* @return a new instance of the {@code NormalVersion} class
*/
NormalVersion incrementMinor() {
return new NormalVersion(major, minor + 1, 0);
}
/**
* Increments the patch version number.
*
* @return a new instance of the {@code NormalVersion} class
*/
NormalVersion incrementPatch() {
return new NormalVersion(major, minor, patch + 1);
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(NormalVersion other) {
int result = major - other.major;
if (result == 0) {
result = minor - other.minor;
if (result == 0) {
result = patch - other.patch;
}
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof NormalVersion)) {
return false;
}
return compareTo((NormalVersion) other) == 0;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = 17;
hash = 31 * hash + major;
hash = 31 * hash + minor;
hash = 31 * hash + patch;
return hash;
}
/**
* Returns the string representation of this normal version.
*
* A normal version number MUST take the form X.Y.Z where X, Y, and Z are
* non-negative integers. X is the major version, Y is the minor version,
* and Z is the patch version. (SemVer p.2)
*
* @return the string representation of this normal version
*/
@Override
public String toString() {
return Joiner.on('.').join(major, minor, patch);
}
}
| lgpl-2.1 |
cytoscape/cytoscape-impl | vizmap-gui-impl/src/main/java/org/cytoscape/view/vizmap/gui/internal/view/cellrenderer/IconCellRenderer.java | 4491 | package org.cytoscape.view.vizmap.gui.internal.view.cellrenderer;
/*
* #%L
* Cytoscape VizMap GUI Impl (vizmap-gui-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2021 The Cytoscape Consortium
* %%
* This program 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 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.awt.Color;
import java.awt.Component;
import java.lang.reflect.Method;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
/**
* Renderer for cells with icon.
*
* Icon size is fixed, so caller of this class is responsible for passing proper
* icons.
*/
public class IconCellRenderer<T> extends JPanel implements TableCellRenderer, ListCellRenderer {
private static final long serialVersionUID = 8942821990143018260L;
private static final float FONT_SIZE = 14.0f;
final JLabel iconLbl;
final JLabel textLbl;
private Map<? extends T, Icon> icons;
public IconCellRenderer(final Map<? extends T, Icon> icons) {
this.icons = icons;
iconLbl = new JLabel();
iconLbl.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
textLbl = new JLabel();
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(iconLbl);
add(Box.createHorizontalStrut(20));
add(textLbl);
add(Box.createHorizontalGlue());
}
@Override
public Component getListCellRendererComponent(final JList list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus) {
update(value, isSelected, cellHasFocus);
setBackground(isSelected ?
UIManager.getColor("Table.selectionBackground") : UIManager.getColor("Table.background"));
textLbl.setFont(UIManager.getFont("TextField.font").deriveFont(FONT_SIZE));
final Color BORDER_COLOR = UIManager.getColor("Separator.foreground");
final Border BORDER = BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, BORDER_COLOR),
BorderFactory.createEmptyBorder(4, 4, 4, 4)
);
setBorder(BORDER);
return this;
}
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus,
final int row, final int column) {
update(value, isSelected, hasFocus);
setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
iconLbl.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
textLbl.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
return this;
}
@SuppressWarnings("unchecked")
private void update(final Object value, final boolean isSelected, final boolean hasFocus) {
setBackground(isSelected ?
UIManager.getColor("Table.selectionBackground") : UIManager.getColor("Table.background"));
final String label = getLabel((T)value);
final Icon icon = icons.get(value);
iconLbl.setIcon(icon);
textLbl.setText(label);
textLbl.setToolTipText(label);
}
private String getLabel(final T value) {
String text = null;
if (value != null) {
// Use reflection to check existence of "getDisplayName" method
final Class<? extends Object> valueClass = value.getClass();
try {
final Method displayMethod = valueClass.getMethod("getDisplayName", (Class<?>)null);
final Object returnVal = displayMethod.invoke(value, (Class<?>)null);
if (returnVal != null)
text = returnVal.toString();
} catch (Exception e) {
// Use toString is failed.
text = value.toString();
}
}
return text;
}
}
| lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/client/gui/GuiSelectClassmoogleknight.java | 3374 | package fr.toss.client.gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ResourceLocation;
import com.google.code.chatterbotapi.ChatterBot;
import com.google.code.chatterbotapi.ChatterBotFactory;
import com.google.code.chatterbotapi.ChatterBotSession;
import com.google.code.chatterbotapi.ChatterBotType;
import cpw.mods.fml.client.config.GuiUtils;
import fr.toss.common.Main;
import fr.toss.common.command.ChatColor;
public class GuiSelectClassmoogleknight extends GuiScreen {
public static final ResourceLocation CLASSES = new ResourceLocation("magiccrusade:textures/gui/classes.png");
@Override
public void initGui()
{
GuiButton buttons[];
buttons = new GuiButton[1];
buttons[0] = new GuiButton(59, this.width / 2 - 50, this.height + 0 + 1 - 144, 80, 20, ChatColor.RESET + I18n.format("More info"));
for (GuiButton b : buttons)
this.buttonList.add(b);
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
protected void keyTyped(char c, int i)
{
super.keyTyped(c, i);
}
/**
* Draws the screen and all the components in it.
*/
@Override
public void drawScreen(int x, int y, float dunno)
{
int x1 = this.width / 4 + 100;
int y1 = this.height / 8;
int a = 0;
int b = 0;
this.drawDefaultBackground();
this.drawCenteredString(this.fontRendererObj, I18n.format("Moogle Knight"), this.width / 2, 14, Integer.MAX_VALUE / 2);
this.mc.getTextureManager().bindTexture(CLASSES);
for (int i = 0; i < 1; i++)
{
GuiUtils.drawTexturedModalRect(x1, y1, a, b, 256, 256, 0);
x1 += this.width / 4;
a += 100;
if (i == 2)
{
a = 0;
b += 52;
x1 = this.width / 2 - 26;
y1 = this.height / 2 - 26;
}
}
super.drawScreen(x, y, dunno);
}
/**
* Called from the main game loop to update the screen.
*/
@Override
public void updateScreen()
{
super.updateScreen();
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override
protected void actionPerformed(GuiButton b)
{
GuiClasseInformation gui;
String classe;
String description[];
String advices[];
if (b.id == 59)
{
description = new String[1];
advices = new String[4];
classe = ChatColor.WHITE + I18n.format("classe.Moogleknight.slogan");
description[0] = I18n.format("classe.Moogleknight.line1");
//description[1] = I18n.format("classe.Moogleknight.line2");
//description[2] = I18n.format("classe.Moogleknight.line3");
advices[0] = ChatColor.GREEN + "+ " + I18n.format("stats.mana");
advices[1] = ChatColor.GREEN + "+ " + I18n.format("stats.clarity");
advices[2] = ChatColor.GREEN + "+" + I18n.format("stats.mana_regen");
advices[3] = ChatColor.RED + "- " + I18n.format("stats.strength");
gui = new GuiClasseInformation(classe, description, advices, 2, 1, Integer.MAX_VALUE, 18);
this.mc.displayGuiScreen(gui);
}
}
}
| lgpl-2.1 |
cogtool/cogtool | java/edu/cmu/cs/hcii/cogtool/uimodel/WidgetFigureSupport.java | 6734 | /*******************************************************************************
* CogTool Copyright Notice and Distribution Terms
* CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* CogTool 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.
*
* CogTool 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 CogTool; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* CogTool makes use of several third-party components, with the
* following notices:
*
* Eclipse SWT version 3.448
* Eclipse GEF Draw2D version 3.2.1
*
* Unless otherwise indicated, all Content made available by the Eclipse
* Foundation is provided to you under the terms and conditions of the Eclipse
* Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this
* Content and is also available at http://www.eclipse.org/legal/epl-v10.html.
*
* CLISP version 2.38
*
* Copyright (c) Sam Steingold, Bruno Haible 2001-2006
* This software is distributed under the terms of the FSF Gnu Public License.
* See COPYRIGHT file in clisp installation folder for more information.
*
* ACT-R 6.0
*
* Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere &
* John R Anderson.
* This software is distributed under the terms of the FSF Lesser
* Gnu Public License (see LGPL.txt).
*
* Apache Jakarta Commons-Lang 2.1
*
* This product contains software developed by the Apache Software Foundation
* (http://www.apache.org/)
*
* jopt-simple version 1.0
*
* Copyright (c) 2004-2013 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Mozilla XULRunner 1.9.0.5
*
* 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/.
* 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 J2SE(TM) Java Runtime Environment version 5.0
*
* Copyright 2009 Sun Microsystems, Inc., 4150
* Network Circle, Santa Clara, California 95054, U.S.A. All
* rights reserved. U.S.
* See the LICENSE file in the jre folder for more information.
******************************************************************************/
package edu.cmu.cs.hcii.cogtool.uimodel;
import edu.cmu.cs.hcii.cogtool.model.GridButton;
import edu.cmu.cs.hcii.cogtool.model.IWidget;
/**
* Interface for finding a figure for a given widget and determining
* next/prev figure if given figure is part of a group.
*/
public interface WidgetFigureSupport
{
/**
* Returns a Graphical Widget from the supplied Widget.
*
* Returns null if the widget is not in the figure list.
* @param widget
*/
public GraphicalWidget<?> getWidgetFigure(IWidget widget);
/**
* If the given figure is part of a group, return the next in the group.
* If the given figure is not part of a group or there is no next
* member, return <code>null</code>.
*
* @param fromWidgetFig
* @return
*/
public GraphicalWidget<?> getNextInGroup(GraphicalWidget<?> fromWidgetFig);
/**
* If the given figure is part of a group, return the previous in the
* group. If the given figure is not part of a group or there is no
* previous member, return <code>null</code>.
*
* @param fromWidgetFig
* @return
*/
public GraphicalWidget<?> getPrevInGroup(GraphicalWidget<?> fromWidgetFig);
/**
* If the given figure is part of a group, return the last widget in the
* group. If the given figure is not part of a group or there is no
* previous member, return <code>null</code>.
*/
public GraphicalWidget<?> getLastInGroup(GraphicalWidget<?> fromWidgetFig);
/**
* Returns the radio button closest to the left of the given button, or
* <code>null</code> if no buttons in the group are close enough to
* qualify.
*/
public GraphicalWidget<GridButton> getLeftGridFigure(GraphicalGridButton gridFig);
/**
* Returns the radio button closest to the right of the given button, or
* <code>null</code> if no buttons in the group are close enough to
* qualify.
*/
public GraphicalWidget<GridButton> getRightGridFigure(GraphicalGridButton gridFig);
/**
* Returns the radio button closest above the given button, or
* <code>null</code> if no buttons in the group are close enough to
* qualify.
*/
public GraphicalWidget<GridButton> getTopGridFigure(GraphicalGridButton gridFig);
/**
* Returns the radio button closest below the given button, or
* <code>null</code> if no buttons in the group are close enough to
* qualify.
*/
public GraphicalWidget<GridButton> getBottomGridFigure(GraphicalGridButton gridFig);
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | libraries/libformula/src/main/java/org/pentaho/reporting/libraries/formula/operators/PercentageOperator.java | 2781 | /*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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 Lesser General Public License for more details.
*
* Copyright (c) 2006 - 2013 Pentaho Corporation and Contributors. All rights reserved.
*/
package org.pentaho.reporting.libraries.formula.operators;
import org.pentaho.reporting.libraries.formula.EvaluationException;
import org.pentaho.reporting.libraries.formula.FormulaContext;
import org.pentaho.reporting.libraries.formula.LibFormulaErrorValue;
import org.pentaho.reporting.libraries.formula.lvalues.TypeValuePair;
import org.pentaho.reporting.libraries.formula.typing.Type;
import org.pentaho.reporting.libraries.formula.typing.TypeRegistry;
import org.pentaho.reporting.libraries.formula.typing.coretypes.NumberType;
import org.pentaho.reporting.libraries.formula.util.NumberUtil;
import java.math.BigDecimal;
/**
* Creation-Date: 02.11.2006, 10:27:03
*
* @author Thomas Morgner
*/
public class PercentageOperator implements PostfixOperator {
private static final BigDecimal HUNDRED = new BigDecimal( 100.0 );
private static final long serialVersionUID = -5578115447971169716L;
public PercentageOperator() {
}
public TypeValuePair evaluate( final FormulaContext context, final TypeValuePair value1 )
throws EvaluationException {
final Object rawValue = value1.getValue();
if ( rawValue == null ) {
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_NA_VALUE );
}
final Type type = value1.getType();
final TypeRegistry typeRegistry = context.getTypeRegistry();
if ( type.isFlagSet( Type.NUMERIC_TYPE ) == false &&
type.isFlagSet( Type.ANY_TYPE ) == false ) {
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE );
}
// return the same as zero minus value.
final Number number = typeRegistry.convertToNumber( type, rawValue );
final BigDecimal value = NumberUtil.getAsBigDecimal( number );
final BigDecimal percentage = NumberUtil.divide( value, HUNDRED );
return new TypeValuePair( NumberType.GENERIC_NUMBER, percentage );
}
public String toString() {
return "%";
}
}
| lgpl-2.1 |
yunqing/imgrtrv | src/feature/EdgeOrientationHistogram.java | 10791 | package feature;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Vector;
public class EdgeOrientationHistogram {
private double []pixels = new double [imgsize];
public static int imgsize = 5050*3350;//the largest size of the image
public static double PI = 3.14159;
int []maxtry = {1,2,3,2,1,
2,4,6,4,2,
3,6,7,6,3,
2,4,6,4,2,
3,6,7,6,3};
int []gauss = maxtry;
public List<Integer> extract(BufferedImage image, int dimension) {
int height = image.getHeight();
int width = image.getWidth();
for(int x = 0; x<width; x++)
{
for(int y = 0; y<height; y++)
{
Color color = new Color(image.getRGB(x, y));
pixels[y*width+x] = (double) (0.299*color.getRed()+0.587*color.getGreen()+0.114*color.getBlue());
//System.out.println(pixels[x][y]+" ");
}
//System.out.println("\n");
}
Gauss(gauss,pixels,width,height);//gauss smooth
double []gradcomp = new double[imgsize];
double []angel = new double[width*height];
compgrad(pixels, gradcomp, angel,width, height);
int[] edge_flag = new int[imgsize];
maximum_restrain(gradcomp,angel,width,height,edge_flag);
thresholding(gradcomp,edge_flag,width,height);
int dim = dimension;//dimensionality
int[] histogram = new int [dim];
double[] NormalHistogram=new double[dim];
edge_hist(edge_flag,angel,width,height,histogram,NormalHistogram,dim);
return arrayToList(histogram); // NormalHistogram;
}
private static void Gauss(int[] gauss,double[] pixels,int w, int h){
double[] grtemp = new double[imgsize];
for(int j = 0; j<h; j++)
for(int i = 0; i<w; i++)
{
grtemp[j*w+i] = 0;
for(int countj = j-2; countj<j+3; countj++)
{
if(countj>=0 && countj<h)
for(int counti = i-2; counti<i+3; counti++)
if(counti>=0 && counti<w)
grtemp[j*w+i] += gauss[(countj-(j-2))*5 + (counti-(i-2))]*pixels[countj*w+counti];
}
}
int sumgauss = 0;
for(int m = 0; m<25; m++)
sumgauss += gauss[m];
for(int j = 0; j<h; j++)
{
for(int i = 0; i<w; i++)
grtemp[j*w+i] = grtemp[j*w+i]/sumgauss;
}
for(int j = 0; j<h; j++)
{
for(int i = 0; i<w; i++)
pixels[j*w+i] = grtemp[j*w+i];
}
//for(int i = 0; i<w*h; i++)
//System.out.println(pixels[i]);
}
private static void compgrad(double[] pixels, double[] grad, double[] angel,int w, int h)
{
double []gradx = new double[imgsize];
double []grady = new double[imgsize];
int x,y;//the directional derivative of x and y
for( y = 0; y<h; y++)
for( x = 0; x<w; x++)
{
if(x == 0 || x == w-1 || y == 0 || y == h-1)
{
gradx[y*w+x] = 0;
grady[y*w+x] = 0;
}
else
{
gradx[y*w+x] = (pixels[(y+1)*w+x]-pixels[y*w+x]+pixels[(y+1)*w+x+1]-pixels[y*w+x+1])/2;
grady[y*w+x] = (pixels[y*w+x]-pixels[y*w+x+1]+pixels[y*w+x+1]-pixels[(y+1)*w+x+1])/2;
}
}
for(y = 0; y<h; y++)
for(x = 0; x<w; x++)
grad[y*w+x] = Math.sqrt(gradx[y*w+x]*gradx[y*w+x]+grad[y*w+x]*grady[y*w+x]);
//get the direction angel of the gradient
for(y = 0; y<h; y++)
for(x = 0; x<w; x++)
{
if(x == 0 || x == w-1 || y == 0 ||y == h-1)
angel[y*w+x] = 0;
else
{
if(gradx[y*w+x] == 0 && grady[y*w+x] != 0)
{
if(grady[y*w+x]>0)
angel[y*w+x] = 90;
else
angel[y*w+x] = 270;
}
else if(gradx[y*w+x] == 0 && grady[y*w+x] == 0)
{
angel[y*w+x] = 0;
}
else if(gradx[y*w+x]*grady[y*w+x]>=0)
{
if(gradx[y*w+x]>0 && grady[y*w+x]>=0)
angel[y*w+x] = Math.atan(grady[y*w+x]/gradx[y*w+x])*180/PI;//the first quadrant
else
angel[y*w+x] = Math.atan(grady[y*w+x]/gradx[y*w+x])*180/PI+180;//the third quadrant
}
else
{
if(gradx[y*w+x]<0 && grady[y*w+x]>0)
angel[y*w+x] = Math.atan(grady[y*w+x]/gradx[y*w+x])*180/PI+180;//the second quadrant
else
angel[y*w+x] = Math.atan(grady[y*w+x]/gradx[y*w+x])*180/PI+360;//the forth quadrant
}
}
}
//for(int i = 0; i<w*h; i++)
//System.out.println(angel[i]);
}
private static void maximum_restrain(double[] gradcomp, double[] angel, int w, int h, int[] edge_flag)
{
for (int y=0;y<h;y++)
for (int x=0;x<w;x++)
{
if(x==0 || x==w-1 || y==0 || y==h-1)
edge_flag[y*w+x]=0;
else
{
if ((angel[y*w+x]>=0 && angel[y*w+x]<45) || (angel[y*w+x]>=180 && angel[y*w+x]<225))
{
if (gradcomp[y*w+x]>gradcomp[y*w+x+1] && gradcomp[y*w+x]>gradcomp[y*w+x-1]&&
Math.abs(angel[y*w+x]-angel[y*w+x+1])<45 && Math.abs(angel[y*w+x]-angel[y*w+x-1])<45)
edge_flag[y*w+x]=255;
else
edge_flag[y*w+x]=0;
}
else if((angel[y*w+x]>=45 && angel[y*w+x]<90) || (angel[y*w+x]>=225 && angel[y*w+x]<270))
{
if(gradcomp[y*w+x]>gradcomp[(y-1)*w+x+1] && gradcomp[y*w+x]>gradcomp[(y+1)*w+x-1]&&
Math.abs(angel[y*w+x]-angel[(y-1)*w+x+1])<45 && Math.abs(angel[y*w+x]-angel[(y+1)*w+x-1])<45)
edge_flag[y*w+x]=255;
else
edge_flag[y*w+x]=0;
}
else if((angel[y*w+x]>=90 && angel[y*w+x]<135) || (angel[y*w+x]>=270 && angel[y*w+x]<315))
{
if (gradcomp[y*w+x]>gradcomp[(y-1)*w+x] && gradcomp[y*w+x]>gradcomp[(y+1)*w+x]&&
Math.abs(angel[y*w+x]-angel[(y-1)*w+x])<45 && Math.abs(angel[y*w+x]-angel[(y+1)*w+x])<45)
edge_flag[y*w+x]=255;
else
edge_flag[y*w+x]=0;
}
else
{
if (gradcomp[y*w+x]>gradcomp[(y-1)*w+x-1] && gradcomp[y*w+x]>gradcomp[(y+1)*w+x+1]&&
Math.abs(angel[y*w+x]-angel[(y-1)*w+x-1])<45 && Math.abs(angel[y*w+x]-angel[(y+1)*w+x+1])<45)
edge_flag[y*w+x]=255;
else
edge_flag[y*w+x]=0;
}
}
}
//for(int i = 0; i<h*w; i++)
//System.out.println(edge_flag[i]);
}
private static void TH1(double[] gradcomp,int w,int h,double TH)
{
int x,y;
double max=0;
int[] histogram1=new int[64];
for(int i = 0; i<64; i++)
histogram1[i] = 0;
//find max
for(y=0;y<h;y++)
{
for(x=0;x<w;x++)
{
if (gradcomp[(y*w+x)]>max)
{
max=gradcomp[y*w+x];
}
}
}
double d=(double)(max)/64;
//quantized
for(y=0;y<h;y++)
{
for(x=0;x<w;x++)
{
for(float k=0;k<=max;k+=d)
{
if(k<=gradcomp[y*w+x] && gradcomp[y*w+x]<(k+d))
{
gradcomp[y*w+x]=k;break;
}
}
}
}
//histogram
for (y=0;y<h;y++)
{
for (x=0;x<w;x++)
{
histogram1[(int)(gradcomp[y*w+x]/d)]++;
}
}
int temp;
for(int i=0;i<64;i++)
{
for(int j=i+1;j<64;j++)
{
if(histogram1[i]>histogram1[j])
{
temp=histogram1[i];
histogram1[i]=histogram1[j];
histogram1[j]=temp;
}
}
}
//sum
double sum=0;
int i = 0;
for( i=0;i<64;i++)
{
sum+=histogram1[i];
if(sum>(0.7*w*h))
break;
}
TH=(double)(max*i/64);
}
private static void thresholding(double[] gradcomp, int[]edge_flag,int w,int h)
{
int x,y;
double TH=16;
double THh;
double beta = 0.08;
TH1(gradcomp,w,h,TH);
THh=TH*beta;
double THl=0.4*THh;
for (y=1;y<h-1;y++)
{
for (x=1;x<w-1;x++)
{
if (edge_flag[y*w+x]==255 )
{
if (gradcomp[y*w+x]<THl)
{
edge_flag[y*w+x]=0;
}
else if (gradcomp[y*w+x]>=THl && gradcomp[y*w+x]<THh)
{
int flag=0;
for (int j=y-1;j<y+2;j++)
{
for (int i=x-1;i<x+2;i++)
{
if (gradcomp[j*w+i]>=THh)
{
flag=1;edge_flag[y*w+x]=255;
break;
}
}
if (flag==1) break;
}
if (flag==0) edge_flag[y*w+x]=0;
}
else
edge_flag[y*w+x]=255;
}
}
}
}
private static void edge_hist(int[] edge_flag,double[] angel,int w,int h,int[] histogram,double[] normal,int dim)
{
int[] histogram1 = new int[dim];
for (int i=0;i<dim;i++)
{
histogram1[i]=0;
}
for (int y=0;y<h;y++)
{
for (int x=0;x<w;x++)
{
if (edge_flag[y*w+x]!=0)
{
histogram1[(int)angel[y*w+x]*dim/360]++;
}
}
}
//normalize
int sum=0;
for (int i=0;i<dim;i++)
{
sum+=histogram1[i];
}
for (int i=0;i<dim;i++)
{
histogram[i]=histogram1[i];
normal[i]=(double)(histogram1[i])/sum;
}
}
private static List<Integer> arrayToList(int [] intArray) {
List<Integer> list = new Vector<>(intArray.length);
int length = intArray.length;
for (int i = 0; i < length; i++) {
list.add(intArray[i]);
}
return list;
}
}
| lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemse/iteme67.java | 156 | package fr.toss.FF7itemse;
public class iteme67 extends FF7itemsebase {
public iteme67(int id) {
super(id);
setUnlocalizedName("iteme67");
}
}
| lgpl-2.1 |
zanata/zanata-mt | common/src/main/java/org/zanata/magpie/annotation/DefaultProvider.java | 1462 | /*
* Copyright 2017, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file 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.zanata.magpie.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
/**
* Qualifier for default translation provider if none is specified.
*/
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface DefaultProvider {
}
| lgpl-2.1 |
languagetool-org/languagetool | languagetool-core/src/test/java/org/languagetool/MultiThreadedJLanguageToolTest.java | 4592 | /* LanguageTool, a natural language style checker
* Copyright (C) 2013 Daniel Naber (http://www.danielnaber.de)
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool;
import org.junit.Test;
import org.languagetool.language.Demo;
import org.languagetool.rules.MultipleWhitespaceRule;
import org.languagetool.rules.Rule;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.UppercaseSentenceStartRule;
import org.languagetool.rules.patterns.AbstractPatternRule;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.RejectedExecutionException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public class MultiThreadedJLanguageToolTest {
@Test
public void testCheck() throws IOException {
MultiThreadedJLanguageTool lt1 = new MultiThreadedJLanguageTool(new Demo());
lt1.setCleanOverlappingMatches(false);
List<String> ruleMatchIds1 = getRuleMatchIds(lt1);
assertEquals(9, ruleMatchIds1.size());
lt1.shutdown();
JLanguageTool lt2 = new JLanguageTool(new Demo());
lt2.setCleanOverlappingMatches(false);
List<String> ruleMatchIds2 = getRuleMatchIds(lt2);
assertEquals(ruleMatchIds1, ruleMatchIds2);
}
@Test
public void testShutdownException() throws IOException {
MultiThreadedJLanguageTool tool = new MultiThreadedJLanguageTool(new Demo());
getRuleMatchIds(tool);
tool.shutdown();
try {
getRuleMatchIds(tool);
fail("should have been rejected as the thread pool has been shut down");
} catch (RejectedExecutionException ignore) {}
}
@Test
public void testTextAnalysis() throws IOException {
MultiThreadedJLanguageTool lt = new MultiThreadedJLanguageTool(new Demo());
List<AnalyzedSentence> analyzedSentences = lt.analyzeText("This is a sentence. And another one.");
assertThat(analyzedSentences.size(), is(2));
assertThat(analyzedSentences.get(0).getTokens().length, is(10));
assertThat(analyzedSentences.get(0).getTokensWithoutWhitespace().length, is(6)); // sentence start has its own token
assertThat(analyzedSentences.get(1).getTokens().length, is(7));
assertThat(analyzedSentences.get(1).getTokensWithoutWhitespace().length, is(5));
lt.shutdown();
}
@Test
public void testConfigurableThreadPoolSize() throws IOException {
MultiThreadedJLanguageTool lt = new MultiThreadedJLanguageTool(new Demo());
assertEquals(Runtime.getRuntime().availableProcessors(), lt.getThreadPoolSize());
lt.shutdown();
}
private List<String> getRuleMatchIds(JLanguageTool lt) throws IOException {
String input = "A small toast. No error here. Foo go bar. First goes last there, please!";
List<RuleMatch> matches = lt.check(input);
List<String> ruleMatchIds = new ArrayList<>();
for (RuleMatch match : matches) {
ruleMatchIds.add(match.getRule().getId());
}
return ruleMatchIds;
}
@Test
public void testTwoRulesOnly() throws IOException {
MultiThreadedJLanguageTool lt = new MultiThreadedJLanguageTool(new FakeLanguage() {
@Override
protected synchronized List<AbstractPatternRule> getPatternRules() {
return Collections.emptyList();
}
@Override
public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) {
// fewer rules than processors (depending on the machine), should at least not crash
return Arrays.asList(
new UppercaseSentenceStartRule(messages, this),
new MultipleWhitespaceRule(messages, this)
);
}
});
assertThat(lt.check("my test text").size(), is(2));
lt.shutdown();
}
}
| lgpl-2.1 |
unicesi/pdg_composicion_patrones | Composition_Project/src/composition/java/patterns/service_locator/examples/ProductoEJBRemote.java | 875 | package composition.java.patterns.service_locator.examples;
import java.util.HashMap;
import javax.ejb.Remote;
import composition.tienda.entities.Producto;
@Remote
public interface ProductoEJBRemote {
/**
* Lista los productos existentes.
*
* @return lista de productos List<Producto>
*/
public HashMap<Long,Producto> getProductos();
/**
* Encuentra un producto dado el identificador.
*
* @return
*/
public Producto findByIdProducto(long idProducto);
/**
* Crea un producto en la base de datos y de manera local.
*
* @param producto
* @return true- si fue agregado, false en caso contrario.
*/
public boolean crearProducto(Producto producto);
/**
* Retorna un true si inicializó y tiene inicializada su lista de productos.
* @return true or false.
*/
public boolean inicializo();
}
| lgpl-2.1 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-common/src/main/java/org/xwiki/crypto/internal/digest/factory/AbstractBcDigestFactory.java | 2721 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.crypto.internal.digest.factory;
import javax.inject.Named;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.xwiki.component.annotation.Component;
import org.xwiki.crypto.Digest;
import org.xwiki.crypto.internal.digest.BouncyCastleDigest;
import org.xwiki.crypto.params.DigestParameters;
/**
* Abstract base class for factory creating Bouncy Castle based digest.
*
* @version $Id$
* @since 5.4M1
*/
public abstract class AbstractBcDigestFactory implements BcDigestFactory
{
@Override
public String getDigestAlgorithmName()
{
String hint = null;
Named named = this.getClass().getAnnotation(Named.class);
if (named != null) {
hint = named.value();
} else {
Component component = this.getClass().getAnnotation(Component.class);
if (component != null && component.hints().length > 0) {
hint = component.hints()[0];
}
}
return hint;
}
@Override
public int getDigestSize()
{
return getDigestInstance().getDigestSize();
}
@Override
public Digest getInstance()
{
return new BouncyCastleDigest(getDigestInstance(), getAlgorithmIdentifier(), null);
}
@Override
public Digest getInstance(DigestParameters parameters)
{
return getInstance();
}
@Override
public Digest getInstance(byte[] encoded)
{
AlgorithmIdentifier algId = AlgorithmIdentifier.getInstance(encoded);
if (!algId.getAlgorithm().equals(getAlgorithmIdentifier().getAlgorithm())) {
throw new IllegalArgumentException("Invalid algorithm identifier in encoded data for this digest factory: "
+ algId.getAlgorithm().getId());
}
return getInstance();
}
}
| lgpl-2.1 |
jbossws/jbossws-cxf | modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/jbws1799/IUserAccountServiceExt.java | 1888 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file 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.jboss.test.ws.jaxws.jbws1799;
import javax.ejb.Remote;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* Second service interface
*
* @author richard.opalka@jboss.com
*
* @since Oct 8, 2007
*/
@Remote
@WebService
@SOAPBinding
(
style=SOAPBinding.Style.DOCUMENT,
use=SOAPBinding.Use.LITERAL
)
public interface IUserAccountServiceExt
{
@WebMethod
@RequestWrapper(className="org.jboss.test.ws.jaxws.jbws1799.jaxws.Authenticate1")
@ResponseWrapper(className="org.jboss.test.ws.jaxws.jbws1799.jaxws.Authenticate1Response")
public boolean authenticate
(
@WebParam(name="username") String username,
@WebParam(name="password") String password
);
}
| lgpl-2.1 |
shabanovd/exist | src/org/exist/xquery/functions/fn/FunNormalizeUnicode.java | 8821 | /* eXist Native XML Database
* Copyright (C) 2006-2009, The eXist Project
* http://exist-db.org/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* $Id$
*/
package org.exist.xquery.functions.fn;
import org.apache.log4j.Logger;
import org.exist.dom.QName;
import org.exist.xquery.Cardinality;
import org.exist.xquery.Dependency;
import org.exist.xquery.ErrorCodes;
import org.exist.xquery.Function;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.Profiler;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Implements fn:normalize-unicode()
* Uses icu4j by introspection
*
* @author perig
*
*/
public class FunNormalizeUnicode extends Function {
protected static final Logger logger = Logger.getLogger(FunNormalizeUnicode.class);
private String normalizationForm = null;
private Class<?> clazz = null;
private Field modeField = null;
private Object modeObject = null;
private static final Integer DUMMY_INTEGER = Integer.valueOf(0);
private Constructor<?> constructor = null;
private Method method = null;
protected static final String FUNCTION_DESCRIPTION_0_PARAM =
"Returns the value of the context item normalized according to the " +
"nomalization form \"NFC\"\n\n";
protected static final String FUNCTION_DESCRIPTION_1_PARAM =
"Returns the value of $arg normalized according to the " +
"normalization criteria for a normalization form identified " +
"by the value of $normalization-form. The effective value of " +
"the $normalization-form is computed by removing leading and " +
"trailing blanks, if present, and converting to upper case.\n\n" +
"If the value of $arg is the empty sequence, returns the zero-length string.\n\n" +
"See [Character Model for the World Wide Web 1.0: Normalization] " +
"for a description of the normalization forms.\n\n" +
"- If the effective value of $normalization-form is \"NFC\", then the value " +
"returned by the function is the value of $arg in Unicode Normalization Form C (NFC).\n" +
"- If the effective value of $normalization-form is \"NFD\", then the value " +
"returned by the function is the value of $arg in Unicode Normalization Form D (NFD).\n" +
"- If the effective value of $normalization-form is \"NFKC\", then the value " +
"returned by the function is the value of $arg in Unicode Normalization Form KC (NFKC).\n" +
"- If the effective value of $normalization-form is \"NFKD\", then the value " +
"returned by the function is the value of $arg in Unicode Normalization Form KD (NFKD).\n" +
"- If the effective value of $normalization-form is \"FULLY-NORMALIZED\", then the value " +
"returned by the function is the value of $arg in the fully normalized form.\n" +
"- If the effective value of $normalization-form is the zero-length string, " +
"no normalization is performed and $arg is returned.\n\n" +
"Conforming implementations must support normalization form \"NFC\" and may " +
"support normalization forms \"NFD\", \"NFKC\", \"NFKD\", \"FULLY-NORMALIZED\". " +
"They may also support other normalization forms with implementation-defined semantics. " +
"If the effective value of the $normalization-form is other than one of the values " +
"supported by the implementation, then an error is raised [err:FOCH0003].";
protected static final FunctionParameterSequenceType ARG_PARAM = new FunctionParameterSequenceType("arg", Type.STRING, Cardinality.ZERO_OR_ONE, "The unicode string to normalize");
protected static final FunctionParameterSequenceType NF_PARAM = new FunctionParameterSequenceType("normalization-form", Type.STRING, Cardinality.ONE, "The normalization form");
protected static final FunctionReturnSequenceType RETURN_TYPE = new FunctionReturnSequenceType(Type.STRING, Cardinality.ONE, "the normalized text");
public final static FunctionSignature signatures [] = {
new FunctionSignature(
new QName("normalize-unicode", Function.BUILTIN_FUNCTION_NS),
FUNCTION_DESCRIPTION_0_PARAM,
new SequenceType[] { ARG_PARAM },
RETURN_TYPE
),
new FunctionSignature (
new QName("normalize-unicode", Function.BUILTIN_FUNCTION_NS),
FUNCTION_DESCRIPTION_1_PARAM,
new SequenceType[] { ARG_PARAM, NF_PARAM },
RETURN_TYPE
)
};
public FunNormalizeUnicode(XQueryContext context, FunctionSignature signature) {
super(context, signature);
}
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
if (context.getProfiler().isEnabled()) {
context.getProfiler().start(this);
context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null)
{context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);}
if (contextItem != null)
{context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());}
}
if (contextItem != null)
{contextSequence = contextItem.toSequence();}
Sequence result;
final Sequence s1 = getArgument(0).eval(contextSequence);
if (s1.isEmpty())
{result = StringValue.EMPTY_STRING;}
else {
String newNormalizationForm = "NFC";
if (getArgumentCount() > 1)
{newNormalizationForm = getArgument(1).eval(contextSequence).getStringValue().toUpperCase().trim();}
//TODO : handle the "FULLY-NORMALIZED" string...
if ("".equals(newNormalizationForm))
{result = new StringValue(s1.getStringValue());}
else {
Object returnedObject = null;
try {
if (clazz == null)
{clazz = Class.forName("com.ibm.icu.text.Normalizer");}
if (modeField == null || !normalizationForm.equals(newNormalizationForm)) {
try {
modeField = clazz.getField(newNormalizationForm);
} catch (final NoSuchFieldException e) {
logger.error("err:FOCH0003: unknown normalization form");
throw new XPathException(this, ErrorCodes.FOCH0003, "unknown normalization form");
}
//com.ibm.icu.text.Normalizer.Mode
modeObject = modeField.get(null);
normalizationForm = newNormalizationForm;
}
if (constructor == null)
//Second argument shouldn't be a problem : modeField always has the same type
{constructor = clazz.getConstructor(
new Class[] { String.class, modeField.getType(), Integer.TYPE}
);}
final Object[] args = new Object[] { s1.getStringValue(), modeObject, DUMMY_INTEGER };
if (method == null)
{method = clazz.getMethod( "getText", (Class[])null );}
//Normalizer n = new Normalizer(s1.getStringValue(), Normalizer.NFC, 0);
final Object instance = constructor.newInstance(args);
//result = new StringValue(n.getText());
returnedObject = method.invoke( instance, (Object[])null );
} catch (final Exception e) {
logger.error("Can not find the ICU4J library in the classpath " + e.getMessage());
throw new XPathException(this, "Can not find the ICU4J library in the classpath " + e.getMessage());
}
result = new StringValue((String)returnedObject);
}
}
if (context.getProfiler().isEnabled())
{context.getProfiler().end(this, "", result);}
return result;
}
}
| lgpl-2.1 |
wbstr/dbunit | src/test/java/org/dbunit/util/QualifiedTableNameTest.java | 5325 | /*
*
* The DbUnit Database Testing Framework
* Copyright (C)2004-2008, DbUnit.org
*
* 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.
*
* You should have received a copy of the GNU Lesser 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
*
*/
package org.dbunit.util;
import org.dbunit.database.DatabaseConfig;
import junit.framework.TestCase;
/**
* @author gommma
* @author Last changed by: $Author$
* @version $Revision$ $Date$
* @since 2.3.0
*/
public class QualifiedTableNameTest extends TestCase
{
public void testQualifiedTableNamePresent_PrecedesDefaultSchemaName()
{
QualifiedTableName qualifiedTableName = new QualifiedTableName("MYSCHEMA.MYTABLE", "DEFAULT_SCHEMA");
assertEquals("MYSCHEMA", qualifiedTableName.getSchema());
assertEquals("MYTABLE", qualifiedTableName.getTable());
assertEquals("MYSCHEMA.MYTABLE", qualifiedTableName.getQualifiedName());
}
public void testQualifiedTableNameNotPresentUsingDefaultSchema()
{
QualifiedTableName qualifiedTableName = new QualifiedTableName("MYTABLE", "DEFAULT_SCHEMA");
assertEquals("DEFAULT_SCHEMA", qualifiedTableName.getSchema());
assertEquals("MYTABLE", qualifiedTableName.getTable());
assertEquals("DEFAULT_SCHEMA.MYTABLE", qualifiedTableName.getQualifiedName());
}
public void testQualifiedTableNameNotPresentAndNoDefaultSchema()
{
QualifiedTableName qualifiedTableName = new QualifiedTableName("MYTABLE", null);
assertEquals(null, qualifiedTableName.getSchema());
assertEquals("MYTABLE", qualifiedTableName.getTable());
assertEquals("MYTABLE", qualifiedTableName.getQualifiedName());
}
public void testQualifiedTableNameNotPresentAndEmptyDefaultSchema()
{
QualifiedTableName qualifiedTableName = new QualifiedTableName("MYTABLE", "");
assertEquals("", qualifiedTableName.getSchema());
assertEquals("MYTABLE", qualifiedTableName.getTable());
assertEquals("MYTABLE", qualifiedTableName.getQualifiedName());
}
public void testGetQualifiedTableName()
{
String qualifiedName = new QualifiedTableName("MY_SCHEMA.MY_TABLE", null, "'?'").getQualifiedName();
assertEquals("'MY_SCHEMA'.'MY_TABLE'", qualifiedName);
}
public void testGetQualifiedTableName_DefaultSchema()
{
String qualifiedName = new QualifiedTableName("MY_TABLE", "DEFAULT_SCHEMA", "'?'").getQualifiedName();
assertEquals("'DEFAULT_SCHEMA'.'MY_TABLE'", qualifiedName);
}
public void testGetQualifiedTableName_DefaultSchema_FeatureEnabled()
{
DatabaseConfig config = new DatabaseConfig();
config.setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
String qualifiedName = new QualifiedTableName("MY_TABLE", "DEFAULT_SCHEMA", null).getQualifiedNameIfEnabled(config);
assertEquals("DEFAULT_SCHEMA.MY_TABLE", qualifiedName);
}
public void testGetQualifiedTableName_DefaultSchema_FeatureDisabled()
{
DatabaseConfig config = new DatabaseConfig();
config.setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, false);
String qualifiedName = new QualifiedTableName("MY_TABLE", "DEFAULT_SCHEMA", null).getQualifiedNameIfEnabled(config);
assertEquals("MY_TABLE", qualifiedName);
}
public void testGetQualifiedTableName_DefaultSchema_FeatureEnabled_Escaping()
{
DatabaseConfig config = new DatabaseConfig();
config.setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
String qualifiedName = new QualifiedTableName("MY_TABLE", "DEFAULT_SCHEMA", "'?'").getQualifiedNameIfEnabled(config);
assertEquals("'DEFAULT_SCHEMA'.'MY_TABLE'", qualifiedName);
}
public void testGetQualifiedTableName_DefaultSchema_FeatureDisabled_Escaping()
{
DatabaseConfig config = new DatabaseConfig();
config.setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, false);
String qualifiedName = new QualifiedTableName("MY_TABLE", "DEFAULT_SCHEMA", "'?'").getQualifiedNameIfEnabled(config);
assertEquals("'MY_TABLE'", qualifiedName);
}
public void testGetQualifiedTableName_DefaultSchema_FeatureEnabled_EscapingWithoutQuestionmark()
{
DatabaseConfig config = new DatabaseConfig();
config.setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
String qualifiedName = new QualifiedTableName("MY_TABLE", "DEFAULT_SCHEMA", "'").getQualifiedNameIfEnabled(config);
assertEquals("'DEFAULT_SCHEMA'.'MY_TABLE'", qualifiedName);
}
public void testConstructorWithNullTable()
{
try {
new QualifiedTableName(null, "SCHEMA");
fail("Should not be able to create object with null table");
}
catch(NullPointerException expected){
assertEquals("The parameter 'tableName' must not be null", expected.getMessage());
}
}
}
| lgpl-2.1 |
OOjDREW/OOjDREW | src/main/java/org/ruleml/oojdrew/parsing/RuleMLParser.java | 8359 | // OO jDREW - An Object Oriented extension of the Java Deductive Reasoning Engine for the Web
// Copyright (C) 2005 Marcel Ball
//
// 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.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
package org.ruleml.oojdrew.parsing;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.Vector;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Nodes;
import nu.xom.ParsingException;
import org.apache.log4j.Level;
import org.ruleml.oojdrew.Configuration;
import org.ruleml.oojdrew.util.DefiniteClause;
/**
* A class for parsing RuleML. This is broken into two section. The RuleMLParser
* class which is the public interface that users access; and the RuleML88Parser
* class; which implements the parsing of the RuleML 0.88 + rests syntax that is
* currently supported.
*
* <p>
* Title: OO jDREW
* </p>
*
* <p>
* Description: Reasoning Engine for the Semantic Web - Supporting OO RuleML
* 0.88
* </p>
*
* <p>
* Copyright: Copyright (c) 2005
* </p>
*
* @author Marcel A. Ball
* @version 0.89
*/
public class RuleMLParser implements PreferenceChangeListener {
/**
* A buffer that stores clauses that have already been parsed.
*/
private Vector<DefiniteClause> clauses;
private Configuration config;
private RuleMLFormat rmlFormat;
private Level logLevel;
/**
* Constructs a new parser object.
*
* @param config
* The configuration instance which should be used
*/
public RuleMLParser(Configuration config) {
clauses = new Vector<DefiniteClause>();
this.config = config;
config.addPreferenceChangeListener(this);
preferenceChange(null);
}
/**
* Gets an iterator over all clauses that are stored in the internal clause
* buffer. This method does not automatically clear items from the buffer.
*
* @return Iterator An iterator over all clauses in the buffer.
*/
public Iterator<DefiniteClause> iterator() {
return clauses.iterator();
}
/**
* Clears the internal buffer; and forces a garbage collection cycle. This
* allows the easy reuse of a parser object.
*/
public void clear() {
clauses = new Vector<DefiniteClause>();
System.gc();
}
/**
* @see jdrew.oo.parsing.RuleMLParser#parseDocument
*/
public void parseFile(String filename) throws ParseException, ParsingException, IOException {
File file = new File(filename);
parseFile(file);
}
/**
* @see jdrew.oo.parsing.RuleMLParser#parseDocument
*/
public void parseFile(File file) throws ParseException, ParsingException, IOException {
Builder bl = new Builder();
Document doc = bl.build(file);
parseDocument(doc);
}
/**
* @see jdrew.oo.parsing.RuleMLParser#parseDocument
*/
public void parseRuleMLString(String contents) throws ParseException, ParsingException, IOException {
Builder bl = new Builder();
StringReader sr = new StringReader(contents);
Document doc = bl.build(sr);
parseDocument(doc);
}
/**
* Parses a document containing a knowledge base that is in the indicated
* format. If additional backed parsers are created then additional formats
* will be added.
*
* NOTE: It may be a good idea to add format auto detection based upon the
* XSD and/or DTD that is referenced by the document.
*
* @param format
* RuleMLVersion The RuleML version for the back-end parser
*
* @param doc
* The document which should be parsed
*
* @throws ParseException
* A ParseException is thrown if there is an error in the
* document that causes parsing to fail.
*
* @throws ParsingException
* A ParsingException is thrown if there is an error in parsing
* the document at an XML level or a ValidityException
* (subclass) is thrown if the XML document is not well * formed
* or does not conform to the DTD specified.
*/
public void parseDocument(Document doc) throws ParseException, ParsingException {
RuleMLDocumentParser parser = new RuleMLDocumentParser(rmlFormat, clauses);
parser.setLogLevel(logLevel);
parser.parseRuleMLDocument(doc);
}
/**
* Parses a RuleML query
*
* @param contents
* The document content
*
* @return A DefiniteClause containing the parsed document
*
* @throws ParseException
* @throws ParsingException
* @throws IOException
*/
public DefiniteClause parseRuleMLQuery(String contents)
throws ParseException, ParsingException, IOException {
contents = ensureQueryTag(contents);
contents = buildFakeImplication(contents);
parseRuleMLString(contents);
return (DefiniteClause) clauses.lastElement();
}
/**
* Builds a fake implication which is needed to satisfy the reasoning
* engine.
*
* @param query
* An input query
*
* @return Input query as a RuleML implication
*/
private String buildFakeImplication(String query) {
Builder builder = new Builder();
StringReader stringReader = new StringReader(query);
Document document;
try {
document = builder.build(stringReader);
} catch (Exception e) {
// Cannot happen
e.printStackTrace();
return "";
}
Element queryElement = document.getRootElement();
RuleMLTagNames rmlTags = new RuleMLTagNames(rmlFormat);
Element rel = new Element(rmlTags.REL);
rel.insertChild("$top", 0);
Element topAtom = new Element(rmlTags.ATOM);
topAtom.appendChild(rel);
Nodes atoms = queryElement.removeChildren();
Element implies = new Element(rmlTags.IMPLIES);
for (int i = 0; i < atoms.size(); ++i) {
implies.appendChild(atoms.get(i));
}
implies.appendChild(topAtom);
queryElement.appendChild(implies);
return document.toXML();
}
/**
* Manually add <Query> wrapper if not exists
*
* @param query
* An input query
*
* @return Input query encapsulated with a <Query> tag
*/
private String ensureQueryTag(String query) {
// Evil hack: encapsulate the query contents in a pair of <Query> tags
RuleMLTagNames rmlTags = new RuleMLTagNames(rmlFormat);
query = query.trim();
String queryTagOpen = String.format("<%s>", rmlTags.QUERY);
String queryTagClose = String.format("</%s>", rmlTags.QUERY);
if (!query.contains(queryTagOpen)) {
query = String.format("%s%s%s", queryTagOpen, query, queryTagClose);
}
return query;
}
/**
* Updates parser configuration when preferences have changed
*/
public void preferenceChange(PreferenceChangeEvent evt) {
rmlFormat = config.getRuleMLFormat();
logLevel = config.getLogLevel();
}
}
| lgpl-2.1 |
joval/jacob | samples/com/jacob/samples/applet/JacobTestApplet.java | 2425 | package com.jacob.samples.applet;
import java.applet.Applet;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* Example applet to demonstrate:
* 1. The use of jacob from an applet
* 2. To show how to distribute the jacob native lib with the applet (also works with webstart)
*
* Comment on 2.:
* The way shown here is quite straight forward and it is not necessary to use
* a mechanism like the "DLLFromJARClassLoader" or something similar...
*
* @author ttreeck, www.nepatec.de
*
*/
public class JacobTestApplet extends Applet implements ActionListener {
private static final long serialVersionUID = 4492492907986849158L;
TextField in;
TextField out;
Button calc;
ActiveXComponent sC = null;
/**
* startup method
*/
@Override
public void init() {
setLayout(new FlowLayout());
add(this.in = new TextField("1+1", 16));
add(this.out = new TextField("?", 16));
add(this.calc = new Button("Calculate"));
this.calc.addActionListener(this);
}
/**
* Returns information about this applet.
* According to the java spec:
* "An applet should override this method to return a String containing information about the author, version, and copyright of the applet."
*
* @return information about the applet.
*/
@Override
public String getAppletInfo() {
return "Jacob Test Applet. Written by ttreeck, nepatec GmbH & Co. KG.\nhttp://www.nepatec.de";
}
/**
* Returns information about the parameters that are understood by this applet.
* According to the java spec:
* "An applet should override this method to return an array of Strings describing these parameters."
*
* @return array with a set of three Strings containing the name, the type, and a description.
*/
@Override
public String[][] getParameterInfo(){
return new String[][]{};
}
/**
* action method that receives button actions
*
* @param ev the event
*/
public void actionPerformed(ActionEvent ev) {
if (this.sC == null) {
String lang = "VBScript";
this.sC = new ActiveXComponent("ScriptControl");
Dispatch.put(this.sC, "Language", lang);
}
Variant v = Dispatch.call(this.sC, "Eval", this.in.getText());
this.out.setText(v.toString());
}
} | lgpl-2.1 |
vincent-zurczak/petals-se-client | src/swt/java/org/ow2/petals/engine/client/swt/tabs/MessageComposite.java | 15623 | /****************************************************************************
*
* Copyright (c) 2012, Linagora
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
package org.ow2.petals.engine.client.swt.tabs;
import java.io.File;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.ow2.petals.engine.client.model.BasicMessageBean;
import org.ow2.petals.engine.client.swt.ClientApplication;
import org.ow2.petals.engine.client.swt.ImageIds;
import org.ow2.petals.engine.client.swt.SwtUtils;
import org.ow2.petals.engine.client.swt.dialogs.KeyValueDialog;
import org.ow2.petals.engine.client.swt.viewers.FilesLabelProvider;
import org.ow2.petals.engine.client.swt.viewers.MessagePropertiesContentProvider;
import org.ow2.petals.engine.client.swt.viewers.MessagePropertiesLabelProvider;
/**
* A widget to display elements of message.
* @author Vincent Zurczak - Linagora
*/
public class MessageComposite extends SashForm {
private Menu menu;
private TableViewer propertiesViewer, attachmentsViewer;
private StyledText styledText;
private final ClientApplication clientApp;
private final Map<String,String> properties = new LinkedHashMap<String,String> ();
private final Set<File> attachments = new LinkedHashSet<File> ();
private final String title;
/**
* Constructor.
* @param title
* @param parent
* @param clientApp
*/
public MessageComposite( String title, Composite parent, ClientApplication clientApp ) {
super( parent, SWT.VERTICAL );
setLayoutData( new GridData( GridData.FILL_BOTH ));
setSashWidth( 10 );
this.clientApp = clientApp;
this.title = title;
createPayloadSection();
createPropertiesSection();
createAttachmentsSection();
setWeights( new int[] { 70, 15, 15 });
}
/**
* @return the menu
*/
@Override
public Menu getMenu() {
return this.menu;
}
/**
* @return the styledText
*/
public StyledText getStyledText() {
return this.styledText;
}
/**
* @return the attachmentsViewer
*/
public TableViewer getAttachmentsViewer() {
return this.attachmentsViewer;
}
/**
* @return the properties
*/
public Map<String, String> getProperties() {
return this.properties;
}
/**
* @return the attachments
*/
public Set<File> getAttachments() {
return this.attachments;
}
/**
* @return the pay-load
*/
public String getPayload() {
return this.styledText.getText();
}
/**
* @param payload the pay-load (can be null)
*/
public void setPayload( String payload ) {
this.styledText.setText( payload == null ? "" : payload );
}
/**
* Updates the data and widgets managed by this class.
* @param bmb a basic message bean (null to clear all the fields)
*/
public void setInput( BasicMessageBean bmb ) {
this.attachments.clear();
this.properties.clear();
if( bmb == null ) {
this.styledText.setText( "" );
} else {
this.styledText.setText( bmb.getXmlPayload() != null ? bmb.getXmlPayload() : "" );
if( bmb.getAttachments() != null )
this.attachments.addAll( bmb.getAttachments());
if( bmb.getProperties() != null )
this.properties.putAll( bmb.getProperties());
}
this.attachmentsViewer.refresh();
this.propertiesViewer.refresh();
}
/**
* Creates the section for the pay-load.
*/
private void createPayloadSection() {
// Container
Composite container = new Composite( this, SWT.NONE );
GridLayoutFactory.swtDefaults().spacing( 5, 0 ).margins( 0, 0 ).applyTo( container );
container.setLayoutData( new GridData( GridData.FILL_BOTH ));
Composite subContainer = new Composite( container, SWT.NONE );
GridLayoutFactory.swtDefaults().numColumns( 2 ).margins( 0, 0 ).extendedMargins( 0, 5, 0, 0 ).applyTo( subContainer );
subContainer.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ));
// Menu + Label
final ToolBar toolBar = new ToolBar( subContainer, SWT.FLAT );
new Label( subContainer, SWT.NONE ).setText( this.title + " - XML Payload" );
// XML Viewer
this.styledText = SwtUtils.createXmlViewer( container, this.clientApp.getColorManager(), false );
// Link the menu and the tool-bar
this.menu = new Menu( getShell(), SWT.POP_UP);
final ToolItem item = new ToolItem( toolBar, SWT.FLAT );
item.setImage( JFaceResources.getImage( ImageIds.VIEW_MENU_16x16 ));
item.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
Rectangle rect = item.getBounds();
Point pt = new Point( rect.x, rect.y + rect.height );
pt = toolBar.toDisplay( pt );
MessageComposite.this.menu.setLocation( pt.x, pt.y );
MessageComposite.this.menu.setVisible( true );
}
});
}
/**
* Creates the section for the message properties.
*/
private void createPropertiesSection() {
// The container
Composite container = new Composite( this, SWT.NONE );
container.setLayoutData( new GridData( GridData.FILL_BOTH ));
GridLayoutFactory.swtDefaults().numColumns( 2 ).margins( 0, 0 ).applyTo( container );
Composite subContainer = new Composite( container, SWT.NONE );
GridLayoutFactory.swtDefaults().numColumns( 2 ).margins( 0, 0 ).extendedMargins( 0, 5, 0, 0 ).applyTo( subContainer );
GridDataFactory.swtDefaults().span( 2, 1 ).grab( true, false ).align( SWT.FILL, SWT.CENTER ).applyTo( subContainer );
// Menu + Label
final ToolBar toolBar = new ToolBar( subContainer, SWT.FLAT );
new Label( subContainer, SWT.NONE ).setText( "Message Properties" );
// The properties
this.propertiesViewer = createPropertiesViewer( container );
this.propertiesViewer.setInput( this.properties );
// The buttons
Composite buttonsComposite = new Composite( container, SWT.NONE );
GridLayoutFactory.swtDefaults().margins( 0, 0 ).applyTo( buttonsComposite );
buttonsComposite.setLayoutData( new GridData( SWT.DEFAULT, SWT.BEGINNING, false, false ));
Button b = new Button( buttonsComposite, SWT.PUSH );
b.setText( "Add..." );
b.setToolTipText( "Add a new message property" );
b.setLayoutData( new GridData( SWT.FILL, SWT.DEFAULT, true, false ));
b.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent( Event e ) {
KeyValueDialog dlg = new KeyValueDialog( getShell(),MessageComposite.this.properties );
if( dlg.open() == Window.OK ) {
MessageComposite.this.properties.put( dlg.getKey(), dlg.getValue());
MessageComposite.this.propertiesViewer.refresh();
}
}
});
b = new Button( buttonsComposite, SWT.PUSH );
b.setText( "Remove" );
b.setToolTipText( "Remove the selected message property" );
b.setLayoutData( new GridData( SWT.FILL, SWT.DEFAULT, true, false ));
b.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent( Event e ) {
ISelection s = MessageComposite.this.propertiesViewer.getSelection();
for( Iterator<?> it = ((IStructuredSelection) s).iterator(); it.hasNext(); ) {
String key = (String) ((Map.Entry<?,?>) it.next()).getKey();
MessageComposite.this.properties.remove( key );
}
MessageComposite.this.propertiesViewer.refresh();
}
});
// Link the menu and the tool-bar
final Menu localMenu = new Menu( getShell(), SWT.POP_UP);
final ToolItem item = new ToolItem( toolBar, SWT.FLAT );
item.setImage( JFaceResources.getImage( ImageIds.VIEW_MENU_16x16 ));
item.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
Rectangle rect = item.getBounds();
Point pt = new Point( rect.x, rect.y + rect.height );
pt = toolBar.toDisplay( pt );
localMenu.setLocation( pt.x, pt.y );
localMenu.setVisible( true );
}
});
MenuItem menuItem = new MenuItem ( localMenu, SWT.PUSH );
menuItem.setText( "Clear All the Properties" );
menuItem.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent( Event e ) {
MessageComposite.this.properties.clear();
MessageComposite.this.propertiesViewer.refresh();
}
});
}
/**
* Creates the section for the message attachments.
*/
private void createAttachmentsSection() {
// The container
Composite container = new Composite( this, SWT.NONE );
container.setLayoutData( new GridData( GridData.FILL_BOTH ));
GridLayoutFactory.swtDefaults().numColumns( 2 ).margins( 0, 0 ).applyTo( container );
Composite subContainer = new Composite( container, SWT.NONE );
GridLayoutFactory.swtDefaults().numColumns( 2 ).margins( 0, 0 ).extendedMargins( 0, 5, 0, 0 ).applyTo( subContainer );
GridDataFactory.swtDefaults().span( 2, 1 ).grab( true, false ).align( SWT.FILL, SWT.CENTER ).applyTo( subContainer );
// Menu + Label
final ToolBar toolBar = new ToolBar( subContainer, SWT.FLAT );
new Label( subContainer, SWT.NONE ).setText( "File Attachments" );
// The attachments
this.attachmentsViewer = createAttachmentsViewer( container );
this.attachmentsViewer.setInput( this.attachments );
// The buttons
Composite buttonsComposite = new Composite( container, SWT.NONE );
GridLayoutFactory.swtDefaults().margins( 0, 0 ).applyTo( buttonsComposite );
buttonsComposite.setLayoutData( new GridData( SWT.DEFAULT, SWT.BEGINNING, false, false ));
Button b = new Button( buttonsComposite, SWT.PUSH );
b.setText( "Add..." );
b.setToolTipText( "Add a new message property" );
b.setLayoutData( new GridData( SWT.FILL, SWT.DEFAULT, true, false ));
b.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent( Event e ) {
FileDialog dlg = new FileDialog( getShell(), SWT.MULTI );
if( dlg.open() != null ) {
for( String s : dlg.getFileNames())
MessageComposite.this.attachments.add( new File( dlg.getFilterPath(), s ));
MessageComposite.this.attachmentsViewer.refresh();
MessageComposite.this.clientApp.validateRequest();
}
}
});
b = new Button( buttonsComposite, SWT.PUSH );
b.setText( "Remove" );
b.setToolTipText( "Remove the selected message property" );
b.setLayoutData( new GridData( SWT.FILL, SWT.DEFAULT, true, false ));
b.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent( Event e ) {
ISelection s = MessageComposite.this.attachmentsViewer.getSelection();
for( Iterator<?> it = ((IStructuredSelection) s).iterator(); it.hasNext(); )
MessageComposite.this.attachments.remove( it.next());
MessageComposite.this.attachmentsViewer.refresh();
MessageComposite.this.clientApp.validateRequest();
}
});
// Link the menu and the tool-bar
final Menu localMenu = new Menu( getShell(), SWT.POP_UP);
final ToolItem item = new ToolItem( toolBar, SWT.FLAT );
item.setImage( JFaceResources.getImage( ImageIds.VIEW_MENU_16x16 ));
item.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
Rectangle rect = item.getBounds();
Point pt = new Point( rect.x, rect.y + rect.height );
pt = toolBar.toDisplay( pt );
localMenu.setLocation( pt.x, pt.y );
localMenu.setVisible( true );
}
});
MenuItem menuItem = new MenuItem ( localMenu, SWT.PUSH );
menuItem.setText( "Remove All the Attachments" );
menuItem.addListener( SWT.Selection, new Listener() {
@Override
public void handleEvent( Event e ) {
MessageComposite.this.attachments.clear();
MessageComposite.this.attachmentsViewer.refresh();
}
});
}
/**
* Creates a viewer for message properties.
* @param parent the parent
* @return a table viewer with the right columns
*/
private TableViewer createPropertiesViewer( Composite parent ) {
TableViewer viewer = new TableViewer( parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER );
viewer.setContentProvider( new MessagePropertiesContentProvider());
viewer.setLabelProvider( new MessagePropertiesLabelProvider());
viewer.getTable().setLayoutData( new GridData( GridData.FILL_BOTH ));
viewer.getTable().setHeaderVisible( true );
viewer.getTable().setLinesVisible( true );
new TableColumn( viewer.getTable(), SWT.NONE ).setText( "Key" );
new TableColumn( viewer.getTable(), SWT.NONE ).setText( "Value" );
TableLayout layout = new TableLayout();
layout.addColumnData( new ColumnWeightData( 50, 75, true ));
layout.addColumnData( new ColumnWeightData( 50, 75, true ));
viewer.getTable().setLayout( layout );
return viewer;
}
/**
* Creates a viewer for message attachments.
* @param parent the parent
* @return a table viewer with the right columns
*/
private TableViewer createAttachmentsViewer( Composite parent ) {
TableViewer viewer = new TableViewer( parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER );
viewer.setContentProvider( ArrayContentProvider.getInstance());
viewer.setLabelProvider( new FilesLabelProvider());
TableLayout layout = new TableLayout();
layout.addColumnData( new ColumnWeightData( 50, 75, true ));
layout.addColumnData( new ColumnWeightData( 50, 75, true ));
viewer.getTable().setLayout( layout );
viewer.getTable().setLayoutData( new GridData( GridData.FILL_BOTH ));
return viewer;
}
}
| lgpl-2.1 |
lhanson/checkstyle | src/tests/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java | 9450 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2010 Oliver Burn
//
// 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.
//
// You should have received a copy of the GNU Lesser 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
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.filters;
import com.google.common.collect.Lists;
import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.Checker;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.TreeWalker;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.checks.FileContentsHolder;
import com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck;
import com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck;
import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import org.junit.Test;
public class SuppressionCommentFilterTest
extends BaseCheckTestSupport
{
private static String[] sAllMessages = {
"13:17: Name 'I' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"16:17: Name 'J' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"19:17: Name 'K' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"22:17: Name 'L' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"23:30: Name 'm' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.",
"27:17: Name 'M2' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"28:30: Name 'n' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.",
"32:17: Name 'P' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"35:17: Name 'Q' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"38:17: Name 'R' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"39:30: Name 's' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.",
"43:17: Name 'T' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"64:23: Catching 'Exception' is not allowed.",
"71:11: Catching 'Exception' is not allowed.",
};
@Test
public void testNone() throws Exception
{
final DefaultConfiguration filterConfig = null;
final String[] suppressed = {
};
verifySuppressed(filterConfig, suppressed);
}
//Supress all checks between default comments
@Test
public void testDefault() throws Exception
{
final DefaultConfiguration filterConfig =
createFilterConfig(SuppressionCommentFilter.class);
final String[] suppressed = {
"16:17: Name 'J' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"43:17: Name 'T' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"64:23: Catching 'Exception' is not allowed.",
"71:11: Catching 'Exception' is not allowed.",
};
verifySuppressed(filterConfig, suppressed);
}
@Test
public void testCheckC() throws Exception
{
final DefaultConfiguration filterConfig =
createFilterConfig(SuppressionCommentFilter.class);
filterConfig.addAttribute("checkC", "false");
final String[] suppressed = {
"43:17: Name 'T' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"64:23: Catching 'Exception' is not allowed.",
"71:11: Catching 'Exception' is not allowed.",
};
verifySuppressed(filterConfig, suppressed);
}
@Test
public void testCheckCPP() throws Exception
{
final DefaultConfiguration filterConfig =
createFilterConfig(SuppressionCommentFilter.class);
filterConfig.addAttribute("checkCPP", "false");
final String[] suppressed = {
"16:17: Name 'J' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
};
verifySuppressed(filterConfig, suppressed);
}
//Supress all checks between CS_OFF and CS_ON
@Test
public void testOffFormat() throws Exception
{
final DefaultConfiguration filterConfig =
createFilterConfig(SuppressionCommentFilter.class);
filterConfig.addAttribute("offCommentFormat", "CS_OFF");
filterConfig.addAttribute("onCommentFormat", "CS_ON");
final String[] suppressed = {
"32:17: Name 'P' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"38:17: Name 'R' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"39:30: Name 's' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.",
"42:17: Name 'T' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
};
verifySuppressed(filterConfig, suppressed);
}
//Test supression of checks of only one type
//Supress only ConstantNameCheck between CS_OFF and CS_ON
@Test
public void testOffFormatCheck() throws Exception
{
final DefaultConfiguration filterConfig =
createFilterConfig(SuppressionCommentFilter.class);
filterConfig.addAttribute("offCommentFormat", "CS_OFF");
filterConfig.addAttribute("onCommentFormat", "CS_ON");
filterConfig.addAttribute("checkFormat", "ConstantNameCheck");
final String[] suppressed = {
"39:30: Name 's' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.",
};
verifySuppressed(filterConfig, suppressed);
}
@Test
public void testExpansion() throws Exception
{
final DefaultConfiguration filterConfig =
createFilterConfig(SuppressionCommentFilter.class);
filterConfig.addAttribute("offCommentFormat", "CSOFF\\: ([\\w\\|]+)");
filterConfig.addAttribute("onCommentFormat", "CSON\\: ([\\w\\|]+)");
filterConfig.addAttribute("checkFormat", "$1");
final String[] suppressed = {
"22:17: Name 'L' must match pattern '^[a-z][a-zA-Z0-9]*$'.",
"23:30: Name 'm' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.",
"28:30: Name 'n' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.",
};
verifySuppressed(filterConfig, suppressed);
}
@Test
public void testMessage() throws Exception
{
final DefaultConfiguration filterConfig =
createFilterConfig(SuppressionCommentFilter.class);
filterConfig.addAttribute("onCommentFormat", "UNUSED ON\\: (\\w+)");
filterConfig.addAttribute("offCommentFormat", "UNUSED OFF\\: (\\w+)");
filterConfig.addAttribute("checkFormat", "Unused");
filterConfig.addAttribute("messageFormat", "^Unused \\w+ '$1'.$");
final String[] suppressed = {
"47:34: Unused parameter 'aInt'.",
};
verifySuppressed(filterConfig, suppressed);
}
public static DefaultConfiguration createFilterConfig(Class<?> aClass)
{
return new DefaultConfiguration(aClass.getName());
}
protected void verifySuppressed(Configuration aFilterConfig,
String[] aSuppressed)
throws Exception
{
verify(createChecker(aFilterConfig),
getPath("filters/InputSuppressionCommentFilter.java"),
removeSuppressed(sAllMessages, aSuppressed));
}
@Override
protected Checker createChecker(Configuration aFilterConfig)
throws CheckstyleException
{
final DefaultConfiguration checkerConfig =
new DefaultConfiguration("configuration");
final DefaultConfiguration checksConfig = createCheckConfig(TreeWalker.class);
checksConfig.addChild(createCheckConfig(FileContentsHolder.class));
checksConfig.addChild(createCheckConfig(MemberNameCheck.class));
checksConfig.addChild(createCheckConfig(ConstantNameCheck.class));
checksConfig.addChild(createCheckConfig(IllegalCatchCheck.class));
checkerConfig.addChild(checksConfig);
if (aFilterConfig != null) {
checkerConfig.addChild(aFilterConfig);
}
final Checker checker = new Checker();
final Locale locale = Locale.ENGLISH;
checker.setLocaleCountry(locale.getCountry());
checker.setLocaleLanguage(locale.getLanguage());
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
checker.addListener(new BriefLogger(mStream));
return checker;
}
private String[] removeSuppressed(String[] aFrom, String[] aRemove)
{
final Collection<String> coll =
Lists.newArrayList(Arrays.asList(aFrom));
coll.removeAll(Arrays.asList(aRemove));
return coll.toArray(new String[coll.size()]);
}
}
| lgpl-2.1 |