repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
specify/specify6 | src/edu/ku/brc/specify/tools/export/CmdAppBase.java | 13017 | /**
*
*/
package edu.ku.brc.specify.tools.export;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Vector;
import edu.ku.brc.af.auth.SecurityMgr;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Element;
import edu.ku.brc.af.auth.JaasContext;
import edu.ku.brc.af.auth.UserAndMasterPasswordMgr;
import edu.ku.brc.af.core.AppContextMgr;
import edu.ku.brc.af.prefs.AppPreferences;
import edu.ku.brc.dbsupport.DatabaseDriverInfo;
import edu.ku.brc.helpers.XMLHelper;
import edu.ku.brc.specify.Specify;
import edu.ku.brc.specify.config.SpecifyAppContextMgr;
import edu.ku.brc.specify.config.SpecifyAppPrefs;
import edu.ku.brc.specify.conversion.BasicSQLUtils;
import edu.ku.brc.specify.datamodel.Discipline;
import edu.ku.brc.specify.tools.ireportspecify.MainFrameSpecify;
import edu.ku.brc.ui.UIHelper;
import edu.ku.brc.ui.UIRegistry;
import edu.ku.brc.util.Pair;
/**
* @author timo
*
*/
public class CmdAppBase {
protected static final String SCHEMA_VERSION_FILENAME = "schema_version.xml";
private static String[] argkeys = {"-u", "-p", "-d", "-m", "-l", "-h", "-o", "-w", "-U", "-P"};
protected List<Pair<String, String>> argList;
protected String userName;
protected String password;
protected String dbName;
protected String outputName;
protected String hostName;
protected String workingPath = ".";
protected Pair<String, String> master;
protected FileWriter out;
boolean success = false;
protected Vector<DatabaseDriverInfo> dbDrivers = new Vector<DatabaseDriverInfo>();
protected int dbDriverIdx;
protected String collectionName;
protected JaasContext jaasContext;
/**
* @param argkeys
*/
public CmdAppBase(String[] akeys) {
String[] as = new String[argkeys.length + akeys.length];
for (int ak=0; ak < argkeys.length; ak++) {
as[ak] = argkeys[ak];
}
for (int ak=0; ak < akeys.length; ak++) {
as[ak + argkeys.length] = akeys[ak];
}
argList = buildArgList(as);
dbDriverIdx = 0;
hostName = "localhost";
}
/**
* @param keys
* @return
*/
protected List<Pair<String, String>> buildArgList(String[] keys) {
List<Pair<String, String>> result = new ArrayList<Pair<String,String>>();
for (String key : keys) {
result.add(new Pair<String, String>(key, null));
}
return result;
}
/**
* @return
*/
public String getDBSchemaVersionFromXML()
{
String dbVersion = null;
Element root;
try
{
root = XMLHelper.readFileToDOM4J(new FileInputStream(XMLHelper.getConfigDirPath(SCHEMA_VERSION_FILENAME)));//$NON-NLS-1$
if (root != null)
{
dbVersion = ((Element)root).getTextTrim();
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return dbVersion;
}
/**
* @return
*/
protected boolean checkVersion() {
String schemaVersion = getDBSchemaVersionFromXML();
String appVersion = UIRegistry.getAppVersion();
String schemaVersionFromDb = BasicSQLUtils.querySingleObj("select SchemaVersion from spversion");
String appVersionFromDb = BasicSQLUtils.querySingleObj("select AppVersion from spversion");
return (schemaVersion.equals(schemaVersionFromDb) && appVersion.equals(appVersionFromDb));
}
/**
* @param args
*/
protected void readArgs(String[] args) {
for (Pair<String, String> argPair : argList) {
argPair.setSecond(readArg(argPair.getFirst(), args));
}
}
/**
* @param argKey
* @param args
* @return
*/
protected String readArg(String argKey, String[] args) {
for (int k = 0; k < args.length - 1; k+=2) {
if (args[k].equals(argKey)) {
return args[k+1];
}
}
return null;
}
/**
* @return
*/
protected String checkArgs() {
String result = "";
for (Pair<String, String> arg : argList) {
String err = checkArg(arg);
if (StringUtils.isNotBlank(err)) {
if (result.length() > 0) {
result += "; ";
}
result += err;
}
}
return result;
}
/**
* @param arg
* @return "" if arg checks out, else err msg
*/
protected String checkArg(Pair<String, String> arg) {
return "";
}
/**
*
*/
protected void adjustLocaleFromPrefs()
{
String language = AppPreferences.getLocalPrefs().get("locale.lang", null); //$NON-NLS-1$
if (language != null)
{
String country = AppPreferences.getLocalPrefs().get("locale.country", null); //$NON-NLS-1$
String variant = AppPreferences.getLocalPrefs().get("locale.var", null); //$NON-NLS-1$
Locale prefLocale = new Locale(language, country, variant);
Locale.setDefault(prefLocale);
UIRegistry.setResourceLocale(prefLocale);
}
try
{
ResourceBundle.getBundle("resources", Locale.getDefault()); //$NON-NLS-1$
} catch (MissingResourceException ex)
{
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(MainFrameSpecify.class, ex);
Locale.setDefault(Locale.ENGLISH);
UIRegistry.setResourceLocale(Locale.ENGLISH);
}
}
/**
* @throws Exception
*/
protected void setupPrefs() throws Exception {
//Apparently this is correct...
System.setProperty(SecurityMgr.factoryName, "edu.ku.brc.af.auth.specify.SpecifySecurityMgr");
UIRegistry.setAppName("Specify"); //$NON-NLS-1$
UIRegistry.setDefaultWorkingPath(this.workingPath);
final AppPreferences localPrefs = AppPreferences.getLocalPrefs();
localPrefs.setDirPath(UIRegistry.getAppDataDir());
adjustLocaleFromPrefs();
final String iRepPrefDir = localPrefs.getDirPath();
int mark = iRepPrefDir.lastIndexOf(UIRegistry.getAppName(), iRepPrefDir.length());
final String SpPrefDir = iRepPrefDir.substring(0, mark) + "Specify";
AppPreferences.getLocalPrefs().flush();
AppPreferences.getLocalPrefs().setDirPath(SpPrefDir);
AppPreferences.getLocalPrefs().setProperties(null);
}
/**
* @return
* @throws Exception
*/
protected boolean hasMasterKey() throws Exception {
UserAndMasterPasswordMgr.getInstance().set(userName, password, dbName);
return UserAndMasterPasswordMgr.getInstance().hasMasterUsernameAndPassword();
}
protected boolean needsMasterKey() {
return !(master != null && master.getFirst() != null && master.getSecond()!= null);
}
/**
* @return
* @throws Exception
*/
protected boolean getMaster() throws Exception {
UserAndMasterPasswordMgr.getInstance().set(userName, password, dbName);
if (!needsMasterKey()) {
UserAndMasterPasswordMgr.getInstance().setUserNamePasswordForDB(master.first, master.second);
return true;
}
Pair<String, String> userpw = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB();
if (userpw != null) {
if (StringUtils.isNotBlank(userpw.getFirst()) && StringUtils.isNotBlank(userpw.getSecond())) {
if (master == null) {
master = new Pair<String, String>(null, null);
}
master.setFirst(userpw.getFirst());
master.setSecond(userpw.getSecond());
return true;
}
}
return false;
}
/**
* @return
*/
protected boolean goodUser() {
String userType = BasicSQLUtils.querySingleObj("select UserType from specifyuser where `name` = '" + userName + "'");
return "manager".equalsIgnoreCase(userType);
}
/**
* @param argKey
* @return
*/
protected String getArg(String argKey) {
for (Pair<String, String> arg : argList) {
if (arg.getFirst().equals(argKey)) {
return arg.getSecond();
}
}
return null;
}
/**
* @param success
*/
protected void setSuccess(boolean success) {
this.success = success;
}
public boolean isSuccess() {
return success;
}
protected DatabaseDriverInfo buildDefaultDriverInfo() {
DatabaseDriverInfo result = new DatabaseDriverInfo("MySQL", "com.mysql.jdbc.Driver", "org.hibernate.dialect.MySQL5InnoDBDialect", false, "3306");
result.addFormat(DatabaseDriverInfo.ConnectionType.Opensys, "jdbc:mysql://SERVER:PORT/");
result.addFormat(DatabaseDriverInfo.ConnectionType.Open, "jdbc:mysql://SERVER:PORT/DATABASE?characterEncoding=UTF-8&autoReconnect=true");
return result;
}
/**
*
*/
public void loadDrivers() {
dbDrivers = DatabaseDriverInfo.getDriversList();
}
/**
* @return
*/
protected String getConnectionStr() {
return dbDrivers.get(dbDriverIdx).getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
hostName, dbName);
}
/**
* @param fileName
* @throws Exception
*/
protected void openLog(String fileName) throws Exception {
FileWriter testOut = new FileWriter(new File(fileName), true);
out = testOut;
}
/**
* @return
*/
protected String getTimestamp() {
return new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
}
/**
* @return
*/
protected String getLogInitText(String[] args) {
String argStr = "";
boolean isPw = false;
for (String arg : args) {
argStr += " " + (isPw ? "********" : arg);
if (isPw) {
isPw = false;
} else if ("-p".equals(arg)) {
isPw = true;
}
}
return String.format(UIRegistry.getResourceString("ExportCmdLine.LogInitTxt"), argStr);
}
/**
* @return
*/
protected String getLogExitText() {
return String.format(UIRegistry.getResourceString("ExportCmdLine.LogExitTxt"), (success ? "" : "UN-") + "successfully.");
}
/**
* @throws IOException
*/
protected void initLog(String[] args) throws IOException {
out(getLogInitText(args));
}
/**
* @throws IOException
*/
protected void flushLog() throws IOException {
if (out != null) {
out.flush();
}
}
/**
* @throws IOException
*/
protected void exitLog() throws IOException {
out(getLogExitText());
if (out != null) {
out.close();
}
}
/**
* @param line
* @throws IOException
*/
protected void out(String line) throws IOException {
if (out != null) {
out.append(getTimestamp() + ": " + line + "\n");
out.flush();
} else {
System.out.println(getTimestamp() + ": " + line);
}
}
/**
* @return
*/
protected boolean login() {
boolean result = UIHelper.tryLogin(dbDrivers.get(dbDriverIdx).getDriverClassName(),
dbDrivers.get(dbDriverIdx).getDialectClassName(),
dbName,
getConnectionStr(),
master.getFirst(),
master.getSecond());
if (result) {
this.jaasContext = new JaasContext();
jaasLogin();
}
return result;
}
/**
* @return true if ContextManager initializes successfully for collection.
*/
protected boolean setContext() {
Specify.setUpSystemProperties();
System.setProperty(AppContextMgr.factoryName, "edu.ku.brc.specify.tools.export.SpecifyExpCmdAppContextMgr"); // Needed by AppContextMgr //$NON-NLS-1$
AppPreferences.shutdownRemotePrefs();
AppContextMgr.CONTEXT_STATUS status = ((SpecifyAppContextMgr)AppContextMgr.getInstance()).
setContext(dbName, userName, false, false, true, collectionName, false);
// AppContextMgr.getInstance().
SpecifyAppPrefs.initialPrefs();
if (status == AppContextMgr.CONTEXT_STATUS.OK) {
if (AppContextMgr.getInstance().getClassObject(Discipline.class) == null) {
return false;
}
} else if (status == AppContextMgr.CONTEXT_STATUS.Error) {
return false;
}
// ...end specify.restartApp snatch
return true;
}
/**
* @return
*/
protected boolean retrieveCollectionName() {
return false;
}
/**
* @return
*/
public boolean jaasLogin()
{
if (jaasContext != null)
{
return jaasContext.jaasLogin(
userName,
password,
getConnectionStr(),
dbDrivers.get(dbDriverIdx).getDriverClassName(),
master.first,
master.second
);
}
return false;
}
/**
* @throws Exception
*/
protected void setMembers() throws Exception {
userName = getArg("-u");
password = getArg("-p");
if (password == null) password = "";
dbName = getArg("-d");
outputName = getArg("-o");
workingPath = getArg("-w");
String logFile = getArg("-l");
if (logFile != null) {
openLog(logFile);
}
String host = getArg("-h");
if (host != null) {
hostName = host;
}
master = new Pair<>(getArg("-U"), getArg("-P"));
}
}
| gpl-2.0 |
fin-nick/fj | util/jlft2/src/jimmLangFileTool/LGFileSubset.java | 2216 | /*******************************************************************************
JimmLangFileTool - Simple Java GUI for editing/comparing Jimm language files
Copyright (C) 2005 Jimm Project
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
********************************************************************************
File: src/jimmLangFileTool/LGFileSubset.java
Version: ###VERSION### Date: ###DATE###
Author(s): Andreas Rossbacher
*******************************************************************************/
package jimmLangFileTool;
import java.util.Vector;
public class LGFileSubset extends Vector
{
private static final long serialVersionUID = 1L;
String id;
boolean removed;
public LGFileSubset(String _id)
{
super();
id = _id;
removed = false;
}
public LGFileSubset()
{
super();
}
public LGFileSubset getClone()
{
return this;
}
public LGString containsKey(String key)
{
for(int i=0;i<super.size();i++)
{
if(super.get(i) instanceof LGString)
if(((LGString)super.get(i)).getKey().equals(key))
return (LGString) super.get(i);
}
return null;
}
/**
* @return Returns the id.
*/
public String getId()
{
return id;
}
public String toString()
{
return id;
}
/**
* @param id The id to set.
*/
public void setId(String id)
{
this.id = id;
}
/**
* @return Returns the removed.
*/
public boolean isRemoved()
{
return removed;
}
/**
* @param removed The removed to set.
*/
public void setRemoved(boolean removed)
{
this.removed = removed;
}
}
| gpl-2.0 |
xstory61/server | src/server/expeditions/MapleExpeditionType.java | 2190 | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.expeditions;
/**
*
* @author SharpAceX(Alan)
*/
public enum MapleExpeditionType {
BALROG_EASY(3, 30, 50, 255, 5),
BALROG_NORMAL(6, 30, 50, 255, 5),
SCARGA(6, 30, 100, 255, 5),
SHOWA(3, 30, 100, 255, 5),
ZAKUM(6, 30, 50, 255, 5),
HORNTAIL(6, 30, 100, 255, 5),
CHAOS_ZAKUM(6, 30, 120, 255, 5),
CHAOS_HORNTAIL(6, 30, 120, 255, 5),
PINKBEAN(6, 30, 120, 255, 5),
CWKPQ(6, 30, 100, 255, 5);
private int minSize;
private int maxSize;
private int minLevel;
private int maxLevel;
private int registrationTime;
private MapleExpeditionType(int minSize, int maxSize, int minLevel, int maxLevel, int minutes) {
this.minSize = minSize;
this.maxSize = maxSize;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.registrationTime = minutes;
}
public int getMinSize() {
return minSize;
}
public int getMaxSize() {
return maxSize;
}
public int getMinLevel() {
return minLevel;
}
public int getMaxLevel() {
return maxLevel;
}
public int getRegistrationTime(){
return registrationTime;
}
}
| gpl-2.0 |
huangyaoming/wxtest | src/com/byhealth/wechat/mysdk/process/in/executor/InWechatTextMsgExecutor.java | 1776 | package com.byhealth.wechat.mysdk.process.in.executor;
import com.byhealth.wechat.base.admin.entity.RespMsgActionEntity;
import com.byhealth.wechat.config.MsgTemplateConstants;
import com.byhealth.wechat.mysdk.constants.WechatReqMsgtypeConstants;
import com.byhealth.wechat.mysdk.context.WechatContext;
import com.byhealth.wechat.mysdk.process.ext.TextExtService;
import com.byhealth.wechat.mysdk.tools.NameTool;
import com.byhealth.wechat.mysdk.beans.req.ReqTextMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 文本消息处理器
* @author fengjx xd-fjx@qq.com
* @date 2014年9月11日
*/
public class InWechatTextMsgExecutor extends InServiceExecutor {
@Autowired
private TextExtService textExtService;
@Override
public String execute() throws Exception {
ReqTextMessage textMessage = new ReqTextMessage(WechatContext.getWechatPostMap());
logger.info("进入文本消息处理器fromUserName="+textMessage.getFromUserName());
RespMsgActionEntity actionEntity = msgActionService.loadMsgAction(null,WechatReqMsgtypeConstants.REQ_MSG_TYPE_TEXT, null,textMessage.getContent(), WechatContext.getPublicAccount().getSysUser());
//没有找到匹配规则
if(null == actionEntity){
String res = textExtService.execute();
if(StringUtils.isNotBlank(res)){ //如果有数据则直接返回
return res;
}
//返回默认回复消息
actionEntity = msgActionService.loadMsgAction(MsgTemplateConstants.WECHAT_DEFAULT_MSG, null, null, null, WechatContext.getPublicAccount().getSysUser());
}
return doAction(actionEntity);
}
@Override
public String getExecutorName() {
return NameTool.buildInServiceName(WechatReqMsgtypeConstants.REQ_MSG_TYPE_TEXT, null);
}
}
| gpl-2.0 |
uw-loci/visbio | src/main/java/loci/visbio/VisBio.java | 4536 | /*
* #%L
* VisBio application for visualization of multidimensional biological
* image data.
* %%
* Copyright (C) 2002 - 2014 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.visbio;
import java.awt.Color;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import loci.visbio.util.InstanceServer;
import loci.visbio.util.SplashScreen;
/**
* VisBio is a biological visualization tool designed for easy visualization and
* analysis of multidimensional image data. This class is the main gateway into
* the application. It creates and displays a VisBioFrame via reflection, so
* that the splash screen appears as quickly as possible, before the class
* loader gets too far along.
*/
public final class VisBio extends Thread {
// -- Constants --
/** Application title. */
public static final String TITLE = "VisBio";
/** Application version (of the form "###"). */
private static final String V = "@visbio.version@";
/** Application version (of the form "#.##"). */
public static final String VERSION = V.equals("@visbio" + ".version@")
? "(internal build)" : (V.substring(0, 1) + "." + V.substring(1));
/** Application authors. */
public static final String AUTHOR = "Curtis Rueden and Abraham Sorber, LOCI";
/** Application build date. */
public static final String DATE = "@date@";
/** Port to use for communicating between application instances. */
public static final int INSTANCE_PORT = 0xabcd;
// -- Constructor --
/** Ensure this class can't be externally instantiated. */
private VisBio() {}
// -- VisBio API methods --
/** Launches the VisBio GUI with no arguments, in a separate thread. */
public static void startProgram() {
new VisBio().start();
}
/** Launches VisBio, returning the newly constructed VisBioFrame object. */
public static Object launch(final String[] args)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException, NoSuchMethodException
{
// check whether VisBio is already running
boolean isRunning = true;
try {
InstanceServer.sendArguments(args, INSTANCE_PORT);
}
catch (final IOException exc) {
isRunning = false;
}
if (isRunning) return null;
// display splash screen
final String[] msg =
{ TITLE + " " + VERSION + " - " + AUTHOR, "VisBio is starting up..." };
final SplashScreen ss =
new SplashScreen(VisBio.class.getResource("visbio-logo.png"), msg,
new Color(255, 255, 220), new Color(255, 50, 50));
ss.setVisible(true);
// toggle window decoration mode via reflection
final boolean b =
"true".equals(System.getProperty("visbio.decorateWindows"));
final Class<?> jf = Class.forName("javax.swing.JFrame");
final Method m =
jf.getMethod("setDefaultLookAndFeelDecorated",
new Class<?>[] { boolean.class });
m.invoke(null, new Object[] { new Boolean(b) });
// construct VisBio interface via reflection
final Class<?> vb = Class.forName("loci.visbio.VisBioFrame");
final Constructor<?> con =
vb.getConstructor(new Class[] { ss.getClass(), String[].class });
return con.newInstance(new Object[] { ss, args });
}
// -- Thread API methods --
/** Launches the VisBio GUI with no arguments. */
@Override
public void run() {
try {
launch(new String[0]);
}
catch (final Exception exc) {
exc.printStackTrace();
}
}
// -- Main --
/** Launches the VisBio GUI. */
public static void main(final String[] args) throws ClassNotFoundException,
IllegalAccessException, InstantiationException, InvocationTargetException,
NoSuchMethodException
{
System.setProperty("apple.laf.useScreenMenuBar", "true");
final Object o = launch(args);
if (o == null) System.out.println("VisBio is already running.");
}
}
| gpl-2.0 |
arthurmelo88/palmetalADP | palmetal_to_lbrk/base/src/org/adempierelbr/model/MLBRTaxConfigProduct.java | 2274 | /******************************************************************************
* Copyright (C) 2011 Kenos Assessoria e Consultoria de Sistemas Ltda *
* Copyright (C) 2011 Ricardo Santana *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License 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 General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*****************************************************************************/
package org.adempierelbr.model;
import java.sql.ResultSet;
import java.util.Properties;
/**
* Model for Tax Configuration Product
*
* @author Ricardo Santana (Kenos, www.kenos.com.br)
* @version $Id: MLBRTaxConfigProduct.java, v2.0 2011/10/13 2:16:18 PM, ralexsander Exp $
*/
public class MLBRTaxConfigProduct extends X_LBR_TaxConfig_Product
{
/**
* Serial Version
*/
private static final long serialVersionUID = 1L;
/**************************************************************************
* Default Constructor
* @param Properties ctx
* @param int ID (0 create new)
* @param String trx
*/
public MLBRTaxConfigProduct (Properties ctx, int ID, String trxName)
{
super (ctx, ID, trxName);
} // MLBRTaxConfigProduct
/**
* Load Constructor
* @param ctx context
* @param rs result set record
* @param trxName transaction
*/
public MLBRTaxConfigProduct (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MLBRTaxConfigProduct
/**
* Before Save
*/
protected boolean beforeSave (boolean newRecord)
{
return super.beforeSave(newRecord);
} // beforeSave
} // MLBRTaxConfigProduct | gpl-2.0 |
mbabic/HeadphoneController | src/ca/mbabic/headphonecontroller/statemachine/HCStateMachine.java | 4900 | /*
* TODO: license
*/
package ca.mbabic.headphonecontroller.statemachine;
import java.lang.Thread.State;
import java.util.concurrent.Semaphore;
import android.util.Log;
import ca.mbabic.headphonecontroller.services.MediaButtonListenerService;
/**
* State machine keeping track of the state of the button presses.
* Implementation of the State Pattern. See:
* http://sourcemaking.com/design_patterns/state
*
* @author Marko Babic
*/
public class HCStateMachine {
/**
* Reference to MediaButtonListenerService such that after command execution
* we can re-register ourselves as exclusive media button player listener.
*/
private static MediaButtonListenerService listenerService;
/**
* Class specific logging tag.
*/
private static final String TAG = ".statemachine.HCStateMachine";
/**
* Interval to wait between button presses.
*/
// TODO: make configurable
private static final long BTN_PRESS_INTERVAL = 400;
/**
* Instance of HCStateMachine available to the application.
*/
private static volatile HCStateMachine instance = null;
/**
* Reference to the state in which the machine is currently in.
*/
private static HCState currentState;
/**
* The starting state of the machine.
*/
private static HCState startState;
/**
* Time left until count down thread will execute the current state's
* command.
*/
private static long timeToExecution;
/**
* The amount of time the count down thread will sleep between acquiring the
* semaphore and updating timeToExecution.
*/
private static final long SLEEP_INTERVAL = 100;
/**
* Semaphore used to lock access to shared variable timeToExecution.
*/
private static Semaphore countDownSemaphore = new Semaphore(1);
/**
* Thread in which the count down to execution monitoring functionality is
* implemented.
*/
private Thread countDownThread;
static Runnable countDownRunnable = new Runnable() {
public void run() {
timeToExecution = BTN_PRESS_INTERVAL;
while (timeToExecution > 0) {
try {
Thread.sleep(SLEEP_INTERVAL);
countDownSemaphore.acquire();
timeToExecution -= SLEEP_INTERVAL;
} catch (InterruptedException ie) {
Log.e(TAG, "Coundown thread interrupted!");
return;
} finally {
countDownSemaphore.release();
}
}
// Count down expired, execute current state's command.
// TODO: this should be synchronized ... and we should take one
// last check here to make sure timeToExecution <= 0 and if not
// start looping again and not execute anything ...
currentState.executeCommand();
listenerService.registerAsMediaButtonListener();
currentState = startState;
}
};
/**
* Private constructor. Get global application reference to state machine
* via getInstance().
*/
private HCStateMachine() {
startState = new InactiveState();
currentState = startState;
}
public void setService(MediaButtonListenerService mbls) {
listenerService = mbls;
}
/**
* @return Singleton instance of HCStateMachine.
*/
public static HCStateMachine getInstance() {
if (instance == null) {
synchronized (HCStateMachine.class) {
// Double check instance locking
if (instance == null) {
instance = new HCStateMachine();
}
}
}
return instance;
}
/**
* Indicate to state machine that the media button has been pressed on the
* headphones. TODO: keep track of long clicks... should not transition to
* next state at end of such a command.
*/
public void keyUp() {
makeStateTransition();
}
/**
* Transition to next state as appropriate given currentState.
*/
private void makeStateTransition() {
HCState nextState = currentState.getNextState();
if (currentState.isTerminal()) {
stopCountDownToExecution();
currentState.executeCommand();
currentState = startState;
} else {
currentState = nextState;
startCountDownToExecution();
}
}
/**
* Call to start or reset a count down to execution of the current state's
* command.
*/
private void startCountDownToExecution() {
try {
countDownSemaphore.acquire();
if (countDownThread == null
|| countDownThread.getState() == State.TERMINATED) {
countDownThread = new Thread(countDownRunnable);
countDownThread.start();
} else {
timeToExecution = BTN_PRESS_INTERVAL;
}
} catch (Exception e) {
Log.e(TAG, e.toString());
} finally {
countDownSemaphore.release();
}
}
/**
* Called to cancel count down to execution thread.
*/
private void stopCountDownToExecution() {
countDownThread.interrupt();
try {
countDownThread.join();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
| gpl-2.0 |
mcberg2016/graal-core | graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/stubs/NewArrayStub.java | 7960 | /*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.hotspot.stubs;
import static com.oracle.graal.hotspot.GraalHotSpotVMConfig.INJECTED_VMCONFIG;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.arrayPrototypeMarkWord;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.getAndClearObjectResult;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.inlineContiguousAllocationSupported;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperElementTypeMask;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperElementTypeShift;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperHeaderSizeMask;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperHeaderSizeShift;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperLog2ElementSizeMask;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.layoutHelperLog2ElementSizeShift;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.loadKlassLayoutHelperIntrinsic;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.registerAsWord;
import static com.oracle.graal.hotspot.replacements.HotSpotReplacementsUtil.wordSize;
import static com.oracle.graal.hotspot.replacements.NewObjectSnippets.MAX_ARRAY_FAST_PATH_ALLOCATION_LENGTH;
import static com.oracle.graal.hotspot.replacements.NewObjectSnippets.formatArray;
import static com.oracle.graal.hotspot.stubs.NewInstanceStub.refillAllocate;
import static com.oracle.graal.hotspot.stubs.StubUtil.handlePendingException;
import static com.oracle.graal.hotspot.stubs.StubUtil.newDescriptor;
import static com.oracle.graal.hotspot.stubs.StubUtil.printf;
import static com.oracle.graal.hotspot.stubs.StubUtil.verifyObject;
import static jdk.vm.ci.hotspot.HotSpotMetaAccessProvider.computeArrayAllocationSize;
import com.oracle.graal.api.replacements.Fold;
import com.oracle.graal.api.replacements.Snippet;
import com.oracle.graal.api.replacements.Snippet.ConstantParameter;
import com.oracle.graal.compiler.common.spi.ForeignCallDescriptor;
import com.oracle.graal.graph.Node.ConstantNodeParameter;
import com.oracle.graal.graph.Node.NodeIntrinsic;
import com.oracle.graal.hotspot.HotSpotForeignCallLinkage;
import com.oracle.graal.hotspot.meta.HotSpotProviders;
import com.oracle.graal.hotspot.nodes.StubForeignCallNode;
import com.oracle.graal.hotspot.nodes.type.KlassPointerStamp;
import com.oracle.graal.hotspot.replacements.NewObjectSnippets;
import com.oracle.graal.hotspot.word.KlassPointer;
import com.oracle.graal.nodes.ConstantNode;
import com.oracle.graal.word.Word;
import jdk.vm.ci.code.Register;
import jdk.vm.ci.hotspot.HotSpotResolvedObjectType;
/**
* Stub implementing the fast path for TLAB refill during instance class allocation. This stub is
* called from the {@linkplain NewObjectSnippets inline} allocation code when TLAB allocation fails.
* If this stub fails to refill the TLAB or allocate the object, it calls out to the HotSpot C++
* runtime to complete the allocation.
*/
public class NewArrayStub extends SnippetStub {
public NewArrayStub(HotSpotProviders providers, HotSpotForeignCallLinkage linkage) {
super("newArray", providers, linkage);
}
@Override
protected Object[] makeConstArgs() {
HotSpotResolvedObjectType intArrayType = (HotSpotResolvedObjectType) providers.getMetaAccess().lookupJavaType(int[].class);
int count = method.getSignature().getParameterCount(false);
Object[] args = new Object[count];
assert checkConstArg(3, "intArrayHub");
assert checkConstArg(4, "threadRegister");
args[3] = ConstantNode.forConstant(KlassPointerStamp.klassNonNull(), intArrayType.klass(), null);
args[4] = providers.getRegisters().getThreadRegister();
return args;
}
@Fold
static boolean logging() {
return StubOptions.TraceNewArrayStub.getValue();
}
/**
* Re-attempts allocation after an initial TLAB allocation failed or was skipped (e.g., due to
* -XX:-UseTLAB).
*
* @param hub the hub of the object to be allocated
* @param length the length of the array
* @param fillContents Should the array be filled with zeroes?
* @param intArrayHub the hub for {@code int[].class}
*/
@Snippet
private static Object newArray(KlassPointer hub, int length, boolean fillContents, @ConstantParameter KlassPointer intArrayHub, @ConstantParameter Register threadRegister) {
int layoutHelper = loadKlassLayoutHelperIntrinsic(hub);
int log2ElementSize = (layoutHelper >> layoutHelperLog2ElementSizeShift(INJECTED_VMCONFIG)) & layoutHelperLog2ElementSizeMask(INJECTED_VMCONFIG);
int headerSize = (layoutHelper >> layoutHelperHeaderSizeShift(INJECTED_VMCONFIG)) & layoutHelperHeaderSizeMask(INJECTED_VMCONFIG);
int elementKind = (layoutHelper >> layoutHelperElementTypeShift(INJECTED_VMCONFIG)) & layoutHelperElementTypeMask(INJECTED_VMCONFIG);
int sizeInBytes = computeArrayAllocationSize(length, wordSize(), headerSize, log2ElementSize);
if (logging()) {
printf("newArray: element kind %d\n", elementKind);
printf("newArray: array length %d\n", length);
printf("newArray: array size %d\n", sizeInBytes);
printf("newArray: hub=%p\n", hub.asWord().rawValue());
}
// check that array length is small enough for fast path.
Word thread = registerAsWord(threadRegister);
if (inlineContiguousAllocationSupported(INJECTED_VMCONFIG) && length >= 0 && length <= MAX_ARRAY_FAST_PATH_ALLOCATION_LENGTH) {
Word memory = refillAllocate(thread, intArrayHub, sizeInBytes, logging());
if (memory.notEqual(0)) {
if (logging()) {
printf("newArray: allocated new array at %p\n", memory.rawValue());
}
return verifyObject(
formatArray(hub, sizeInBytes, length, headerSize, memory, Word.unsigned(arrayPrototypeMarkWord(INJECTED_VMCONFIG)), fillContents, false, false));
}
}
if (logging()) {
printf("newArray: calling new_array_c\n");
}
newArrayC(NEW_ARRAY_C, thread, hub, length);
handlePendingException(thread, true);
return verifyObject(getAndClearObjectResult(thread));
}
public static final ForeignCallDescriptor NEW_ARRAY_C = newDescriptor(NewArrayStub.class, "newArrayC", void.class, Word.class, KlassPointer.class, int.class);
@NodeIntrinsic(StubForeignCallNode.class)
public static native void newArrayC(@ConstantNodeParameter ForeignCallDescriptor newArrayC, Word thread, KlassPointer hub, int length);
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest12371.java | 3211 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest12371")
public class BenchmarkTest12371 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] values = request.getParameterValues("foo");
String param;
if (values.length != 0)
param = request.getParameterValues("foo")[0];
else param = null;
String bar = new Test().doSomething(param);
java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir + bar));
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
// Chain a bunch of propagators in sequence
String a13109 = param; //assign
StringBuilder b13109 = new StringBuilder(a13109); // stick in stringbuilder
b13109.append(" SafeStuff"); // append some safe content
b13109.replace(b13109.length()-"Chars".length(),b13109.length(),"Chars"); //replace some of the end content
java.util.HashMap<String,Object> map13109 = new java.util.HashMap<String,Object>();
map13109.put("key13109", b13109.toString()); // put in a collection
String c13109 = (String)map13109.get("key13109"); // get it back out
String d13109 = c13109.substring(0,c13109.length()-1); // extract most of it
String e13109 = new String( new sun.misc.BASE64Decoder().decodeBuffer(
new sun.misc.BASE64Encoder().encode( d13109.getBytes() ) )); // B64 encode and decode it
String f13109 = e13109.split(" ")[0]; // split it on a space
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String g13109 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe'
String bar = thing.doSomething(g13109); // reflection
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
guodongxiaren/JFC | src/layout/SignUpPanel.java | 1277 | package layout;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import swing.Sample;
@SuppressWarnings("serial")
public class SignUpPanel extends JPanel{
private int count;
private JLabel label[];
private JComponent comp[];
private JButton jbok;
public SignUpPanel(String[] fields) {
count = fields.length;
jbok = new JButton("确定");
JPanel p1 = new JPanel(new GridLayout(count,2,5,5));
JPanel p2 = new JPanel();
setLayout(new BorderLayout());
add(p1,BorderLayout.CENTER);
add(p2,BorderLayout.SOUTH);
p2.add(jbok);
label = new JLabel[count];
comp = new JTextField[count];
for(int i=0;i<count;i++){
label[i] = new JLabel(fields[i]);
comp[i] = new JTextField();
p1.add(label[i]);
p1.add(comp[i]);
}
}
public static void main(String[] args) {
JFrame testFrame = new Sample();
String []fields = {"用户名","密码","邮箱","地址"};
testFrame.add(new SignUpPanel(fields));
testFrame.setSize(300, 200);
}
}
| gpl-2.0 |
baijian/root-tools | RootTools2/src/main/java/com/rarnu/tools/neo/activity/MainActivity.java | 3185 | package com.rarnu.tools.neo.activity;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import com.rarnu.tools.neo.R;
import com.rarnu.tools.neo.api.NativeAPI;
import com.rarnu.tools.neo.base.BaseActivity;
import com.rarnu.tools.neo.fragment.MainFragment;
import com.rarnu.tools.neo.utils.UIUtils;
import com.rarnu.tools.neo.xposed.XpStatus;
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
UIUtils.initDisplayMetrics(this, getWindowManager(), false);
super.onCreate(savedInstanceState);
NativeAPI.isRejected = !NativeAPI.mount();
if (!XpStatus.isEnable()) {
new AlertDialog.Builder(this)
.setTitle(R.string.alert_hint)
.setMessage(R.string.alert_xposed)
.setCancelable(false)
.setPositiveButton(R.string.alert_ok, null)
.show();
}
if (Build.VERSION.SDK_INT >= 24) {
new AlertDialog.Builder(this)
.setTitle(R.string.alert_hint)
.setMessage(R.string.alert_androidn_pending)
.setPositiveButton(R.string.alert_ok, null)
.show();
} else {
if (NativeAPI.isRejected) {
new AlertDialog.Builder(this)
.setTitle(R.string.alert_hint)
.setMessage(R.string.alert_root)
.setCancelable(false)
.setPositiveButton(R.string.alert_ok, null)
.show();
}
}
requirePermission();
}
@Override
public int getIcon() {
return R.drawable.ic_launcher;
}
@Override
public Fragment replaceFragment() {
return new MainFragment();
}
@Override
public int customTheme() {
return 0;
}
@Override
public boolean getActionBarCanBack() {
return false;
}
private void requirePermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
XpStatus.canWriteSdcard = true;
}
} else {
XpStatus.canWriteSdcard = true;
}
}
// No override here for compact with 5.0
// @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
XpStatus.canWriteSdcard = grantResults[i] == PackageManager.PERMISSION_GRANTED;
break;
}
}
}
}
| gpl-2.0 |
zhanglei920802/ypgl | src/xzd/mobile/android/common/ImageUtils.java | 18019 | package xzd.mobile.android.common;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.DisplayMetrics;
import android.view.View;
public class ImageUtils {
public final static String SDCARD_MNT = "/mnt/sdcard";
public final static String SDCARD = "/sdcard";
/** 请求相册 */
public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
/** 请求相机 */
public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
/** 请求裁剪 */
public static final int REQUEST_CODE_GETIMAGE_BYCROP = 2;
private static ImageUtils mImageUtils = null;
public static ImageUtils getInstance() {
if (mImageUtils == null) {
mImageUtils = new ImageUtils();
}
return mImageUtils;
}
public static void releaseMem() {
if (mImageUtils != null) {
mImageUtils = null;
}
}
public Bitmap getBitmapFromView(View view) {
view.destroyDrawingCache();
view.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache(true);
return bitmap;
}
/**
* 写图片文�? 在Android系统中,文件保存�?/data/data/PACKAGE_NAME/files 目录�?
*
* @throws IOException
*/
public void saveImage(Context context, String fileName, Bitmap bitmap)
throws IOException {
saveImage(context, fileName, bitmap, 100);
}
public void saveImage(Context context, String fileName, Bitmap bitmap,
int quality) throws IOException {
if (bitmap == null || fileName == null || context == null)
return;
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, stream);
byte[] bytes = stream.toByteArray();
fos.write(bytes);
fos.close();
}
/**
* 写图片文件到SD�?
*
* @throws IOException
*/
public void saveImageToSD(String filePath, Bitmap bitmap, int quality)
throws IOException {
if (bitmap != null) {
FileOutputStream fos = new FileOutputStream(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, stream);
byte[] bytes = stream.toByteArray();
fos.write(bytes);
fos.close();
}
}
/**
* 获取bitmap
*
* @param context
* @param fileName
* @return
*/
public Bitmap getBitmap(Context context, String fileName) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = context.openFileInput(fileName);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* 获取bitmap
*
* @param filePath
* @return
*/
public Bitmap getBitmapByPath(String filePath) {
return getBitmapByPath(filePath, null);
}
public Bitmap getBitmapByPath(String filePath, BitmapFactory.Options opts) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis, null, opts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* 获取bitmap
*
* @param file
* @return
*/
public Bitmap getBitmapByFile(File file) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* 使用当前时间戳拼接一个唯�?��文件�?
*
* @param format
* @return
*/
public String getTempFileName() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
String fileName = format.format(new Timestamp(System
.currentTimeMillis()));
return fileName;
}
/**
* 获取照相机使用的目录
*
* @return
*/
public String getCamerPath() {
return Environment.getExternalStorageDirectory() + File.separator
+ "FounderNews" + File.separator;
}
/**
* 判断当前Url是否标准的content://样式,如果不是,则返回绝对路�?
*
* @param uri
* @return
*/
public String getAbsolutePathFromNoStandardUri(Uri mUri) {
String filePath = null;
String mUriString = mUri.toString();
mUriString = Uri.decode(mUriString);
String pre1 = "file://" + SDCARD + File.separator;
String pre2 = "file://" + SDCARD_MNT + File.separator;
if (mUriString.startsWith(pre1)) {
filePath = Environment.getExternalStorageDirectory().getPath()
+ File.separator + mUriString.substring(pre1.length());
} else if (mUriString.startsWith(pre2)) {
filePath = Environment.getExternalStorageDirectory().getPath()
+ File.separator + mUriString.substring(pre2.length());
}
return filePath;
}
/**
* 通过uri获取文件的绝对路�?
*
* @param uri
* @return
*/
public String getAbsoluteImagePath(Activity context, Uri uri) {
String imagePath = "";
String[] proj = { MediaColumns.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = context.managedQuery(uri, proj, // Which columns to
// return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
imagePath = cursor.getString(column_index);
}
}
return imagePath;
}
/**
* 获取图片缩略�? 只有Android2.1以上版本支持
*
* @param imgName
* @param kind
* MediaStore.Images.Thumbnails.MICRO_KIND
* @return
*/
public Bitmap loadImgThumbnail(Activity context, String imgName, int kind) {
Bitmap bitmap = null;
String[] proj = { BaseColumns._ID, MediaColumns.DISPLAY_NAME };
Cursor cursor = context.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
MediaColumns.DISPLAY_NAME + "='" + imgName + "'", null, null);
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
ContentResolver crThumb = context.getContentResolver();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
bitmap = MethodsCompat.getInstance().getThumbnail(crThumb,
cursor.getInt(0), kind, options);
}
return bitmap;
}
public Bitmap loadImgThumbnail(String filePath, int w, int h) {
Bitmap bitmap = getBitmapByPath(filePath);
return zoomBitmap(bitmap, w, h);
}
/**
* 获取SD卡中�?��图片路径
*
* @return
*/
public String getLatestImage(Activity context) {
String latestImage = null;
String[] items = { BaseColumns._ID, MediaColumns.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = context.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items, null,
null, BaseColumns._ID + " desc");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
latestImage = cursor.getString(1);
break;
}
}
return latestImage;
}
/**
* 计算缩放图片的宽�?
*
* @param img_size
* @param square_size
* @return
*/
public int[] scaleImageSize(int[] img_size, int square_size) {
if (img_size[0] <= square_size && img_size[1] <= square_size)
return img_size;
double ratio = square_size
/ (double) Math.max(img_size[0], img_size[1]);
return new int[] { (int) (img_size[0] * ratio),
(int) (img_size[1] * ratio) };
}
/**
* 创建缩略�?
*
* @param context
* @param largeImagePath
* 原始大图路径
* @param thumbfilePath
* 输出缩略图路�?
* @param square_size
* 输出图片宽度
* @param quality
* 输出图片质量
* @throws IOException
*/
public void createImageThumbnail(Context context, String largeImagePath,
String thumbfilePath, int square_size, int quality)
throws IOException {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 1;
// 原始图片bitmap
Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);
if (cur_bitmap == null)
return;
// 原始图片的高�?
int[] cur_img_size = new int[] { cur_bitmap.getWidth(),
cur_bitmap.getHeight() };
// 计算原始图片缩放后的宽高
int[] new_img_size = scaleImageSize(cur_img_size, square_size);
// 生成缩放后的bitmap
Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0],
new_img_size[1]);
// 生成缩放后的图片文件
saveImageToSD(thumbfilePath, thb_bitmap, quality);
}
/**
* 放大缩小图片
*
* @param bitmap
* @param w
* @param h
* @return
*/
public Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
Bitmap newbmp = null;
if (bitmap != null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidht, scaleHeight);
newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
true);
}
return newbmp;
}
public Bitmap scaleBitmap(Bitmap bitmap) {
// 获取这个图片的宽和高
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// 定义预转换成的图片的宽度和高�?
int newWidth = 200;
int newHeight = 200;
// 计算缩放率,新尺寸除原始尺寸
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
// 旋转图片 动作
// matrix.postRotate(45);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
return resizedBitmap;
}
/**
* (缩放)重绘图片
*
* @param context
* Activity
* @param bitmap
* @return
*/
public Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int rHeight = dm.heightPixels;
int rWidth = dm.widthPixels;
// float rHeight=dm.heightPixels/dm.density+0.5f;
// float rWidth=dm.widthPixels/dm.density+0.5f;
// int height=bitmap.getScaledHeight(dm);
// int width = bitmap.getScaledWidth(dm);
int height = bitmap.getHeight();
int width = bitmap.getWidth();
float zoomScale;
/** 方式1 **/
// if(rWidth/rHeight>width/height){//以高为准
// zoomScale=((float) rHeight) / height;
// }else{
// //if(rWidth/rHeight<width/height)//以宽为准
// zoomScale=((float) rWidth) / width;
// }
/** 方式2 **/
// if(width*1.5 >= height) {//以宽为准
// if(width >= rWidth)
// zoomScale = ((float) rWidth) / width;
// else
// zoomScale = 1.0f;
// }else {//以高为准
// if(height >= rHeight)
// zoomScale = ((float) rHeight) / height;
// else
// zoomScale = 1.0f;
// }
/** 方式3 **/
if (width >= rWidth)
zoomScale = ((float) rWidth) / width;
else
zoomScale = 1.0f;
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 缩放图片动作
matrix.postScale(zoomScale, zoomScale);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* 将Drawable转化为Bitmap
*
* @param drawable
* @return
*/
public Bitmap drawableToBitmap(Drawable drawable) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
return bitmap;
}
/**
* 获得圆角图片的方�?
*
* @param bitmap
* @param roundPx
* �?��设成14
* @return
*/
public Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* 获得带�?影的图片方法
*
* @param bitmap
* @return
*/
public Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
final int reflectionGap = 4;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
width, height / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
(height + height / 2), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
+ reflectionGap, paint);
return bitmapWithReflection;
}
/**
* 将bitmap转化为drawable
*
* @param bitmap
* @return
*/
public Drawable bitmapToDrawable(Bitmap bitmap) {
Drawable drawable = new BitmapDrawable(bitmap);
return drawable;
}
/**
* 获取图片类型
*
* @param file
* @return
*/
public String getImageType(File file) {
if (file == null || !file.exists()) {
return null;
}
InputStream in = null;
try {
in = new FileInputStream(file);
String type = getImageType(in);
return type;
} catch (IOException e) {
return null;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
}
/**
* detect bytes's image type by inputstream
*
* @param in
* @return
* @see #getImageType(byte[])
*/
public String getImageType(InputStream in) {
if (in == null) {
return null;
}
try {
byte[] bytes = new byte[8];
in.read(bytes);
return getImageType(bytes);
} catch (IOException e) {
return null;
}
}
/**
* detect bytes's image type
*
* @param bytes
* 2~8 byte at beginning of the image file
* @return image mimetype or null if the file is not image
*/
public String getImageType(byte[] bytes) {
if (isJPEG(bytes)) {
return "image/jpeg";
}
if (isGIF(bytes)) {
return "image/gif";
}
if (isPNG(bytes)) {
return "image/png";
}
if (isBMP(bytes)) {
return "application/x-bmp";
}
return null;
}
private boolean isJPEG(byte[] b) {
if (b.length < 2) {
return false;
}
return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
}
private boolean isGIF(byte[] b) {
if (b.length < 6) {
return false;
}
return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8'
&& (b[4] == '7' || b[4] == '9') && b[5] == 'a';
}
private boolean isPNG(byte[] b) {
if (b.length < 8) {
return false;
}
return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78
&& b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10
&& b[6] == (byte) 26 && b[7] == (byte) 10);
}
private boolean isBMP(byte[] b) {
if (b.length < 2) {
return false;
}
return (b[0] == 0x42) && (b[1] == 0x4d);
}
}
| gpl-2.0 |
DanielCoutoVale/TranslogToolset | src/org/uppermodel/translog/TranslogDocument_0_1_0.java | 4381 | package org.uppermodel.translog;
import java.util.LinkedList;
import java.util.List;
import org.uppermodel.translog.v0v1v0.Event;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
/**
* Translog document v.0.1.0
*
* @author Daniel Couto-Vale <danielvale@icloud.com>
*/
public class TranslogDocument_0_1_0 implements TranslogDocument {
private static final String VERSION_EXP = "/LogFile/VersionString";
private static final String TRANSLATOR_ID_EXP = "/LogFile/Subject";
private static final String SOURCE_TEXT_EXP = "/LogFile/Project/Interface/Standard/Settings/SourceTextUTF8";
private static final String TARGET_TEXT_EXP = "/LogFile/Project/Interface/Standard/Settings/TargetTextUTF8";
private static final String FINAL_TARGET_TEXT_EXP = "/LogFile/FinalTextChar/CharPos";
private static final String EVENTS_EXP = "/LogFile/Events/*";
/**
* The DOM document
*/
private Document document;
/**
* The xPath object
*/
private final XPath xPath;
private XPathExpression versionExp;
private XPathExpression translatorIdExp;
private XPathExpression sourceTextExp;
private XPathExpression targetTextExp;
private XPathExpression finalTargetTextExp;
private XPathExpression eventsExp;
/**
* Constructor
*
* @param document the DOM document
*/
public TranslogDocument_0_1_0(Document document) {
this.document = document;
this.xPath = XPathFactory.newInstance().newXPath();
try {
this.versionExp = this.xPath.compile(VERSION_EXP);
this.translatorIdExp = this.xPath.compile(TRANSLATOR_ID_EXP);
this.sourceTextExp = this.xPath.compile(SOURCE_TEXT_EXP);
this.targetTextExp = this.xPath.compile(TARGET_TEXT_EXP);
this.finalTargetTextExp = this.xPath.compile(FINAL_TARGET_TEXT_EXP);
this.eventsExp = this.xPath.compile(EVENTS_EXP);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
@Override
public final String getVersion() {
return extractString(versionExp);
}
@Override
public final String getTranslatorId() {
return extractString(translatorIdExp);
}
@Override
public final String getSourceText() {
return extractString(sourceTextExp);
}
@Override
public final String getInitialTargetText() {
return extractString(targetTextExp);
}
@Override
public final String getFinalTargetText() {
try {
return getFinalTargetTextImpl();
} catch (XPathExpressionException e) {
e.printStackTrace();
return "";
}
}
private final String getFinalTargetTextImpl() throws XPathExpressionException {
StringBuffer buffer = new StringBuffer();
NodeList nodeList = (NodeList) finalTargetTextExp.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element)nodeList.item(i);
String value = element.getAttribute("Value");
if (value.equals("\n")) {
value = "";
}
buffer.append(value);
}
return buffer.toString();
}
@Override
public final List<TranslogEvent> getEvents() {
try {
return getEventListImp();
} catch (XPathExpressionException e) {
e.printStackTrace();
return new LinkedList<TranslogEvent>();
}
}
private final List<TranslogEvent> getEventListImp() throws XPathExpressionException {
List<TranslogEvent> events = new LinkedList<TranslogEvent>();
NodeList nodeList = (NodeList) eventsExp.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element)nodeList.item(i);
events.add(Event.makeNode(element, xPath));
}
return events;
}
private final String extractString(XPathExpression exp) {
try {
return extractStringImp(exp);
} catch (XPathExpressionException e) {
e.printStackTrace();
return null;
}
}
private final String extractStringImp(XPathExpression exp) throws XPathExpressionException {
NodeList nodeList = (NodeList) exp.evaluate(document, XPathConstants.NODESET);
Node node = nodeList.item(0).getFirstChild();
return node == null ? "" : node.getNodeValue();
}
@Override
public boolean isCompliant() {
return document.getDocumentElement().getNodeName().equals("LogFile");
}
}
| gpl-2.0 |
marchold/DashAndDittosPlayground | PlaygroundFree/src/com/catglo/dashplaygroundfree/MenuExecutor.java | 973 | package com.catglo.dashplaygroundfree;
import java.util.LinkedList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
interface MenuExecutor {
void execute();
}
class MenuItem extends Object {
Rect area;
private MenuExecutor executor;
boolean inverted=false;
public MenuItem(Rect r,MenuExecutor executor){
area = r;
this.executor = executor;
}
void go(){
executor.execute();
}
public void invert() {
inverted=true;
}
}
| gpl-2.0 |
ifellows/Deducer | org/org/rosuda/deducer/widgets/event/RKeyListener.java | 420 | package org.rosuda.deducer.widgets.event;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class RKeyListener extends RListener implements KeyListener{
public void keyPressed(KeyEvent arg0) {
eventOccured(arg0,"keyPressed");
}
public void keyReleased(KeyEvent arg0) {
eventOccured(arg0,"keyReleased");
}
public void keyTyped(KeyEvent arg0) {
eventOccured(arg0,"keyTyped");
}
}
| gpl-2.0 |
BayCEER/bayeos-xmlrpc | src/main/java/org/apache/xmlrpc/SessionHandler.java | 156 | package org.apache.xmlrpc;
public interface SessionHandler {
void checkSession(Integer SessionId, Integer UserId) throws InvalidSessionException;
}
| gpl-2.0 |
jpelc/java-design-patterns | factory-method/src/main/java/jpelc/learning/designpatterns/factorymethod/WeaponType.java | 324 | package jpelc.learning.designpatterns.factorymethod;
public enum WeaponType {
SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
private String title;
WeaponType(String title) {
this.title = title;
}
@Override
public String toString() {
return title;
}
}
| gpl-2.0 |
shevek/qemu-java | qemu-qapi/src/main/java/org/anarres/qemu/qapi/api/NFSServer.java | 1832 | package org.anarres.qemu.qapi.api;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.anarres.qemu.qapi.common.*;
/**
* Autogenerated class.
*
* <pre>QApiStructDescriptor{name=NFSServer, data={type=NFSTransport, host=str}, innerTypes=null, fields=null, base=null}</pre>
*/
// QApiStructDescriptor{name=NFSServer, data={type=NFSTransport, host=str}, innerTypes=null, fields=null, base=null}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class NFSServer extends QApiType {
@SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")
@JsonProperty("type")
@Nonnull
public NFSTransport type;
@SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")
@JsonProperty("host")
@Nonnull
public java.lang.String host;
@Nonnull
public NFSServer withType(NFSTransport value) {
this.type = value;
return this;
}
@Nonnull
public NFSServer withHost(java.lang.String value) {
this.host = value;
return this;
}
public NFSServer() {
}
public NFSServer(NFSTransport type, java.lang.String host) {
this.type = type;
this.host = host;
}
@JsonIgnore
@Override
public java.util.List<java.lang.String> getFieldNames() {
java.util.List<java.lang.String> names = super.getFieldNames();
names.add("type");
names.add("host");
return names;
}
@Override
public Object getFieldByName(@Nonnull java.lang.String name) throws NoSuchFieldException {
if ("type".equals(name))
return type;
if ("host".equals(name))
return host;
return super.getFieldByName(name);
}
}
| gpl-2.0 |
wnoisephx/fred-official | src/freenet/node/PacketFormat.java | 1733 | package freenet.node;
import java.util.List;
import java.util.Vector;
import freenet.io.comm.Peer;
public interface PacketFormat {
boolean handleReceivedPacket(byte[] buf, int offset, int length, long now, Peer replyTo);
/**
* Maybe send something. A SINGLE PACKET. Don't send everything at once, for two reasons:
* <ol>
* <li>It is possible for a node to have a very long backlog.</li>
* <li>Sometimes sending a packet can take a long time.</li>
* <li>In the near future PacketSender will be responsible for output bandwidth throttling. So it makes sense to
* send a single packet and round-robin.</li>
* </ol>
* @param ackOnly
*/
boolean maybeSendPacket(long now, Vector<ResendPacketItem> rpiTemp, int[] rpiIntTemp, boolean ackOnly)
throws BlockedTooLongException;
/**
* Called when the peer has been disconnected.
*/
List<MessageItem> onDisconnect();
/**
* Returns {@code false} if the packet format can't send packets because it must wait for some internal event.
* For example, if a packet sequence number can not be allocated this method should return {@code false}, but if
* nothing can be sent because there is no (external) data to send it should not.
* Note that this only applies to packets being created from messages on the @see PeerMessageQueue.
* @return {@code false} if the packet format can't send packets
*/
boolean canSend();
/**
* @return The time at which the packet format will want to send an ack or similar.
* 0 if there are already messages in flight. Long.MAX_VALUE if not supported or if
* there is nothing to ack and nothing in flight. */
long timeNextUrgent();
void checkForLostPackets();
long timeCheckForLostPackets();
}
| gpl-2.0 |
Thomashuet/Biocham | gui/modelData/ParamTableRules.java | 32668 | package fr.inria.contraintes.biocham.modelData;
import fr.inria.contraintes.biocham.BiochamDynamicTree;
import fr.inria.contraintes.biocham.BiochamMainFrame;
import fr.inria.contraintes.biocham.BiochamModel;
import fr.inria.contraintes.biocham.BiochamModelElement;
import fr.inria.contraintes.biocham.WorkbenchArea;
import fr.inria.contraintes.biocham.customComponents.CustomToolTipButton;
import fr.inria.contraintes.biocham.customComponents.DeleteButton;
import fr.inria.contraintes.biocham.customComponents.ModifyButton;
import fr.inria.contraintes.biocham.dialogs.DialogAddSpecification;
import fr.inria.contraintes.biocham.graphicalEditor.Parser_SBGNRule2BiochamRule;
import fr.inria.contraintes.biocham.menus.BiochamMenuBar;
import fr.inria.contraintes.biocham.utils.SwingWorker;
import fr.inria.contraintes.biocham.utils.Utils;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
public class ParamTableRules implements Parameters, ActionListener{
private final static int H_CONST=70;
private final static int W_CONST=10;
Vector<Rule> rules;
WorkbenchArea biocham;
private JPanel panel;
BiochamModel model;
BiochamModelElement element;
int savedResponses;
boolean deleting=false, adding=false;
ArrayList<String> uknownParams;
Spring maxSpring;
int north=0;
HashMap<Integer,String> parentRules;
boolean newAdded=false;
boolean ignoreUndefinedParametersWarnings=false;
boolean addRule=false;
boolean fromGraph=false;
int rulesCounter=0;
boolean dontDraw=false;
int counter=0;
ModifyRule modifyListener;
DeleteRule deleteListener;
private boolean forDeleting=false;
RulesModel rulesModel;
RulesView view;
public RulesView getView() {
return view;
}
public void setView(RulesView view) {
this.view = view;
}
public RulesModel getRulesModel() {
return rulesModel;
}
public void setRulesModel(RulesModel rmodel) {
this.rulesModel = rmodel;
}
private int calculatePreferredPanelHeight(){
int h=0;
h=rules.size()*ParamTableRules.H_CONST;
Utils.debugMsg("h="+h);
return h;
}
private int calculatePreferredPanelWidth(){
int w=0;
for(int i=0;i<rules.size();i++){
if(w<rules.get(i).getName().length()){
w=rules.get(i).getName().length();
}
}
w*=ParamTableRules.W_CONST;
Utils.debugMsg("w="+w);
return w;
}
public void setPanelPreferredSize(){
Dimension d=null;
if(rules.size()>1){
d=new Dimension(calculatePreferredPanelWidth(),calculatePreferredPanelHeight());
}else{
d=new Dimension(100,100);
}
if(panel.getParent()!=null){
panel.getParent().setPreferredSize(d);
Utils.debugMsg("PARENT IS NOT NULL");
}else{
Utils.debugMsg("PARENT ISSSSSS NULL");
}/*panel.setPreferredSize(null);
panel.revalidate();
panel.repaint();*/
/*if(getPanel().getParent()!=null) getPanel().getParent().validate();
//getPanelCurrentX();getPanelCurrentY();
SwingWorker sw=new SwingWorker(){
@Override
public Object construct() {
Dimension d=new Dimension(getPanelCurrentX(),getPanelCurrentY());
getPanel().setPreferredSize(d);
//getPanel().setLayout (null);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
d=null;
return null;
}
@Override
public void finished() {
//getPanel().getParent().validate();
}};
sw.start();
//if(rules.size()<4) getPanel().setMaximumSize(new Dimension(100,80));
//getPanel().setMaximumSize(new Dimension(getPanelCurrentX(),getPanelCurrentY()));
//getPanel().revalidate();
//getPanel().repaint();
*/
}
/*public int getPanelCurrentX(){
int x=(int) getPanel().getPreferredSize().getWidth();
int x=0;
Spring maxSpring =null;// Spring.constant(10);
SpringLayout layout = (SpringLayout) getPanel().getLayout();
int i=1;
if(getPanel().getComponentCount()>3){
i=3;
}
maxSpring=layout.getConstraint(SpringLayout.WEST, getPanel().getComponent(getPanel().getComponentCount()-i));
x=maxSpring.getValue()+80;
System.out.println("\nx="+x+"\n");
return x;
}
public int getPanelCurrentY(){
int y=(int) getPanel().getPreferredSize().getWidth();
int y=0;
Spring maxSpring =null;// Spring.constant(10);
SpringLayout layout = (SpringLayout) getPanel().getLayout();
maxSpring=layout.getConstraint(SpringLayout.NORTH, getPanel().getComponent(getPanel().getComponentCount()-1));
y=maxSpring.getValue()+80;
System.out.println("\ny="+y+"\n");
return y;
}*/
public ParamTableRules(BiochamModel m,WorkbenchArea workbench, JPanel p){
biocham=workbench;
model=m;
setPanel(p);
rules=new Vector<Rule>();
element=model.getRules();
savedResponses=-1;
uknownParams=new ArrayList<String>();
parentRules=new HashMap<Integer,String>();
Utils.modern.setBorderThickness(3);
Utils.modern.enableAntiAliasing(true);
modifyListener=new ModifyRule();
deleteListener=new DeleteRule();
rulesModel=new RulesModel(model);
view=new RulesView(BiochamMainFrame.frame,rulesModel);
}
public String getName(int i) {
return rules.get(i).getName();
}
public String getValue(int i) {
return rules.get(i).getValue();
}
public int indexOf(String paramName) {
int i=0;
while (i<rules.size() && !getName(i).equals(paramName))
i++;
if (i == rules.size())
return -1;
return i;
}
public int indexOfExtendedPart(String paramName) {
int i=0;
while (i<rules.size() && !getValue(i).equals(paramName))
i++;
if (i == rules.size())
return -1;
return i;
}
public void resetParameter(String s) {
//as the rule can't be modified, it can't be reseted to its original value too.
}
public void setValue(ArrayList list) {
boolean b=SwingUtilities.isEventDispatchThread();
String arg1=((String) list.get(0)).trim();
String arg2=((String) list.get(1)).trim();
int i = indexOf(arg1);
int j = indexOfExtendedPart(arg2);
rulesModel.addRule(arg1, arg2);
if(i<0 || j<0){
Rule rule=new Rule(arg1,arg2);
rules.add(rule);
BiochamModelElement element=model.getModelElement("Reactions");
if(i<0){
BiochamDynamicTree tree=new BiochamDynamicTree(arg1.trim());
tree.addRuleObject(rule);
tree.setName(arg1);
tree.tree.setName(arg1.trim());
element.addDtree(tree);
getPanel().add(tree.tree);
parentRules.put(rulesCounter,arg1.trim());
rulesCounter++;
}else if(i>=0 && j<0){
Component[] comps=getPanel().getComponents();
for(int k=0;k<comps.length;k++){
if(comps[k].getName().equals(arg1)){
BiochamDynamicTree dtree=element.getDtree(arg1);
dtree.addRuleObject(rule);
//getPanel().setPreferredSize(new Dimension(getPanelCurrentX(),getPanelCurrentY()));
//getPanel().revalidate();
break;
}
}
comps=null;
}
//getPanel().setPreferredSize(new Dimension(getPanelCurrentX(),getPanelCurrentY()));
//getPanel().revalidate();
}else{
//JOptionPane.showMessageDialog(BiochamMainFrame.frame,"\nThe rule "+arg1+" is already definied.\n");
}
setFromGraph(false);
refreshAfterAddingNew();
setNewAdded(false);
//setPanelPreferredSize();
//getPanel().revalidate();
}
public int size() {
return rules.size();
}
public void setModified(Component comp) {
// There is no point yet of rule to be modified.
}
public class Rule{
private String name,value;
Rule(String n,String v){
name=n; //the original rule
value=v; //the expanded rule
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String toString() {
return getValue();
}
}
class ModifyRule extends MouseAdapter{
public void mouseClicked(MouseEvent e) {
Component button=(Component) e.getSource();
String name=button.getName();
modifyRule(name,true,true);
button=null;
name=null;
}
}
class DeleteRule extends MouseAdapter{
public void mouseClicked(MouseEvent e) {
int answ=JOptionPane.showConfirmDialog(BiochamMainFrame.frame,"Are you sure you want to delete this reaction? ","Delete reaction rule",JOptionPane.YES_NO_OPTION);
if(answ==JOptionPane.YES_OPTION){
Component button=(Component) e.getSource();
String name=button.getName();
deleteRule(name,true,true,true);
button=null;
name=null;
}
}
}
synchronized public JPanel refreshPanel(ArrayList cs) {
int northBefore=25;
Spring maxSpring = Spring.constant(BiochamModel.MIDDLE);
int size=cs.size();
SpringLayout layout = (SpringLayout) getPanel().getLayout();
if(size!=0){
JTree jt;
ArrayList<JTree> trees=new ArrayList<JTree>();
for(int i=0;i<size;i++){
if(cs.get(i) instanceof JTree){
trees.add((JTree)cs.get(i));
}
}
size=trees.size();
JTree treeBefore=null;
for(int t=0;t<size;t++){
jt=trees.get(t);
jt.setToolTipText("Show expanded rules...");
String s=jt.getName();
ArrayList<TreeNode> nodes = new ArrayList<TreeNode>();
TreeNode root = (TreeNode) jt.getModel().getRoot();
nodes.add(root);
appendAllChildrenToList(nodes, root, true);
jt.collapseRow(0);
panel.add(jt);
ModifyButton but1=new ModifyButton();
but1.setName(s);
but1.addMouseListener(modifyListener);
panel.add(but1);
DeleteButton b2=new DeleteButton();
b2.setName(s);
b2.addMouseListener(deleteListener);
panel.add(b2);
int nrthBefore=0;
if(treeBefore!=null){
nrthBefore=layout.getConstraint(SpringLayout.NORTH,treeBefore).getValue();
}
int p=1;
if(t==0){
northBefore=25;
}else{
p+=((DefaultMutableTreeNode)treeBefore.getModel().getRoot()).getChildCount();
northBefore=nrthBefore+p*treeBefore.getHeight()+20;
}
layout.putConstraint(SpringLayout.WEST, but1, 5, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, but1, northBefore,SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.WEST, b2, 5, SpringLayout.EAST, but1);
layout.putConstraint(SpringLayout.NORTH, b2, northBefore,SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.WEST, jt, 10, SpringLayout.EAST, b2);
layout.putConstraint(SpringLayout.NORTH, jt, northBefore,SpringLayout.NORTH, panel);
treeBefore=jt;
nodes.clear();
nodes=null;
s=null;
root=null;
}
/*Component[] comps=getPanel().getComponents();
for(int i=0;i<comps.length/3;i++){
Spring x=Spring.sum(Spring.sum(layout.getConstraints(panel.getComponent(3*i)).getWidth(),Spring.constant(30)),Spring.constant(20));
System.out.println("********X-Spring="+x.getValue());
maxSpring = Spring.max(maxSpring, x);
System.out.println("********maxX-Spring="+maxSpring.getValue());
// int v1=maxSpring.getValue();
}
for(int i=0;i<comps.length/3;i++){
layout.putConstraint(SpringLayout.WEST, panel.getComponent(3*i+1), maxSpring, SpringLayout.WEST, panel);
}
int v1=maxSpring.getValue();
System.out.println("********maxX-Spring="+v1);
comps=null;
*/
trees.clear();
trees=null;
}
String toolTipText="<html><i>Add a reaction rule to the current set of rules if any.</i></html>";
CustomToolTipButton addButton=new CustomToolTipButton("Add",toolTipText);
addButton.setBalloonToolTipVisible(false);
addButton.setName("Add");
addButton.setActionCommand("addRule");
addButton.addActionListener(this);
toolTipText="<html><i>Shows kinetics in a separate window.</i></html>";
CustomToolTipButton showKineticsButton=new CustomToolTipButton("Show Kinetics",toolTipText);
showKineticsButton.setBalloonToolTipVisible(false);
showKineticsButton.setName("showKinetics");
showKineticsButton.setActionCommand("showKinetics");
showKineticsButton.addActionListener(biocham.tree.treeListener);
toolTipText="<html><i>Export the kinetics to a file.</i></html>";
CustomToolTipButton exportKineticsButton=new CustomToolTipButton("Export Kinetics",toolTipText);
exportKineticsButton.setBalloonToolTipVisible(false);
exportKineticsButton.setName("exportKinetics");
exportKineticsButton.setActionCommand("exportKinetics");
exportKineticsButton.addActionListener(biocham.tree.treeListener);
toolTipText="<html><i>Deletes all the reactions' rules.</i></html>";
CustomToolTipButton deleteAllButton=new CustomToolTipButton("Delete All",toolTipText);
deleteAllButton.setBalloonToolTipVisible(false);
deleteAllButton.setName("deleteAll");
deleteAllButton.setActionCommand("deleteAll");
deleteAllButton.addActionListener(this);
toolTipText="<html><i>Launches the graphical reaction editor in a separate window.</i></html>";
CustomToolTipButton rgeButton=new CustomToolTipButton("Graphical Editor",toolTipText);
rgeButton.setBalloonToolTipVisible(false);
rgeButton.setName("launchGraphicalEditor");
rgeButton.setActionCommand("launchGraphicalEditor");
rgeButton.addActionListener(biocham.tree.treeListener);
/*JLabel refreshButton=new JLabel();
refreshButton.setIcon(Icons.icons.get("Refresh3.png"));
refreshButton.setName("refresh");
refreshButton.setText("Screen Refresh");
refreshButton.setForeground(Utils.refreshedColor);
refreshButton.setToolTipText("Click to Refresh the Screen");
refreshButton.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me) {
refreshAfterAddingNew();
}
}); */
if(panel.getComponents().length>0 && !(panel.getComponents()[0] instanceof JButton)){
//int len=getPanel().getComponents().length;
//Spring n=layout.getConstraint(SpringLayout.NORTH,getPanel().getComponent(len-1));
panel.add(addButton);
panel.add(showKineticsButton);
panel.add(exportKineticsButton);
panel.add(deleteAllButton);
panel.add(rgeButton);
int north=(northBefore+60);
layout.putConstraint(SpringLayout.NORTH, addButton,north,SpringLayout.NORTH,panel);
layout.putConstraint(SpringLayout.WEST, addButton, LEFT_OFF, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, showKineticsButton, 0,SpringLayout.NORTH, addButton);
layout.putConstraint(SpringLayout.WEST, showKineticsButton, 10, SpringLayout.EAST, addButton);
layout.putConstraint(SpringLayout.NORTH, exportKineticsButton, 0,SpringLayout.NORTH, showKineticsButton);
layout.putConstraint(SpringLayout.WEST, exportKineticsButton, 10, SpringLayout.EAST, showKineticsButton);
layout.putConstraint(SpringLayout.NORTH, deleteAllButton, 0,SpringLayout.NORTH, exportKineticsButton);
layout.putConstraint(SpringLayout.WEST, deleteAllButton, 10, SpringLayout.EAST, exportKineticsButton);
layout.putConstraint(SpringLayout.NORTH, rgeButton, 0,SpringLayout.NORTH, deleteAllButton);
layout.putConstraint(SpringLayout.WEST, rgeButton, 10, SpringLayout.EAST, deleteAllButton);
}else{
panel.add(addButton);
panel.add(rgeButton);
layout.putConstraint(SpringLayout.NORTH, addButton, BiochamModel.HEIGHT,SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.NORTH, rgeButton, BiochamModel.HEIGHT,SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.WEST, addButton, 10, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.WEST, rgeButton, 10, SpringLayout.EAST, addButton);
}
//model.getRules().setSumChildren(sumChildren);
//getPanel().setPreferredSize(new Dimension(getPanelCurrentX(),getPanelCurrentY()));
/*if(!forDeleting){
setPanelPreferredSize();
}else{
forDeleting=false;
getPanel().revalidate();
getPanel().repaint();
}*/
getPanel().revalidate();
getPanel().repaint();
//getPanel().revalidate();
BiochamMenuBar.refreshMenusContext(model);
return panel;
}
private static void appendAllChildrenToList(ArrayList<TreeNode> nodes, TreeNode parent, boolean getChildChildren) {
Enumeration children = parent.children();
if (children != null) {
while (children.hasMoreElements()) {
TreeNode node = (TreeNode) children.nextElement();
nodes.add(node);
if (getChildChildren) {
appendAllChildrenToList(nodes, node, getChildChildren);
}
}
}
}
public void changeRules(final String oldRule, final String newRule){
SwingWorker sw=new SwingWorker(){
String s="";
@Override
public Object construct() {
setFromGraph(true);
boolean has=false;
String ruleToDelete=oldRule;
if(oldRule.startsWith("{") && oldRule.endsWith("}")){
ruleToDelete=oldRule.substring(1,oldRule.length()-1);
}
if(oldRule.contains("<=")){
String tmp0="";
int ind=0;
if(ruleToDelete.contains("for")){
tmp0=ruleToDelete.substring(0,ruleToDelete.indexOf("for")+2);
ind=ruleToDelete.indexOf("for")+2;
}
String r=ruleToDelete.substring(ind,ruleToDelete.indexOf("<"));
String tmp0_1="";
if(ruleToDelete.contains("=[")){
tmp0_1=ruleToDelete.substring(ruleToDelete.indexOf("<="),ruleToDelete.indexOf("]"));
}
String p=ruleToDelete.substring(ruleToDelete.lastIndexOf(">"));
ruleToDelete=tmp0+r+"="+tmp0_1+"=>"+p+","+tmp0+p+"="+tmp0_1+"=>"+r;
}
s="delete_rules({"+ruleToDelete+"}).\n";
model.sendToBiocham(s,"rules");
Component[] comps=getPanel().getComponents();
ArrayList cs=new ArrayList();
for(int i=0;i<comps.length;i++){
if(comps[i].getName().equals(oldRule)){
cs.add(comps[i]);
}
}
for(int i=0;i<cs.size();i++){
if(cs.get(i) instanceof JTree){
JTree deletedTree=(JTree)cs.get(i);
BiochamModelElement element=model.getModelElement("Reactions");
int ind=element.getNodeIndex(oldRule);
if(ind>=0){
element.removeNodeDtree(ind);
}
JLabel delbut=(JLabel)cs.get(i+1);
getPanel().remove(deletedTree);
getPanel().remove(delbut);
getPanel().validate();
}
}
forDeleting=true;
int siz=rules.size();
ArrayList<Integer> al=new ArrayList<Integer>();
String cmd="";
for(int i=0;i<siz;i++){
if(rules.get(i).getName().equals(oldRule)){
if(has){
cmd+=",";
}
cmd+=rules.get(i).getValue();
has=true;
al.add(i);
}
}
siz=al.size();
for(int i=siz-1;i>=0;i--){
rules.removeElementAt(al.get(i));
}
al.clear();
al=null;
//oldRule+=","+cmd;
comps=getPanel().getComponents();
cs.clear();
for(int i=0;i<comps.length;i++){
if((comps[i] instanceof JTree)){
cs.add(comps[i]);
}
}
comps=null;
getPanel().removeAll();
refreshPanel(cs);
cs.clear();
cs=null;
clearUknownParams();
/*try{
getPanel().getParent().validate();
getPanel().getParent().repaint();
}catch(Exception e){
e.printStackTrace();
}*/
return null;
}
@Override
public void finished() {
// at the end..
s="add_rules("+newRule+").\n"+"list_molecules.\n";
Parser_SBGNRule2BiochamRule.setDontDraw(true);
model.sendToBiocham(s,"rules");
}};
sw.start();
}
public void modifyRule(final String nmm,final boolean inGraphAlso, final boolean fromEverywhere){
String s = (String)JOptionPane.showInputDialog(
BiochamMainFrame.frame,
"",
"Rule modification",
JOptionPane.PLAIN_MESSAGE,
null,
null,
nmm);
// If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
deleteRule(nmm,true,true,false);
sendRuleToBiocham(s);
}
}
public void deleteRule(final String nmm,final boolean inGraphAlso, final boolean fromEverywhere,boolean verifyReversible) {
boolean exit=false;
forDeleting=true;
try{
String s1=null, s2=null;
String ruleToDelete=nmm;
if(nmm.startsWith("{") && nmm.endsWith("}")){
ruleToDelete=nmm.substring(1,nmm.length()-1);
}
if(nmm.contains("<=")){
String rule1=null,rule2=null;
for(int i=0;i<rules.size();i++){
if(rules.get(i).getName().equals(ruleToDelete)){
if(rule1==null){
rule1=rules.get(i).getValue();
}else{
rule2=rules.get(i).getValue();
break;
}
}
}
JCheckBox choice1 = new JCheckBox(rule1);
choice1.setName(rule1);
JCheckBox choice2 = new JCheckBox(rule2);
choice2.setName(rule2);
if(verifyReversible){
int answer=JOptionPane.showConfirmDialog(BiochamMainFrame.frame,new Object[]{"Select which direction you want to delete:",choice1,choice2},"Delete Rule",JOptionPane.OK_CANCEL_OPTION);
if(answer==JOptionPane.OK_OPTION){
//delete all the rule....
String tmp0="";
int ind=0;
if(ruleToDelete.contains("for")){
tmp0=ruleToDelete.substring(0,ruleToDelete.indexOf("for")+4);
ind=ruleToDelete.indexOf("for")+4;
}
String r=ruleToDelete.substring(ind,ruleToDelete.indexOf("<"));
String tmp0_1="";
if(ruleToDelete.contains("=[")){
tmp0_1=ruleToDelete.substring(ruleToDelete.indexOf("["),ruleToDelete.indexOf("]")+1);
}
String p=ruleToDelete.substring(ruleToDelete.lastIndexOf(">")+1);
if(tmp0_1.equals("")){
ruleToDelete=tmp0+r+"=>"+p+","+tmp0+p+"=>"+r;
}else{
ruleToDelete=tmp0+r+"="+tmp0_1+"=>"+p+","+tmp0+p+"="+tmp0_1+"=>"+r;
}
if(choice1.isSelected() && !choice2.isSelected()){
//delete all add just one.....
s2="add_rules("+choice2.getName()+").\n list_molecules.\n";
}else if(!choice1.isSelected() && choice2.isSelected()){
//delete all add just one....
s2="add_rules("+choice1.getName()+").\n list_molecules.\n";
}else if(!choice1.isSelected() && !choice2.isSelected()){
//do nothing.....
JOptionPane.showMessageDialog(BiochamMainFrame.frame, "You didn't choose any rule's direction to delete.");
exit=true;
}
}else{
exit=true;
}
}else{
//delete all the rule....
String tmp0="";
int ind=0;
if(ruleToDelete.contains("for")){
tmp0=ruleToDelete.substring(0,ruleToDelete.indexOf("for")+4);
ind=ruleToDelete.indexOf("for")+4;
}
String r=ruleToDelete.substring(ind,ruleToDelete.indexOf("<"));
String tmp0_1="";
if(ruleToDelete.contains("=[")){
tmp0_1=ruleToDelete.substring(ruleToDelete.indexOf("["),ruleToDelete.indexOf("]")+1);
}
String p=ruleToDelete.substring(ruleToDelete.lastIndexOf(">")+1);
if(tmp0_1.equals("")){
ruleToDelete=tmp0+r+"=>"+p+","+tmp0+p+"=>"+r;
}else{
ruleToDelete=tmp0+r+"="+tmp0_1+"=>"+p+","+tmp0+p+"="+tmp0_1+"=>"+r;
}
}
}
if(!exit){
s1="delete_rules({"+ruleToDelete+"}).\n";
model.sendToBiocham(s1,"rules");
Component[] comps=getPanel().getComponents();
ArrayList cs=new ArrayList();
for(int i=0;i<comps.length;i++){
if(comps[i].getName().equals(nmm)){
cs.add(comps[i]);
}
}
for(int i=0;i<cs.size();i++){
if(cs.get(i) instanceof JTree){
JTree deletedTree=(JTree)cs.get(i);
BiochamModelElement element=model.getModelElement("Reactions");
int ind=element.getNodeIndex(nmm);
if(ind>=0){
element.removeNodeDtree(ind);
}
JLabel delbut=(JLabel)cs.get(i+1);
JLabel delbut2=(JLabel)cs.get(i+2);
getPanel().remove(deletedTree);
getPanel().remove(delbut);
getPanel().remove(delbut2);
}
}
try{
rules.removeElementAt(indexOf(nmm));
}catch(Exception e){
e.getStackTrace();
}
if(nmm.contains("<=")){
try{
rules.removeElementAt(indexOf(nmm));
}catch(Exception e){}
}
comps=getPanel().getComponents();
cs.clear();
for(int i=0;i<comps.length;i++){
if((comps[i] instanceof JTree)){
cs.add(comps[i]);
}
}
comps=null;
getPanel().removeAll();
refreshPanel(cs);
cs.clear();
cs=null;
clearUknownParams();
for(int i=0;i<parentRules.size();i++){
if(parentRules.get(i)!=null && parentRules.get(i).equals(nmm)){
parentRules.remove(i);
break;
}
}
if(nmm.contains("<=")){
for(int i=0;i<parentRules.size();i++){
if(parentRules.get(i)!=null && parentRules.get(i).equals(nmm)){
parentRules.remove(i);
break;
}
}
}
if(inGraphAlso && ruleToDelete!=null){
model.getGraphEditor().getGraph().deleteReaction(nmm,fromEverywhere);
}
if(s2!=null){
model.sendToBiocham(s2,"rules");
}
}
} catch(Exception e){
if(!exit){
model.getGraphEditor().getGraph().deleteReaction(nmm,fromEverywhere);
}
e.printStackTrace();
}
BiochamMenuBar.refreshMenusContext(model);
refreshAfterAddingNew();
}
public void refreshAfterAddingNew() {
ArrayList<Component> cs=new ArrayList<Component>();
Component[] comps=getPanel().getComponents();
for(int i=0;i<comps.length;i++){
if((comps[i] instanceof JTree)){
cs.add(comps[i]);
}
}
getPanel().removeAll();
setPanel(refreshPanel(cs));
int o=getUknownParams().size();
if(o>0){
String s="Attention! These parameters have to be declared:"+"\n<html><font color=#4EE2EC>";
boolean exists=false;
for(int i=0;i<o;i++){
s+=" "+getUknownParams().get(i);
//add the rows for the uknown parameters.....
int ukn=((ParamTableParameters)model.getParameters().getParamTable()).getUknown().size();
exists=false;
for(int j=0;j<ukn;j++){
if(((ParamTableParameters)model.getParameters().getParamTable()).getUknown().get(j).equals(getUknownParams().get(i))){
exists=true;
}
}
if(!exists){
ArrayList<String> sl=new ArrayList<String>();
sl.add(getUknownParams().get(i));
sl.add("You have to define the value of this parameter...");
((ParamTableParameters)model.getParameters().getParamTable()).addUknownParameter(sl);
sl.clear();
sl=null;
}
if(i<o-1){
s+=", ";
}
int m=(i+1)%4;
if(m==0){
s+="<br> ";
}
}
s+="</font><br><br></html>";
if(!isIgnoreUndefinedParametersWarnings() && !isAddRule()){
JOptionPane.showMessageDialog(BiochamMainFrame.frame, s);
setAddRule(false);
}
//check if all molecules are declared....
if(!exists){
int molsSize=((ParamTableMolecules)model.getMolecules().getParamTable()).molecules.size();
int initConcSize=((ParamTableInitConc)model.getInitConditions().getParamTable()).getInitConcentrations().size();
s="";
for(int i=0;i<molsSize;i++){
if(initConcSize==0){
s+="absent("+((ParamTableMolecules)model.getMolecules().getParamTable()).molecules.get(i).getMoleculeName()+").\n";
}else{
for(int j=0;j<initConcSize;j++){
if(!((ParamTableInitConc)model.getInitConditions().getParamTable()).getInitConcentrations().get(j).getName().equals(((ParamTableMolecules)model.getMolecules().getParamTable()).molecules.get(i).getMoleculeName())){
s+="absent("+((ParamTableMolecules)model.getMolecules().getParamTable()).molecules.get(i).getMoleculeName()+").\n";
}
}
}
}
model.sendToBiocham(s,"rules");
}
}
setPanelPreferredSize();
//getPanel().revalidate();
BiochamMenuBar.refreshMenusContext(model);
}
public int getSavedResponses() {
return savedResponses;
}
public void setSavedResponses(int savedResponses) {
this.savedResponses = savedResponses;
}
public void resetSavedResponses() {
savedResponses=-1;
}
public boolean isDeleting() {
return deleting;
}
public void setDeleting(boolean deleting) {
this.deleting = deleting;
}
public boolean isAdding() {
return adding;
}
public void setAdding(boolean adding) {
this.adding = adding;
}
public Vector<Rule> getRules() {
return rules;
}
public void addRule(Rule rule) {
rules.add(rule);
}
public Rule createNewRule(String p, String v) {
return new Rule(p,v);
}
public void disposeElements() {
rules.clear();
rules=null;
biocham=null;
setPanel(null);
model=null;
element=null;
uknownParams.clear();
uknownParams=null;
parentRules.clear();
parentRules=null;
}
public ArrayList<String> getUknownParams() {
return uknownParams;
}
public void clearUknownParams() {
uknownParams.clear();
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="addRule"){
setFromGraph(false);
model.getGraphEditor().getGraph().setAllAdded(false);
addParameter();
BiochamMenuBar.refreshMenusContext(model);
}else if(e.getActionCommand().equals("deleteAll")){
int asw=JOptionPane.showConfirmDialog(BiochamMainFrame.frame,"Are you sure you want to delete all the model reactions?","Confirm",JOptionPane.YES_NO_OPTION);
if(asw==JOptionPane.YES_OPTION){
/*for(int i=0;i<rules.size();i++){
model.sendToBiocham("delete_rules({"+rules.get(i).getName()+","+rules.get(i).getValue()+"}).\n");
}*/
model.sendToBiocham("clear_rules.\n");
model.sendToBiocham("list_molecules.\n");
rules.clear();
getPanel().removeAll();
ArrayList cs=new ArrayList(0);
setPanel(refreshPanel(cs));
cs.clear();
cs=null;
}
}
}
public void addParameter() {
model.getGraphEditor().getGraph().setAllAdded(false);
setNewAdded(true);
setSavedResponses(-1);
element=model.getRules();
DialogAddSpecification adds=new DialogAddSpecification(BiochamMainFrame.frame, element, "Rules Operators",getPanel());
String value=adds.getFormula();
if(value!=null){
if(value.endsWith(".")){
value=value.substring(0,value.lastIndexOf("."));
}
if(value!=null){
sendRuleToBiocham(value);
}
}
}
/**
* @param value
*/
public void sendRuleToBiocham(String value) {
ArrayList<Integer> al=new ArrayList<Integer>();
for(int k=0;k<rules.size();k++){
if(rules.get(k).getName().equals(value)){
al.add(k);
}
}
for(int i=0;i<al.size();i++){
rules.removeElementAt(al.get(i));
}
al.clear();
al=null;
String s="add_rules("+value+").\n";
s+="list_molecules.\n";
model.sendToBiocham(s,"rules");
s=null;
}
public HashMap<Integer,String> getParentRules() {
return parentRules;
}
public boolean isNewAdded() {
return newAdded;
}
public void setNewAdded(boolean newAdded) {
this.newAdded = newAdded;
}
public boolean isIgnoreUndefinedParametersWarnings() {
return ignoreUndefinedParametersWarnings;
}
public void setIgnoreUndefinedParametersWarnings(boolean i) {
this.ignoreUndefinedParametersWarnings = i;
}
public boolean isAddRule() {
return addRule;
}
public void setAddRule(boolean addRule) {
this.addRule = addRule;
}
public boolean isFromGraph() {
return fromGraph;
}
public void setFromGraph(boolean fromGraph) {
this.fromGraph = fromGraph;
}
public int getRulesCounter() {
return rulesCounter;
}
public void setRulesCounter(int rulesCounter) {
this.rulesCounter = rulesCounter;
}
public boolean isDontDraw() {
return dontDraw;
}
public void setDontDraw(boolean dontDraw,int cnt) {
this.counter=cnt;
this.dontDraw = dontDraw;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
if(counter<=1){
this.dontDraw=false;
}
}
public void setPanel(JPanel panel) {
this.panel = panel;
}
public JPanel getPanel() {
return panel;
}
}
| gpl-2.0 |
WorldsBestCoder/PlanetSimulation | src/drawing/Collision.java | 3059 | package drawing;
import math.VectorMath;
/**
*
* @author Mark Traquair - Started in 2013/14
*/
public class Collision {
VectorMath math = new VectorMath();
private boolean doTheMath(Point point1, Point point2){
//This is the dot product of point 2 - point1
return ((point2.getDx()-point1.getDx())*(point2.getX()-point1.getX()))+((point2.getDy()-point1.getDy())*(point2.getY()-point1.getY())) < 0;
}
public boolean colliding(Point p1, Point p2){
double dist = math.distance(p1.getX(), p2.getX(), p1.getY(), p2.getY());
return dist < (p1.getRadius()+p2.getRadius());
}
/**
* This function is responsible for doing the math for a 2d collision
* between two points. Collisions are passed directly, hence void type.
*
* @param point1 The first point in the collision check
* @param point2 The second point in the collision check
*/
public void Coll(Point point1, Point point2){
if (doTheMath(point1, point2)){
double velocity1x = (2*point2.getMass())/(point1.getMass()+point2.getMass());
double velocity1y;
double V1xsubV2x = (point1.getDx()-point2.getDx());
double V1ysubV2y = (point1.getDy()-point2.getDy());
double X1xsubX2x = (point1.getX()-point2.getX());
double X1ysubX2y = (point1.getY()-point2.getY());
double magX1squared = Math.pow(X1xsubX2x,2)+Math.pow(X1ysubX2y,2);
double velocity2x = (2*point1.getMass())/(point1.getMass()+point2.getMass());
double velocity2y;
double V2xsubV1x = (point2.getDx()-point1.getDx());
double V2ysubV1y = (point2.getDy()-point1.getDy());
double X2xsubX1x = (point2.getX()-point1.getX());
double X2ysubX1y = (point2.getY()-point1.getY());
double magX2squared = Math.pow(X2xsubX1x,2)+Math.pow(X2ysubX1y,2);
velocity1x *= ((V1xsubV2x*X1xsubX2x+V1ysubV2y*X1ysubX2y)/magX1squared);
velocity2x *= ((V2xsubV1x*X2xsubX1x+V2ysubV1y*X2ysubX1y)/magX2squared);
velocity1y = velocity1x;
velocity2y = velocity2x;
velocity1x *= X1xsubX2x;
velocity1y *= X1ysubX2y;
velocity2x *= X2xsubX1x;
velocity2y *= X2ysubX1y;
velocity1x = point1.getDx()-velocity1x;
velocity1y = point1.getDy()-velocity1y;
velocity2x = point2.getDx()-velocity2x;
velocity2y = point2.getDy()-velocity2y;
//System.out.println(point1.getVelocity()*point1.getMass()+point2.getVelocity()*point2.getMass());
point1.setDx(velocity1x);
point1.setDy(velocity1y);
point2.setDx(velocity2x);
point2.setDy(velocity2y);
//System.out.println(point1.getVelocity()*point1.getMass()+point2.getVelocity()*point2.getMass());
}
}
}
| gpl-2.0 |
hgdev-ch/toposuite-android | app/src/main/java/ch/hgdev/toposuite/transfer/SaveStrategy.java | 1754 | package ch.hgdev.toposuite.transfer;
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Interface implementing the Strategy design pattern in order to provide an
* easy way to save an object into a file.
*
* @author HGdev
*/
public interface SaveStrategy {
/**
* Save the content of the object into a file stored in the default app
* directory.
*
* @param context The current Android Context.
* @param filename The file name.
* @return The number of line written in the target file.
*/
int saveAsCSV(Context context, String filename) throws IOException;
/**
* Save the content of the object into a file identified by its path.
*
* @param context The current Android Context.
* @param path The path where to store the file.
* @param filename The file name.
* @return The number of line written in the target file.
*/
int saveAsCSV(Context context, String path, String filename) throws IOException;
/**
* Save the content of the object into a file identified by its output
* stream.
*
* @param context The current Android Context.
* @param outputStream An opened output stream. This method must close the output
* stream.
* @return The number of line written in the target file.
*/
int saveAsCSV(Context context, FileOutputStream outputStream) throws IOException;
/**
* @param context The Current Android Context.
* @param file The file to which to save
* @return The number of lines written in the target file.
*/
int saveAsCSV(Context context, File file) throws IOException;
}
| gpl-2.0 |
mohlerm/hotspot_cached_profiles | test/gc/g1/TestG1TraceEagerReclaimHumongousObjects.java | 3815 | /*
* Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test TestG1TraceEagerReclaimHumongousObjects
* @bug 8058801 8048179
* @summary Ensure that the output for a G1TraceEagerReclaimHumongousObjects
* includes the expected necessary messages.
* @key gc
* @library /testlibrary
* @modules java.base/sun.misc
* java.management
*/
import jdk.test.lib.ProcessTools;
import jdk.test.lib.OutputAnalyzer;
import java.util.LinkedList;
public class TestG1TraceEagerReclaimHumongousObjects {
public static void main(String[] args) throws Exception {
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC",
"-Xms128M",
"-Xmx128M",
"-Xmn16M",
"-XX:G1HeapRegionSize=1M",
"-Xlog:gc+phases=trace,gc+humongous=trace",
"-XX:+UnlockExperimentalVMOptions",
GCWithHumongousObjectTest.class.getName());
OutputAnalyzer output = new OutputAnalyzer(pb.start());
// As G1ReclaimDeadHumongousObjectsAtYoungGC is set(default), below logs should be displayed.
output.shouldContain("Humongous Reclaim");
output.shouldContain("Humongous Total");
output.shouldContain("Humongous Candidate");
output.shouldContain("Humongous Reclaimed");
// As G1TraceReclaimDeadHumongousObjectsAtYoungGC is set and GCWithHumongousObjectTest has humongous objects,
// these logs should be displayed.
output.shouldContain("Live humongous");
output.shouldContain("Dead humongous region");
output.shouldHaveExitValue(0);
}
static class GCWithHumongousObjectTest {
public static final int M = 1024*1024;
public static LinkedList<Object> garbageList = new LinkedList<Object>();
// A large object referenced by a static.
static int[] filler = new int[10 * M];
public static void genGarbage() {
for (int i = 0; i < 32*1024; i++) {
garbageList.add(new int[100]);
}
garbageList.clear();
}
public static void main(String[] args) {
int[] large = new int[M];
Object ref = large;
System.out.println("Creating garbage");
for (int i = 0; i < 100; i++) {
// A large object that will be reclaimed eagerly.
large = new int[6*M];
genGarbage();
// Make sure that the compiler cannot completely remove
// the allocation of the large object until here.
System.out.println(large);
}
// Keep the reference to the first object alive.
System.out.println(ref);
System.out.println("Done");
}
}
}
| gpl-2.0 |
ahuarte47/SOS | core/api/src/main/java/org/n52/sos/service/operator/ServiceOperatorRepository.java | 6805 | /**
* Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* 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.
*/
package org.n52.sos.service.operator;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.n52.sos.exception.ConfigurationException;
import org.n52.sos.ogc.ows.OwsExceptionReport;
import org.n52.sos.request.operator.RequestOperatorRepository;
import org.n52.sos.util.AbstractConfiguringServiceLoaderRepository;
import org.n52.sos.util.CollectionHelper;
import org.n52.sos.util.MultiMaps;
import org.n52.sos.util.SetMultiMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* @author Christian Autermann <c.autermann@52north.org>
*
* @since 4.0.0
*/
public class ServiceOperatorRepository extends AbstractConfiguringServiceLoaderRepository<ServiceOperator> {
private static class LazyHolder {
private static final ServiceOperatorRepository INSTANCE = new ServiceOperatorRepository();
private LazyHolder() {};
}
/**
* Implemented ServiceOperator
*/
private final Map<ServiceOperatorKey, ServiceOperator> serviceOperators = Maps.newHashMap();
/** supported SOS versions */
private final SetMultiMap<String, String> supportedVersions = MultiMaps.newSetMultiMap();
/** supported services */
private final Set<String> supportedServices = Sets.newHashSet();
/**
* Load implemented request listener
*
* @throws ConfigurationException
* If no request listener is implemented
*/
private ServiceOperatorRepository() throws ConfigurationException {
super(ServiceOperator.class, false);
load(false);
}
public static ServiceOperatorRepository getInstance() {
return LazyHolder.INSTANCE;
}
/**
* Load the implemented request listener and add them to a map with
* operation name as key
*
* @param implementations
* the loaded implementations
*
* @throws ConfigurationException
* If no request listener is implemented
*/
@Override
protected void processConfiguredImplementations(final Set<ServiceOperator> implementations)
throws ConfigurationException {
serviceOperators.clear();
supportedServices.clear();
supportedVersions.clear();
for (final ServiceOperator so : implementations) {
serviceOperators.put(so.getServiceOperatorKey(), so);
supportedVersions.add(so.getServiceOperatorKey().getService(), so.getServiceOperatorKey()
.getVersion());
supportedServices.add(so.getServiceOperatorKey().getService());
}
}
/**
* Update/reload the implemented request listener
*
* @throws ConfigurationException
* If no request listener is implemented
*/
@Override
public void update() throws ConfigurationException {
RequestOperatorRepository.getInstance().update();
super.update();
}
/**
* @return the implemented request listener
*/
public Map<ServiceOperatorKey, ServiceOperator> getServiceOperators() {
return Collections.unmodifiableMap(serviceOperators);
}
public Set<ServiceOperatorKey> getServiceOperatorKeyTypes() {
return getServiceOperators().keySet();
}
public ServiceOperator getServiceOperator(final ServiceOperatorKey sok) {
return serviceOperators.get(sok);
}
/**
* @param service
* the service
* @param version
* the version
* @return the implemented request listener
*
*
* @throws OwsExceptionReport
*/
public ServiceOperator getServiceOperator(final String service, final String version) throws OwsExceptionReport {
return getServiceOperator(new ServiceOperatorKey(service, version));
}
/**
* @return the supportedVersions
*
* @deprecated use getSupporteVersions(String service)
*/
@Deprecated
public Set<String> getSupportedVersions() {
return getAllSupportedVersions();
}
public Set<String> getAllSupportedVersions() {
return CollectionHelper.union(supportedVersions.values());
}
/**
* @param service
* the service
* @return the supportedVersions
*
*/
public Set<String> getSupportedVersions(final String service) {
if (isServiceSupported(service)) {
return Collections.unmodifiableSet(supportedVersions.get(service));
}
return Sets.newHashSet();
}
/**
* @param version
* the version
* @return the supportedVersions
*
* @deprecated use isVersionSupported(String service, String version)
*/
@Deprecated
public boolean isVersionSupported(final String version) {
return getAllSupportedVersions().contains(version);
}
/**
* @param service
* the service
* @param version
* the version
* @return the supportedVersions
*
*/
public boolean isVersionSupported(final String service, final String version) {
return isServiceSupported(service) && supportedVersions.get(service).contains(version);
}
/**
* @return the supportedVersions
*/
public Set<String> getSupportedServices() {
return Collections.unmodifiableSet(supportedServices);
}
public boolean isServiceSupported(final String service) {
return supportedServices.contains(service);
}
}
| gpl-2.0 |
gerhard2202/Culinaromancy | src/main/java/gerhard2202/culinaromancy/item/ItemGourmetChicken.java | 856 | package gerhard2202.culinaromancy.item;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
import java.util.Random;
public class ItemGourmetChicken extends ItemCulinaromancyFood
{
public ItemGourmetChicken() {
super("gourmetChicken", 7, 8.2F, false);
}
@Override
public int getMaxItemUseDuration(ItemStack stack)
{
return 32;
}
@Override
public void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player)
{
Random buffChance = new Random();
int result = buffChance.nextInt(100) + 1;
if (result <= 50) {
player.addPotionEffect(new PotionEffect(MobEffects.SPEED, 1600, 0, false, false));
}
}
}
| gpl-2.0 |
iucn-whp/world-heritage-outlook | portlets/iucn-dbservice-portlet/docroot/WEB-INF/src/com/iucn/whp/dbservice/service/base/inscription_criteria_lkpLocalServiceClpInvoker.java | 9411 | /**
* Copyright (c) 2000-2012 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 com.iucn.whp.dbservice.service.base;
import com.iucn.whp.dbservice.service.inscription_criteria_lkpLocalServiceUtil;
import java.util.Arrays;
/**
* @author Brian Wing Shun Chan
*/
public class inscription_criteria_lkpLocalServiceClpInvoker {
public inscription_criteria_lkpLocalServiceClpInvoker() {
_methodName0 = "addinscription_criteria_lkp";
_methodParameterTypes0 = new String[] {
"com.iucn.whp.dbservice.model.inscription_criteria_lkp"
};
_methodName1 = "createinscription_criteria_lkp";
_methodParameterTypes1 = new String[] { "int" };
_methodName2 = "deleteinscription_criteria_lkp";
_methodParameterTypes2 = new String[] { "int" };
_methodName3 = "deleteinscription_criteria_lkp";
_methodParameterTypes3 = new String[] {
"com.iucn.whp.dbservice.model.inscription_criteria_lkp"
};
_methodName4 = "dynamicQuery";
_methodParameterTypes4 = new String[] { };
_methodName5 = "dynamicQuery";
_methodParameterTypes5 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery"
};
_methodName6 = "dynamicQuery";
_methodParameterTypes6 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int"
};
_methodName7 = "dynamicQuery";
_methodParameterTypes7 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int",
"com.liferay.portal.kernel.util.OrderByComparator"
};
_methodName8 = "dynamicQueryCount";
_methodParameterTypes8 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery"
};
_methodName9 = "fetchinscription_criteria_lkp";
_methodParameterTypes9 = new String[] { "int" };
_methodName10 = "getinscription_criteria_lkp";
_methodParameterTypes10 = new String[] { "int" };
_methodName11 = "getPersistedModel";
_methodParameterTypes11 = new String[] { "java.io.Serializable" };
_methodName12 = "getinscription_criteria_lkps";
_methodParameterTypes12 = new String[] { "int", "int" };
_methodName13 = "getinscription_criteria_lkpsCount";
_methodParameterTypes13 = new String[] { };
_methodName14 = "updateinscription_criteria_lkp";
_methodParameterTypes14 = new String[] {
"com.iucn.whp.dbservice.model.inscription_criteria_lkp"
};
_methodName15 = "updateinscription_criteria_lkp";
_methodParameterTypes15 = new String[] {
"com.iucn.whp.dbservice.model.inscription_criteria_lkp",
"boolean"
};
_methodName426 = "getBeanIdentifier";
_methodParameterTypes426 = new String[] { };
_methodName427 = "setBeanIdentifier";
_methodParameterTypes427 = new String[] { "java.lang.String" };
_methodName432 = "getAllInscriptionCriteria";
_methodParameterTypes432 = new String[] { };
}
public Object invokeMethod(String name, String[] parameterTypes,
Object[] arguments) throws Throwable {
if (_methodName0.equals(name) &&
Arrays.deepEquals(_methodParameterTypes0, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.addinscription_criteria_lkp((com.iucn.whp.dbservice.model.inscription_criteria_lkp)arguments[0]);
}
if (_methodName1.equals(name) &&
Arrays.deepEquals(_methodParameterTypes1, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.createinscription_criteria_lkp(((Integer)arguments[0]).intValue());
}
if (_methodName2.equals(name) &&
Arrays.deepEquals(_methodParameterTypes2, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.deleteinscription_criteria_lkp(((Integer)arguments[0]).intValue());
}
if (_methodName3.equals(name) &&
Arrays.deepEquals(_methodParameterTypes3, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.deleteinscription_criteria_lkp((com.iucn.whp.dbservice.model.inscription_criteria_lkp)arguments[0]);
}
if (_methodName4.equals(name) &&
Arrays.deepEquals(_methodParameterTypes4, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.dynamicQuery();
}
if (_methodName5.equals(name) &&
Arrays.deepEquals(_methodParameterTypes5, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]);
}
if (_methodName6.equals(name) &&
Arrays.deepEquals(_methodParameterTypes6, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0],
((Integer)arguments[1]).intValue(),
((Integer)arguments[2]).intValue());
}
if (_methodName7.equals(name) &&
Arrays.deepEquals(_methodParameterTypes7, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0],
((Integer)arguments[1]).intValue(),
((Integer)arguments[2]).intValue(),
(com.liferay.portal.kernel.util.OrderByComparator)arguments[3]);
}
if (_methodName8.equals(name) &&
Arrays.deepEquals(_methodParameterTypes8, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]);
}
if (_methodName9.equals(name) &&
Arrays.deepEquals(_methodParameterTypes9, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.fetchinscription_criteria_lkp(((Integer)arguments[0]).intValue());
}
if (_methodName10.equals(name) &&
Arrays.deepEquals(_methodParameterTypes10, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.getinscription_criteria_lkp(((Integer)arguments[0]).intValue());
}
if (_methodName11.equals(name) &&
Arrays.deepEquals(_methodParameterTypes11, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.getPersistedModel((java.io.Serializable)arguments[0]);
}
if (_methodName12.equals(name) &&
Arrays.deepEquals(_methodParameterTypes12, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.getinscription_criteria_lkps(((Integer)arguments[0]).intValue(),
((Integer)arguments[1]).intValue());
}
if (_methodName13.equals(name) &&
Arrays.deepEquals(_methodParameterTypes13, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.getinscription_criteria_lkpsCount();
}
if (_methodName14.equals(name) &&
Arrays.deepEquals(_methodParameterTypes14, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.updateinscription_criteria_lkp((com.iucn.whp.dbservice.model.inscription_criteria_lkp)arguments[0]);
}
if (_methodName15.equals(name) &&
Arrays.deepEquals(_methodParameterTypes15, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.updateinscription_criteria_lkp((com.iucn.whp.dbservice.model.inscription_criteria_lkp)arguments[0],
((Boolean)arguments[1]).booleanValue());
}
if (_methodName426.equals(name) &&
Arrays.deepEquals(_methodParameterTypes426, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.getBeanIdentifier();
}
if (_methodName427.equals(name) &&
Arrays.deepEquals(_methodParameterTypes427, parameterTypes)) {
inscription_criteria_lkpLocalServiceUtil.setBeanIdentifier((java.lang.String)arguments[0]);
}
if (_methodName432.equals(name) &&
Arrays.deepEquals(_methodParameterTypes432, parameterTypes)) {
return inscription_criteria_lkpLocalServiceUtil.getAllInscriptionCriteria();
}
throw new UnsupportedOperationException();
}
private String _methodName0;
private String[] _methodParameterTypes0;
private String _methodName1;
private String[] _methodParameterTypes1;
private String _methodName2;
private String[] _methodParameterTypes2;
private String _methodName3;
private String[] _methodParameterTypes3;
private String _methodName4;
private String[] _methodParameterTypes4;
private String _methodName5;
private String[] _methodParameterTypes5;
private String _methodName6;
private String[] _methodParameterTypes6;
private String _methodName7;
private String[] _methodParameterTypes7;
private String _methodName8;
private String[] _methodParameterTypes8;
private String _methodName9;
private String[] _methodParameterTypes9;
private String _methodName10;
private String[] _methodParameterTypes10;
private String _methodName11;
private String[] _methodParameterTypes11;
private String _methodName12;
private String[] _methodParameterTypes12;
private String _methodName13;
private String[] _methodParameterTypes13;
private String _methodName14;
private String[] _methodParameterTypes14;
private String _methodName15;
private String[] _methodParameterTypes15;
private String _methodName426;
private String[] _methodParameterTypes426;
private String _methodName427;
private String[] _methodParameterTypes427;
private String _methodName432;
private String[] _methodParameterTypes432;
} | gpl-2.0 |
Jotschi/jogl2-example | src/main/java/demos/nehe/lesson27/Lesson27.java | 562 | package demos.nehe.lesson27;
import demos.common.GLDisplay;
import demos.common.LessonNativeLoader;
/**
* @author Abdul Bezrati
*/
public class Lesson27 extends LessonNativeLoader {
public static void main(String[] args) {
GLDisplay neheGLDisplay = GLDisplay
.createGLDisplay("Lesson 27: Shadows");
Renderer renderer = new Renderer();
InputHandler inputHandler = new InputHandler(renderer, neheGLDisplay);
neheGLDisplay.addGLEventListener(renderer);
neheGLDisplay.addKeyListener(inputHandler);
neheGLDisplay.start();
}
}
| gpl-2.0 |
vs49688/RAFTools | src/main/java/net/vs49688/rafview/cli/commands/RamInfo.java | 1855 | /*
* RAFTools - Copyright (C) 2016 Zane van Iperen.
* Contact: zane@zanevaniperen.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, and only
* version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Any and all GPL restrictions may be circumvented with permission from the
* the original author.
*/
package net.vs49688.rafview.cli.commands;
import java.io.*;
import net.vs49688.rafview.interpreter.*;
public class RamInfo implements ICommand {
private final PrintStream m_Console;
public RamInfo(PrintStream out) {
m_Console = out;
}
@Override
public void process(String cmdLine, String[] args) throws CommandException, Exception {
long mb = 1048576;
Runtime r = Runtime.getRuntime();
m_Console.printf("Total Memory: %d MB\n", r.totalMemory() / mb);
m_Console.printf("Free Memory: %d MB\n", r.freeMemory() / mb);
m_Console.printf("Used Memory: %d MB\n", (r.totalMemory() - r.freeMemory()) / mb);
m_Console.printf("Max Memory: %d MB\n", r.maxMemory() / mb);
}
@Override
public String getCommand() {
return "raminfo";
}
@Override
public String getUsageString() {
return "";
}
@Override
public String getDescription() {
return "Show the system's current memory usage";
}
}
| gpl-2.0 |
vexorian/kawigi-edit | kawigi/cmd/SettingAction.java | 4485 | package kawigi.cmd;
import kawigi.properties.*;
import kawigi.widget.*;
import kawigi.editor.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Action implementation for setting actions.
*
* This class really serves two purposes. The first is to implement actions
* that are related to settings but aren't settings themselves (for instance,
* launching the config dialog and the OK and Cancel buttons on the config
* dialog).
*
* The other purpose is that it's the base class of all setting actions. As
* part of this, there are a set of static variables and methods that are
* shared by all setting instances.
*
* The intended behavior is that if the settings dialog is up, all settings are
* set on a temporary prefs object, and committed when the "OK" button is
* pushed. Otherwise, the setting is applied immediately. Therefore, if
* buttons bound to setting actions are put on the main UI somewhere, they will
* be effective immediately on being used, but settings done on the dialog are
* cancellable.
**/
@SuppressWarnings("serial")
public class SettingAction extends DefaultAction
{
/**
* Temporary storage for settings until the settings dialog is committed.
**/
protected static PrefProxy tempPrefs;
/**
* Reference to the config dialog.
**/
protected static JDialog dialog;
/**
* Returns the temporary prefs if there is one, otherwise the real
* KawigiEdit prefs.
**/
protected static PrefProxy getCurrentPrefs()
{
if (tempPrefs == null)
return PrefFactory.getPrefs();
else
return tempPrefs;
}
/**
* Returns true if settings shouldn't be committed yet.
*
* Even though things set to the temporary prefs won't be committed par se,
* in order to immediately be effective, some settings need to notify other
* objects (for instance, syntax highlighting settings require a
* repopulation of some structures in the View classes), but they should
* only do that if delayNotify() returns false.
**/
protected static boolean delayNotify()
{
return tempPrefs != null;
}
/**
* Constructs a new SettingAction for the given ActID.
**/
public SettingAction(ActID cmdid)
{
super(cmdid);
}
/**
* Executes the non-setting setting commands.
**/
public void actionPerformed(ActionEvent e)
{
switch (cmdid)
{
case actLaunchConfig:
if (dialog == null)
{
dialog = new JDialog(Dispatcher.getWindow(), "KawigiEdit Configuration", true);
dialog.getContentPane().add(UIHandler.loadMenu(MenuID.ConfigPanel, Dispatcher.getGlobalDispatcher()));
dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
dialog.pack();
dialog.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Dispatcher.getGlobalDispatcher().runCommand(ActID.actCancelConfig);
}
});
}
if (tempPrefs == null)
tempPrefs = new ChainedPrefs(PrefFactory.getPrefs());
Dispatcher.getGlobalDispatcher().UIRefresh();
dialog.setVisible(true);
break;
case actCommitConfig:
tempPrefs.commit();
doUpdates();
// fallthrough...
case actCancelConfig:
tempPrefs = null;
if (dialog != null)
{
dialog.setVisible(false);
}
break;
}
}
/**
* Returns true if this action is available.
**/
public boolean isEnabled()
{
return true;
}
/**
* Does all the commital actions that need to happen assuming all settings
* were changed at once.
**/
public void doUpdates()
{
if (Dispatcher.getProblemTimer() != null)
{
boolean show = getCurrentPrefs().getBoolean("kawigi.timer.show");
if (show)
Dispatcher.getProblemTimer().start();
else
Dispatcher.getProblemTimer().stop();
}
ProblemTimer.resetPrefs();
GenericView.getColors();
CPPView.initColors();
PythonView.initColors();
CSharpView.initColors();
JavaView.initColors();
VBView.initColors();
GenericView.resetTabStop();
if (Dispatcher.getCompileComponent() != null)
Dispatcher.getCompileComponent().updatePrefs();
if (Dispatcher.getOutputComponent() != null)
Dispatcher.getOutputComponent().updatePrefs();
if (Dispatcher.getEditorPanel() != null)
Dispatcher.getCodePane().resetPrefs();
if (Dispatcher.getLocalCodeEditorPanel() != null)
Dispatcher.getLocalCodePane().resetPrefs();
}
}
| gpl-2.0 |
VK2012/AppCommonFrame | app/src/main/java/com/vk/libs/appcommontest/gankio/mvp/data/requestbody/LoginInfoReqParam.java | 2960 | package com.vk.libs.appcommontest.gankio.mvp.data.requestbody;
/**
* Created by VK on 2017/2/8.<br/>
* - 登录
*/
public class LoginInfoReqParam {
/*
URL: /user/login.action
param:
{
account: ‘admin’,
password: ‘admin123’
}
*/
// {"j_mobile_mid":"864895022552002","j_pic_code":"4725",
// "j_password":"841e5c1f5a8a9ebc34a723f66affb38787b9364f",
// "j_app_version":"2.4.1_52_20170810","j_os_name":"samsung",
// "j_mobile_type":"ZTE U795","j_os_sdk":"17",
// "j_os_version":"Android4.2.2_JDQ39E","j_username":"leileima","salt":"b208cb62a85edb65d30f99ec3d08c434"}
private String j_mobile_mid = "864895022552002";
private String j_pic_code ;
private String j_password = "841e5c1f5a8a9ebc34a723f66affb38787b9364f";
private String j_app_version ="2.4.1_52_20170810";
private String j_os_name = "samsung";
private String j_mobile_type = "ZTE U795";
private String j_os_sdk = "17";
private String j_os_version = "Android4.2.2_JDQ39E";
private String j_username;
private String salt;
public LoginInfoReqParam(String account,String pwd,String picCode,String salt){
j_username = account;
this.salt = salt;
j_pic_code = picCode;
}
public String getJ_mobile_mid() {
return j_mobile_mid;
}
public void setJ_mobile_mid(String j_mobile_mid) {
this.j_mobile_mid = j_mobile_mid;
}
public String getJ_pic_code() {
return j_pic_code;
}
public void setJ_pic_code(String j_pic_code) {
this.j_pic_code = j_pic_code;
}
public String getJ_password() {
return j_password;
}
public void setJ_password(String j_password) {
this.j_password = j_password;
}
public String getJ_app_version() {
return j_app_version;
}
public void setJ_app_version(String j_app_version) {
this.j_app_version = j_app_version;
}
public String getJ_os_name() {
return j_os_name;
}
public void setJ_os_name(String j_os_name) {
this.j_os_name = j_os_name;
}
public String getJ_mobile_type() {
return j_mobile_type;
}
public void setJ_mobile_type(String j_mobile_type) {
this.j_mobile_type = j_mobile_type;
}
public String getJ_os_sdk() {
return j_os_sdk;
}
public void setJ_os_sdk(String j_os_sdk) {
this.j_os_sdk = j_os_sdk;
}
public String getJ_os_version() {
return j_os_version;
}
public void setJ_os_version(String j_os_version) {
this.j_os_version = j_os_version;
}
public String getJ_username() {
return j_username;
}
public void setJ_username(String j_username) {
this.j_username = j_username;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
| gpl-2.0 |
tincent/libtincent | appdemo/src/com/tincent/demo/adapter/AdBannerAdapter.java | 4595 | package com.tincent.demo.adapter;
import java.util.ArrayList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.tincent.demo.R;
import com.tincent.demo.activity.ImageDisplayActivity;
import com.tincent.demo.activity.ImagePreviewActivity;
import com.tincent.demo.model.AdBean;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
/**
* 广告条适配器
*
* @author hui.wang
* @date 2015.3.25
*
*/
public class AdBannerAdapter extends PagerAdapter {
private DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.banner_stub).showImageOnFail(R.drawable.banner_stub)
.showImageOnLoading(R.drawable.banner_stub).resetViewBeforeLoading(true).cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true).displayer(new FadeInBitmapDisplayer(300)).build();
private List<AdBean> adList;
private LayoutInflater inflater;
private Context context;
private ImageLoader imageLoader = ImageLoader.getInstance();
public AdBannerAdapter(Context ctx) {
context = ctx;
inflater = LayoutInflater.from(ctx);
adList = new ArrayList<AdBean>();
AdBean bean = new AdBean();
bean.imgul = "http://www.wahh.com.cn/UploadFiles/UploadADPic/201407291041466579.jpg";
//bean.httpurl = "http://mhospital.yihu.com/hospital/default.aspx?hospitalid=734&platformType=0&sourceType=1&sourceId=734";
AdBean bean1 = new AdBean();
bean1.imgul = "http://www.wahh.com.cn/UploadFiles/UploadADPic/201401271110367821.jpg";
//bean1.httpurl = "http://88.88.88.197:8010/Summery/index.html?PatientId=108";
AdBean bean2 = new AdBean();
bean2.imgul = "http://www.wahh.com.cn/UploadFiles/UploadADPic/201404090916310760.jpg";
//bean2.httpurl = "http://88.88.88.197:8010/ForTestRecover/index.html";
adList.add(bean);
adList.add(bean1);
adList.add(bean2);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.image_pager_item, view, false);
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final int pos = position;
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, ImagePreviewActivity.class);
intent.putExtra("position", pos);
intent.putStringArrayListExtra("uriList", (ArrayList<String>) getUriList());
context.startActivity(intent);
}
});
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(adList.get(position).imgul, imageView, options, new SimpleImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
spinner.setVisibility(View.GONE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
view.addView(imageLayout, 0);
return imageLayout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
if (adList != null) {
return adList.size();
}
return 0;
}
public String getItem(int position) {
if (adList != null) {
return adList.get(position).httpurl;
}
return null;
}
public List<String> getUriList() {
if(adList != null) {
List<String> uriList = new ArrayList<String>();
for(AdBean bean : adList) {
uriList.add(bean.imgul);
}
return uriList;
}
return null;
}
public void updateDate(List<AdBean> list) {
adList = list;
notifyDataSetChanged();
}
}
| gpl-2.0 |
christianchristensen/resin | modules/webbeans/src/javax/enterprise/inject/spi/ProcessManagedBean.java | 1495 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.enterprise.inject.spi;
/**
* {@link javax.enterprise.inject.spi.Extension} callback while processing
* a managed bean.
*
* <code><pre>
* public class MyExtension implements Extension
* {
* <X> public void
* processManagedBean(@Observes ProcessManagedBean<X> event)
* {
* ...
* }
* }
* </pre></code>
*/
public interface ProcessManagedBean<X> extends ProcessBean<X>
{
public AnnotatedType<X> getAnnotatedBeanClass();
}
| gpl-2.0 |
TKPROG/MiSeLoR | src/de/tkprog/MiSeLoR/MiSeLoR.java | 5164 | package de.tkprog.MiSeLoR;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.tkprog.log.Logger;
public class MiSeLoR {
private Database currentDatabase;
public static MiSeLoR THIS;
public static Logger log;
public static void main(String[] args){
(new File("log/")).mkdir();
log = new Logger("log/MiSeLoR_"+System.currentTimeMillis()+".log");
log.setLogToCLI(true);
log.setLogToFile(true);
log.logAll(true);
new MiSeLoR();
}
public MiSeLoR(){
try {
THIS = this;
currentDatabase = new Database("MiSeLoR_current.db");
Message.initialise(cD());
SimpleMessage.initialise(cD());
ChatMessage.initialise(cD());
LoginMessage.initialise(cD());
LeftGameMessage.initialise(cD());
ServerOverloadMessage.initialise(cD());
DeathMessage.initialise(cD());
EarnedAchievementMessage.initialise(cD());
JoinMessage.initialise(cD());
LostConnectionMessage.initialise(cD());
MovedWronglyMessage.initialise(cD());
PlayerOnlineMessage.initialise(cD());
SavingWorldDataMessage.initialise(cD());
ServerChatMessage.initialise(cD());
UUIDofPlayerIsMessage.initialise(cD());
cmd();
} catch (Exception e) {
e.printStackTrace();
}
}
private void cmd() {
boolean running = true;
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println();
do{
try {
System.out.print("> ");
String input = bf.readLine();
if(input != null){
if(Pattern.matches("help|\\?|\\\\\\?|\\\\help", input)){
System.out.println("Commands:\r\n"+
"\thelp|?|\\?|\\help - Shows this help\r\n"+
"\tparse <dd> <mm> <yyyy> <file name> - parses the given file for the given day // file name can use Regex\r\n"+
"\tparses <file name> - parses the given file (\"yyyy-mm-dd-x.log\") for the given day // file name can use Regex\r\n"+
"\tuptime <player name> - shows the uptime for the player\r\n"+
"\tall - shows a summary\r\n"+
"\tgetAllPlayer - shows all saved player\r\n"+
"\tleaderboard - Shows some leaderboard\r\n"+
"\texit - exits the program");
}
else if(Pattern.matches("parse\\s\\d{2}\\s\\d{2}\\s\\d{4}\\s(\\S*)", input)){
Pattern p = Pattern.compile("parse\\s(\\d{2})\\s(\\d{2})\\s(\\d{4})\\s(\\S*)");
Matcher mm = p.matcher(input);
mm.find();
File[] f = getFiles(mm.group(4));
for(File ff : f){
Commands.parse(Integer.parseInt(mm.group(1)), Integer.parseInt(mm.group(2)), Integer.parseInt(mm.group(3)), ff.getAbsolutePath());
}
}
else if(Pattern.matches("parses\\s(\\S*)", input)){
Pattern p = Pattern.compile("parses\\s(\\S*)");
Matcher mm = p.matcher(input);
mm.find();
String filename = mm.group(1);
File[] f = getFiles(filename);
for(File ff : f){
p = Pattern.compile("(\\d{4})\\-(\\d{2})\\-(\\d{2})\\-\\d*\\.log");
mm = p.matcher(ff.getName());
mm.find();
Commands.parse(Integer.parseInt(mm.group(3)), Integer.parseInt(mm.group(2)), Integer.parseInt(mm.group(1)), ff.getAbsolutePath());
}
}
else if(Pattern.matches("uptime\\s(\\S*)", input)){
Pattern p = Pattern.compile("uptime\\s(\\S*)");
Matcher mm = p.matcher(input);
mm.find();
Commands.uptime(mm.group(1));
}
else if(Pattern.matches("all", input)){
Commands.all();
}
else if(Pattern.matches("exit", input)){
Commands.exit();
}
else if(Pattern.matches("getAllPlayer", input)){
String[] s = Commands.getAllPlayers();
for(String ss : s){
System.out.println(ss);
}
}
else if(Pattern.matches("leaderboard", input)){
Commands.showLeaderboard(cD());
}
else{
System.out.println("The command \""+input+"\" wasn't recognized. Type in \"help\".");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} while(running);
}
private File[] getFiles(String fileregex) {
File f = new File(".");
if(!f.isDirectory()){
f = f.getParentFile();
}
if(!f.isDirectory()){
System.err.println("Sollte ned passieren...");
}
File[] ff = f.listFiles();
ArrayList<File> o = new ArrayList<File>();
for(File fff : ff){
if(Pattern.matches(fileregex, fff.getName())){
o.add(fff);
}
else{
System.out.println("\""+fileregex+"\" does not match \""+fff.getName()+"\"");
}
}
File[] ffff = new File[o.size()];
int i = 0;
for(File fff : o){
ffff[i] = fff;
i++;
}
return ffff;
}
public Database cD() {
return getCurrentDatabase();
}
public Database getCurrentDatabase() {
return currentDatabase;
}
public void setCurrentDatabase(Database currentDatabase) {
this.currentDatabase = currentDatabase;
}
}
| gpl-2.0 |
intranda/goobi-viewer-core | goobi-viewer-core/src/test/java/io/goobi/viewer/model/cms/CMSStaticPageTest.java | 1546 | /**
* This file is part of the Goobi viewer - a content presentation and management application for digitized objects.
*
* Visit these websites for more information.
* - http://www.intranda.com
* - http://digiverso.com
*
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.goobi.viewer.model.cms;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import io.goobi.viewer.model.cms.CMSStaticPage;
public class CMSStaticPageTest {
private CMSStaticPage page = new CMSStaticPage("test");
@Before
public void setUp() {
}
@Test
public void testGetPageName() {
Assert.assertEquals("test", page.getPageName());
}
@Test
public void testIsLanguageComplete() {
Assert.assertFalse(page.isLanguageComplete(Locale.GERMANY));
}
@Test
public void testHasCmsPage() {
Assert.assertFalse(page.isHasCmsPage());
}
}
| gpl-2.0 |
PDavid/aTunes | aTunes/src/main/java/net/sourceforge/atunes/kernel/modules/context/audioobject/AudioObjectBasicInfoContent.java | 5655 | /*
* aTunes
* Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
*
* See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
*
* http://www.atunes.org
* http://sourceforge.net/projects/atunes
*
* 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.
*/
package net.sourceforge.atunes.kernel.modules.context.audioobject;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.sourceforge.atunes.kernel.modules.context.AbstractContextPanelContent;
import net.sourceforge.atunes.model.ILocalAudioObject;
import net.sourceforge.atunes.model.IStateContext;
import net.sourceforge.atunes.utils.I18nUtils;
/**
* Basic information about an audio object
* @author alex
*
*/
public class AudioObjectBasicInfoContent extends AbstractContextPanelContent<AudioObjectBasicInfoDataSource> {
private static final long serialVersionUID = 996227362636450601L;
/**
* Image for Audio Object
*/
private JLabel audioObjectImage;
/**
* Title of audio object
*/
private JLabel audioObjectTitle;
/**
* Artist of audio object
*/
private JLabel audioObjectArtist;
/**
* Last date played this audio object
*/
private JLabel audioObjectLastPlayDate;
private IStateContext stateContext;
private AbstractAction addLovedSongInLastFMAction;
private AbstractAction addBannedSongInLastFMAction;
/**
* @param addBannedSongInLastFMAction
*/
public void setAddBannedSongInLastFMAction(AbstractAction addBannedSongInLastFMAction) {
this.addBannedSongInLastFMAction = addBannedSongInLastFMAction;
}
/**
* @param addLovedSongInLastFMAction
*/
public void setAddLovedSongInLastFMAction(AbstractAction addLovedSongInLastFMAction) {
this.addLovedSongInLastFMAction = addLovedSongInLastFMAction;
}
/**
* @param stateContext
*/
public void setStateContext(IStateContext stateContext) {
this.stateContext = stateContext;
}
@Override
public void clearContextPanelContent() {
super.clearContextPanelContent();
audioObjectImage.setIcon(null);
audioObjectImage.setBorder(null);
audioObjectTitle.setText(null);
audioObjectArtist.setText(null);
audioObjectLastPlayDate.setText(null);
addLovedSongInLastFMAction.setEnabled(false);
addBannedSongInLastFMAction.setEnabled(false);
}
@Override
public void updateContentFromDataSource(AudioObjectBasicInfoDataSource source) {
ImageIcon image = source.getImage();
if (image != null) {
audioObjectImage.setIcon(image);
}
audioObjectTitle.setText(source.getTitle());
audioObjectArtist.setText(source.getArtist());
audioObjectLastPlayDate.setText(source.getLastPlayDate());
// TODO: Allow these options for radios where song information is available
addLovedSongInLastFMAction.setEnabled(stateContext.isLastFmEnabled() && source.getAudioObject() instanceof ILocalAudioObject);
addBannedSongInLastFMAction.setEnabled(stateContext.isLastFmEnabled() && source.getAudioObject() instanceof ILocalAudioObject);
}
@Override
public String getContentName() {
return I18nUtils.getString("INFO");
}
@Override
public Component getComponent() {
// Create components
audioObjectImage = new JLabel();
audioObjectTitle = new JLabel();
audioObjectTitle.setHorizontalAlignment(SwingConstants.CENTER);
audioObjectTitle.setFont(getLookAndFeelManager().getCurrentLookAndFeel().getContextInformationBigFont());
audioObjectArtist = new JLabel();
audioObjectArtist.setHorizontalAlignment(SwingConstants.CENTER);
audioObjectLastPlayDate = new JLabel();
audioObjectLastPlayDate.setHorizontalAlignment(SwingConstants.CENTER);
// Add components
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(15, 0, 0, 0);
panel.add(audioObjectImage, c);
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5, 10, 0, 10);
panel.add(audioObjectTitle, c);
c.gridy = 2;
c.insets = new Insets(5, 10, 10, 10);
panel.add(audioObjectArtist, c);
c.gridy = 3;
panel.add(audioObjectLastPlayDate, c);
return panel;
}
@Override
public List<Component> getOptions() {
List<Component> options = new ArrayList<Component>();
options.add(new JMenuItem(addLovedSongInLastFMAction));
options.add(new JMenuItem(addBannedSongInLastFMAction));
return options;
}
}
| gpl-2.0 |
PDavid/aTunes | aTunes/src/main/java/net/sourceforge/atunes/gui/views/dialogs/ExtendedToolTip.java | 4283 | /*
* aTunes
* Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
*
* See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
*
* http://www.atunes.org
* http://sourceforge.net/projects/atunes
*
* 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.
*/
package net.sourceforge.atunes.gui.views.dialogs;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import net.sourceforge.atunes.Constants;
import net.sourceforge.atunes.gui.views.controls.AbstractCustomWindow;
import net.sourceforge.atunes.gui.views.controls.FadeInPanel;
import net.sourceforge.atunes.model.IControlsBuilder;
import net.sourceforge.atunes.utils.ImageUtils;
/**
* The Class ExtendedToolTip. This is a special window shown as tooltip for
* navigator tree objects
*/
public final class ExtendedToolTip extends AbstractCustomWindow {
private static final long serialVersionUID = -5041702404982493070L;
private final FadeInPanel imagePanel;
private final JLabel image;
private final JLabel line1;
private final JLabel line2;
private final JLabel line3;
/**
* Instantiates a new extended tool tip.
*
* @param controlsBuilder
* @param width
* @param height
*/
public ExtendedToolTip(final IControlsBuilder controlsBuilder,
final int width, final int height) {
super(null, width, height, controlsBuilder);
setFocusableWindowState(false);
JPanel container = new JPanel(new GridBagLayout());
this.image = new JLabel();
this.imagePanel = new FadeInPanel();
this.imagePanel.setLayout(new GridLayout(1, 1));
this.imagePanel.add(this.image);
this.line1 = new JLabel();
this.line2 = new JLabel();
this.line3 = new JLabel();
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridheight = 3;
c.insets = new Insets(0, 5, 0, 0);
container.add(this.imagePanel, c);
c.gridx = 1;
c.gridheight = 1;
c.weightx = 1;
c.anchor = GridBagConstraints.WEST;
// c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 0, 10);
container.add(this.line1, c);
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0, 10, 0, 10);
container.add(this.line2, c);
c.gridx = 1;
c.gridy = 2;
c.weighty = 1;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(0, 10, 0, 10);
container.add(this.line3, c);
// Use scroll pane to draw a border consistent with look and feel
JScrollPane scrollPane = controlsBuilder.createScrollPane(container);
scrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
add(scrollPane);
}
/**
* Sets the text of line 1
*
* @param text
*
*/
public void setLine1(final String text) {
this.line1.setText(text);
}
/**
* Sets the text of line 2
*
* @param text
*
*/
public void setLine2(final String text) {
this.line2.setText(text);
}
/**
* Sets the image
*
* @param img
* the new image
*/
public void setImage(final ImageIcon img) {
if (img != null) {
// Add 50 to width to force images to fit height of tool tip as much
// as possible
this.image.setIcon(ImageUtils.scaleImageBicubic(img.getImage(),
Constants.TOOLTIP_IMAGE_WIDTH + 50,
Constants.TOOLTIP_IMAGE_HEIGHT));
this.imagePanel.setVisible(true);
} else {
this.image.setIcon(null);
this.imagePanel.setVisible(false);
}
}
/**
* Sets the text of line 3
*
* @param text
*
*/
public void setLine3(final String text) {
this.line3.setText(text);
}
}
| gpl-2.0 |
CleverCloud/Quercus | quercus/src/main/java/com/caucho/quercus/env/JavaCalendarValue.java | 1904 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.env;
import com.caucho.quercus.program.JavaClassDef;
import java.util.Calendar;
import java.util.logging.Logger;
/**
* Represents a Quercus java Calendar value.
*/
public class JavaCalendarValue extends JavaValue {
private static final Logger log = Logger.getLogger(JavaCalendarValue.class.getName());
private final Calendar _calendar;
public JavaCalendarValue(Env env, Calendar calendar, JavaClassDef def) {
super(env, calendar, def);
_calendar = calendar;
}
/**
* Converts to a long.
*/
@Override
public long toLong() {
return _calendar.getTimeInMillis();
}
/**
* Converts to a Java Calendar.
*/
@Override
public Calendar toJavaCalendar() {
return _calendar;
}
@Override
public String toString() {
return _calendar.getTime().toString();
}
}
| gpl-2.0 |
Shashi-Bhushan/General | cp-trials/src/main/java/in/shabhushan/cp_trials/bits/CountBits.java | 392 | package in.shabhushan.cp_trials.bits;
/**
* Leetcode solution for
* https://leetcode.com/problems/counting-bits/submissions/
*/
class CountBits {
public static int[] countBits(int num) {
int[] n = new int[num + 1];
for (int i = 1; i < num + 1; i++) {
if (i % 2 == 0) {
n[i] = n[i / 2];
} else {
n[i] = n[i/2] + 1;
}
}
return n;
}
}
| gpl-2.0 |
derekprovance/Freemind | plugins/map/JCursorMapViewer.java | 9023 | /*FreeMind - A Program for creating and viewing Mindmaps
*Copyright (C) 2000-2011 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitri Polivaev and others.
*
*See COPYING for Details
*
*This program is free software; you can redistribute it and/or
*modify it under the terms of the GNU General Public License
*as published by the Free Software Foundation; either version 2
*of the License, or (at your option) any later version.
*
*This program is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License
*along with this program; if not, write to the Free Software
*Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package plugins.map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JDialog;
import javax.swing.Timer;
import org.openstreetmap.gui.jmapviewer.Coordinate;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.Tile;
import org.openstreetmap.gui.jmapviewer.TileController;
import org.openstreetmap.gui.jmapviewer.interfaces.TileCache;
import org.openstreetmap.gui.jmapviewer.interfaces.TileLoaderListener;
import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
import freemind.main.FreeMind;
import freemind.main.Resources;
import freemind.modes.mindmapmode.MindMapController;
/**
* @author foltin
* @date 24.10.2011
*/
final class JCursorMapViewer extends JMapViewer {
private static final class ScalableTileController extends TileController {
private ScalableTileController(TileSource pSource,
TileCache pTileCache, TileLoaderListener pListener) {
super(pSource, pTileCache, pListener);
}
@Override
public Tile getTile(int tilex, int tiley, int zoom) {
int max = (1 << zoom);
if (tilex < 0 || tilex >= max || tiley < 0 || tiley >= max)
return null;
Tile tile = tileCache.getTile(tileSource, tilex, tiley, zoom);
if (tile == null) {
int scale = Resources.getInstance().getIntProperty(FreeMind.SCALING_FACTOR_PROPERTY, 100);
if(scale >= 200){
tile = new ScaledTile(this, tileSource, tilex, tiley, zoom);
} else {
tile = new Tile(tileSource, tilex, tiley, zoom);
}
tileCache.addTile(tile);
tile.loadPlaceholderFromCache(tileCache);
}
return super.getTile(tilex, tiley, zoom);
}
}
private static final class ScaledTile extends Tile {
private BufferedImage scaledImage = null;
private TileController tileController;
private ScaledTile(TileController pTileController, TileSource pSource, int pXtile, int pYtile, int pZoom) {
super(pSource, pXtile, pYtile, pZoom);
tileController = pTileController;
}
@Override
public void paint(Graphics pG, int pX, int pY) {
if(scaledImage == null){
int xtile_low = xtile >> 1;
int ytile_low = ytile >> 1;
Tile tile = tileController.getTile(xtile_low, ytile_low, zoom-1);
if (tile != null && tile.isLoaded()) {
int tileSize = source.getTileSize();
int translate_x = (xtile % 2) * tileSize/2;
int translate_y = (ytile % 2) * tileSize/2;
BufferedImage image2 = tile.getImage();
scaledImage = new BufferedImage(tileSize, tileSize, image2.getType());
Graphics2D g = scaledImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image2, 0, 0, scaledImage.getWidth(), scaledImage.getHeight(), translate_x, translate_y, translate_x+tileSize/2, translate_y+tileSize/2, null);
g.dispose();
}
}
if(scaledImage != null){
pG.drawImage(scaledImage, pX, pY, null);
} else {
pG.drawImage(getImage(), pX, pY, null);
}
}
}
boolean mShowCursor;
boolean mUseCursor;
Coordinate mCursorPosition;
Stroke mStroke;
Stroke mRectangularStroke = new BasicStroke(1, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_MITER, 10.0f, new float[] { 10.0f, 10.0f }, 0.0f);
private FreeMindMapController mFreeMindMapController;
private final MapDialog mMapHook;
private boolean mHideFoldedNodes = true;
private Coordinate mRectangularStart;
private Coordinate mRectangularEnd;
private boolean mDrawRectangular = false;
private int mCursorLength;
/**
* @param pMindMapController
* @param pMapDialog
* @param pMapHook
*
*/
public JCursorMapViewer(MindMapController pMindMapController,
JDialog pMapDialog, TileCache pTileCache, MapDialog pMapHook) {
super(pTileCache, 8);
tileController = new ScalableTileController(tileSource, pTileCache, this);
int scaleProperty = Resources.getInstance().getIntProperty(FreeMind.SCALING_FACTOR_PROPERTY, 100);
mCursorLength = 15 * scaleProperty/100;
mStroke = new BasicStroke(2 * scaleProperty / 100);
mMapHook = pMapHook;
mFreeMindMapController = new FreeMindMapController(this,
pMindMapController, pMapDialog, pMapHook);
Action updateCursorAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
mShowCursor = !mShowCursor;
repaint();
}
};
new Timer(1000, updateCursorAction).start();
setFocusable(false);
}
public FreeMindMapController getFreeMindMapController() {
return mFreeMindMapController;
}
public boolean isUseCursor() {
return mUseCursor;
}
public void setUseCursor(boolean pUseCursor) {
mUseCursor = pUseCursor;
repaint();
}
public Coordinate getCursorPosition() {
return mCursorPosition;
}
public void setCursorPosition(Coordinate pCursorPosition) {
mCursorPosition = pCursorPosition;
repaint();
}
/*
* (non-Javadoc)
*
* @see
* org.openstreetmap.gui.jmapviewer.JMapViewer#paintComponent(java.awt.Graphics
* )
*/
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (g instanceof Graphics2D) {
Graphics2D g2d = (Graphics2D) g;
Stroke oldStroke = g2d.getStroke();
Color oldColor = g2d.getColor();
// do cursor
if (mUseCursor && mShowCursor) {
Point position = getMapPosition(mCursorPosition);
if (position != null) {
int size_h = mCursorLength;
g2d.setStroke(mStroke);
g2d.setColor(Color.RED);
g2d.drawLine(position.x - size_h, position.y, position.x
+ size_h, position.y);
g2d.drawLine(position.x, position.y - size_h, position.x,
position.y + size_h);
}
}
if (mDrawRectangular) {
g2d.setColor(Color.BLACK);
g2d.setStroke(mRectangularStroke);
Rectangle r = getRectangle(mRectangularStart, mRectangularEnd);
if (r != null) {
g2d.drawRect(r.x, r.y, r.width, r.height);
}
}
g2d.setColor(oldColor);
g2d.setStroke(oldStroke);
}
}
public Rectangle getRectangle(Coordinate rectangularStart,
Coordinate rectangularEnd) {
Point positionStart = getMapPosition(rectangularStart);
Point positionEnd = getMapPosition(rectangularEnd);
Rectangle r = null;
if (positionStart != null && positionEnd != null) {
int x = Math.min(positionStart.x, positionEnd.x);
int y = Math.min(positionStart.y, positionEnd.y);
int width = Math.abs(positionStart.x - positionEnd.x);
int height = Math.abs(positionStart.y - positionEnd.y);
r = new Rectangle(x, y, width, height);
}
return r;
}
public TileController getTileController() {
return tileController;
}
/* (non-Javadoc)
* @see org.openstreetmap.gui.jmapviewer.JMapViewer#initializeZoomSlider()
*/
protected void initializeZoomSlider() {
super.initializeZoomSlider();
//focus
zoomSlider.setFocusable(false);
zoomInButton.setFocusable(false);
zoomOutButton.setFocusable(false);
}
/**
* @param pHideFoldedNodes
*/
public void setHideFoldedNodes(boolean pHideFoldedNodes) {
mHideFoldedNodes = pHideFoldedNodes;
repaint();
}
public boolean isHideFoldedNodes() {
return mHideFoldedNodes;
}
public void setRectangular(Coordinate pRectangularStart, Coordinate pRectangularEnd) {
mRectangularStart = pRectangularStart;
mRectangularEnd = pRectangularEnd;
}
public boolean isDrawRectangular() {
return mDrawRectangular;
}
public void setDrawRectangular(boolean pDrawRectangular) {
mDrawRectangular = pDrawRectangular;
}
/**
* @param pMapCenterLatitude
* @param pMapCenterLongitude
* @param pZoom
*/
public void setDisplayPositionByLatLon(double pMapCenterLatitude,
double pMapCenterLongitude, int pZoom) {
super.setDisplayPosition(new Coordinate(pMapCenterLatitude, pMapCenterLongitude), pZoom);
}
} | gpl-2.0 |
dousha/MySpigotPlugins | RandomCraft/src/main/java/io/github/dousha/randomCraft/randomcraft/ItemDescription.java | 815 | package io.github.dousha.randomCraft.randomcraft;
import java.util.HashMap;
// WHY DOESN'T JAVA HAVE A STRUCT
public class ItemDescription implements Cloneable{
public boolean type; // false = in, true = out, I would use #define in c/c++!
public String itemname;
@Deprecated
public int itemid;
public boolean isMajor;
public int leastAmount;
public double base;
public String formula;
public double arg1, arg2, arg3;
public boolean isMagic;
// TODO: make it works
public HashMap<String, String> enchantments; // <name, level>
// ----^-----------------------^-----------
public String giveMethod;
@Override
public Object clone(){
ItemDescription o = null;
try{
o = (ItemDescription) super.clone();
}
catch(CloneNotSupportedException ex){
ex.printStackTrace();
}
return o;
}
}
| gpl-2.0 |
glelouet/RPG | Model/src/main/java/fr/lelouet/rpg/model/Character.java | 312 | package fr.lelouet.rpg.model;
import fr.lelouet.rpg.model.character.CharStats;
public class Character extends CharStats {
public Character(RPGGame system) {
super(system);
}
/**
*
* @return true if this character is an avatar
*/
public boolean isPlayer() {
return true;
}
public int lvl;
}
| gpl-2.0 |
rdanieli/heatmapGPS | hmGPS/ejb/src/main/java/com/eng/univates/bd/OcorrenciaBD.java | 598 | package com.eng.univates.bd;
import java.util.List;
import javax.ejb.Remote;
import com.eng.univates.pojo.Filter;
import com.eng.univates.pojo.Ocorrencia;
import com.eng.univates.pojo.Usuario;
import com.vividsolutions.jts.geom.Point;
@Remote
public interface OcorrenciaBD extends CrudBD<Ocorrencia, Integer> {
public String convertPontosGeo();
public List<Ocorrencia> getPontosConvertidos();
public List<String> getDescricaoFatos();
public List<Ocorrencia> filtraMapa(Filter filtro);
public List<Ocorrencia> pontosBatalhao(Usuario usuario, Point localViatura, Double distance);
}
| gpl-2.0 |
itsazzad/zanata-server | zanata-war/src/main/java/org/zanata/file/FileSystemPersistService.java | 5646 | /*
* Copyright 2013, 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.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.zanata.ApplicationConfiguration;
import org.zanata.dao.DocumentDAO;
import org.zanata.model.HDocument;
import org.zanata.model.HProject;
import org.zanata.model.HProjectIteration;
import org.zanata.model.HRawDocument;
import org.zanata.rest.service.VirusScanner;
import com.google.common.io.Files;
@Name("filePersistService")
@Scope(ScopeType.STATELESS)
@AutoCreate
@Slf4j
public class FileSystemPersistService implements FilePersistService {
private static final String RAW_DOCUMENTS_SUBDIRECTORY = "documents";
@In("applicationConfiguration")
private ApplicationConfiguration appConfig;
@In
private DocumentDAO documentDAO;
@In
private VirusScanner virusScanner;
@Override
public void persistRawDocumentContentFromFile(HRawDocument rawDocument,
File fromFile, String extension) {
String fileName = generateFileNameFor(rawDocument, extension);
rawDocument.setFileId(fileName);
File newFile = getFileForName(fileName);
try {
Files.copy(fromFile, newFile);
} catch (IOException e) {
// FIXME damason: throw something more specific and handle at call
// sites
throw new RuntimeException(e);
}
GlobalDocumentId globalId = getGlobalId(rawDocument);
log.info("Persisted raw document {} to file {}", globalId,
newFile.getAbsolutePath());
virusScanner.scan(newFile, globalId.toString());
}
@Override
public void copyAndPersistRawDocument(HRawDocument fromDoc,
HRawDocument toDoc) {
File file = getFileForRawDocument(fromDoc);
persistRawDocumentContentFromFile(toDoc, file,
FilenameUtils.getExtension(file.getName()));
}
private File getFileForName(String fileName) {
File docsPath = ensureDocsDirectory();
File newFile = new File(docsPath, fileName);
return newFile;
}
private File ensureDocsDirectory() {
String basePathStringOrNull =
appConfig.getDocumentFileStorageLocation();
if (basePathStringOrNull == null) {
throw new RuntimeException(
"Document storage location is not configured in JNDI.");
}
File docsDirectory =
new File(basePathStringOrNull, RAW_DOCUMENTS_SUBDIRECTORY);
docsDirectory.mkdirs();
return docsDirectory;
}
private static String generateFileNameFor(HRawDocument rawDocument, String extension) {
// Could change to use id of rawDocument, and throw if rawDocument has
// no id yet.
String idAsString = rawDocument.getDocument().getId().toString();
return idAsString + "." + extension;
}
// TODO damason: put this in a more appropriate location
private static GlobalDocumentId getGlobalId(HRawDocument rawDocument) {
HDocument document = rawDocument.getDocument();
HProjectIteration version = document.getProjectIteration();
HProject project = version.getProject();
GlobalDocumentId id =
new GlobalDocumentId(project.getSlug(), version.getSlug(),
document.getDocId());
return id;
}
@Override
public InputStream getRawDocumentContentAsStream(HRawDocument document)
throws RawDocumentContentAccessException {
File rawFile = getFileForRawDocument(document);
try {
return new FileInputStream(rawFile);
} catch (FileNotFoundException e) {
// FIXME damason: throw more specific exception and handle at call
// sites
throw new RuntimeException(e);
}
}
@Override
public boolean hasPersistedDocument(GlobalDocumentId id) {
HDocument doc = documentDAO.getByGlobalId(id);
if (doc != null) {
HRawDocument rawDocument = doc.getRawDocument();
return rawDocument != null
&& getFileForRawDocument(rawDocument).exists();
}
return false;
}
private File getFileForRawDocument(HRawDocument rawDocument) {
return getFileForName(rawDocument.getFileId());
}
}
| gpl-2.0 |
thecodinglive/hanbit-gradle-book-example | ch06/src/main/java/info/thecodinglive/service/TeamServiceImpl.java | 902 | package info.thecodinglive.service;
import info.thecodinglive.model.Team;
import info.thecodinglive.repository.TeamDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class TeamServiceImpl implements TeamService{
@Autowired
private TeamDao teamDao;
@Override
public void addTeam(Team team) {
teamDao.addTeam(team);
}
@Override
public void updateTeam(Team team) {
teamDao.updateTeam(team);
}
@Override
public Team getTeam(int id) {
return teamDao.getTeam(id);
}
@Override
public void deleteTeam(int id) {
teamDao.deleteTeam(id);
}
@Override
public List<Team> getTeams() {
return teamDao.getTeams();
}
}
| gpl-2.0 |
adamfisk/littleshoot-client | common/sip/stack/src/main/java/org/lastbamboo/common/sip/stack/message/header/SipHeaderFactoryImpl.java | 7606 | package org.lastbamboo.common.sip.stack.message.header;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.id.uuid.UUID;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.littleshoot.util.RuntimeIoException;
/**
* Factory for creating SIP headers.
*/
public class SipHeaderFactoryImpl implements SipHeaderFactory
{
private final Logger LOG = LoggerFactory.getLogger(SipHeaderFactoryImpl.class);
private static int sequenceNumber = 1;
public SipHeader createHeader(final String name, final String value)
{
final List<SipHeaderValue> headerValues;
try
{
headerValues = createHeaderValues(value);
}
catch (final IOException e)
{
LOG.error("Could not parse header");
throw new RuntimeIoException(e);
}
return new SipHeaderImpl(name, headerValues);
}
/**
* Creates a list of header values.
*
* @param headerValueString The header value string.
* @return A list of header value instances.
* @throws IOException If the header values don't match the expected
* syntax.
*
* TODO: This should really be handled at the protocol reading level
* rather than re-parsing read data here.
*/
private List<SipHeaderValue> createHeaderValues(
final String headerValueString) throws IOException
{
final List<SipHeaderValue> valuesList = new ArrayList<SipHeaderValue>();
if (!StringUtils.contains(headerValueString, ","))
{
final SipHeaderValue value =
new SipHeaderValueImpl(headerValueString);
valuesList.add(value);
return valuesList;
}
final String[] values = StringUtils.split(headerValueString, ",");
for (int i = 0; i < values.length; i++)
{
final SipHeaderValue value =
new SipHeaderValueImpl(values[i].trim());
valuesList.add(value);
}
return valuesList;
}
public SipHeader createSentByVia(final InetAddress address)
{
final String baseValue =
"SIP/2.0/TCP " + address.getHostAddress();
final Map<String, String> params =
createParams(SipHeaderParamNames.BRANCH, createBranchId());
return new SipHeaderImpl(SipHeaderNames.VIA,
new SipHeaderValueImpl(baseValue, params));
}
public SipHeader createMaxForwards(final int maxForwards)
{
final String valueString = Integer.toString(maxForwards);
final SipHeaderValue value =
new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP);
return new SipHeaderImpl(SipHeaderNames.MAX_FORWARDS, value);
}
public SipHeader createSupported()
{
final String valueString = "outbound";
final SipHeaderValue value =
new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP);
return new SipHeaderImpl(SipHeaderNames.SUPPORTED, value);
}
public SipHeader createTo(final URI sipUri)
{
final String valueString = "Anonymous <"+sipUri+">";
final SipHeaderValue value =
new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP);
return new SipHeaderImpl(SipHeaderNames.TO, value);
}
public SipHeader createTo(final SipHeader originalTo)
{
final SipHeaderValue value = originalTo.getValue();
final Map<String, String> params = value.getParams();
params.put(SipHeaderParamNames.TAG, createTagValue());
final SipHeaderValue copy =
new SipHeaderValueImpl(value.getBaseValue(), params);
return new SipHeaderImpl(SipHeaderNames.TO, copy);
}
public SipHeader createFrom(final String displayName, final URI sipUri)
{
final String baseValue = displayName + " <"+sipUri+">";
final Map<String, String> params = createParams(SipHeaderParamNames.TAG,
createTagValue());
final SipHeaderValue value = new SipHeaderValueImpl(baseValue, params);
return new SipHeaderImpl(SipHeaderNames.FROM, value);
}
public SipHeader createCallId()
{
final String valueString = createCallIdValue();
final SipHeaderValue value =
new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP);
return new SipHeaderImpl(SipHeaderNames.CALL_ID, value);
}
public SipHeader createCSeq(final String method)
{
final String valueString = createCSeqValue(method);
final SipHeaderValue value =
new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP);
return new SipHeaderImpl(SipHeaderNames.CSEQ, value);
}
public SipHeader createContact(final URI contactUri,
final UUID instanceId)
{
final String baseValue = "<"+contactUri+">";
final String sipInstanceValue = "\"<"+instanceId.toUrn()+">\"";
final Map<String, String> params =
createParams(SipHeaderParamNames.SIP_INSTANCE, sipInstanceValue);
final SipHeaderValue value = new SipHeaderValueImpl(baseValue, params);
return new SipHeaderImpl(SipHeaderNames.CONTACT, value);
}
public SipHeader createExpires(final int millis)
{
final String valueString = Integer.toString(millis);
final SipHeaderValue value =
new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP);
return new SipHeaderImpl(SipHeaderNames.EXPIRES, value);
}
public SipHeader createContentLength(final int contentLength)
{
final String valueString = Integer.toString(contentLength);
final SipHeaderValue value =
new SipHeaderValueImpl(valueString, Collections.EMPTY_MAP);
return new SipHeaderImpl(SipHeaderNames.CONTENT_LENGTH, value);
}
private String createTagValue()
{
final UUID id = UUID.randomUUID();
final String urn = id.toUrn();
return urn.substring(9, 19);
}
private String createCallIdValue()
{
final UUID id = UUID.randomUUID();
return id.toUrn().substring(10, 18);
}
private String createBranchId()
{
final UUID id = UUID.randomUUID();
return "z9hG4bK"+id.toUrn().substring(10, 17);
}
private String createCSeqValue(final String method)
{
sequenceNumber++;
return sequenceNumber + " " + method;
}
/**
* Generates the parameters map. This is the complete parameters for the
* common case where a header only has a single parameter. Otherwise,
* calling methods can add additional parameters to the map.
*
* @param name The name of the first parameter to add.
* @param value The value of the first parameter to add.
* @return The map mapping parameter names to parameter values.
*/
private Map<String, String> createParams(final String name,
final String value)
{
final Map<String, String> params = new HashMap<String, String>();
params.put(name, value);
return params;
}
}
| gpl-2.0 |
Unit4TechProjects/ChoiceOptimization | testing/TestSchedule.java | 3494 | package testing;
/**
* Copyright (C) 2015 Matthew Mussomele
*
* This file is part of ChoiceOptimizationAlgorithm
*
* ChoiceOptimizationAlgorithm 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/>.
*/
import duty_scheduler.RA;
import duty_scheduler.RA.RABuilder;
import duty_scheduler.Duty;
import duty_scheduler.Schedule;
import duty_scheduler.Schedule.ScheduleBuilder;
import java.util.ArrayList;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
* JUnit Testing Class for the duty_scheduler.Schedule class.
*
* @author Matthew Mussomele
*/
public class TestSchedule {
private static final int THIS_YEAR = 2015;
private ScheduleBuilder testBuilder;
private Schedule test;
private ArrayList<RA> raList;
private ArrayList<Duty> dutyList;
/**
* Fill the four instance variables with some simple test instances before every test.
*/
@Before public void setUp() {
dutyList = new ArrayList<Duty>();
for (int i = 0; i < 6; i += 1) {
dutyList.add(new Duty(THIS_YEAR, 1, i + 1, "/"));
}
raList = new ArrayList<RA>();
for (int i = 0; i < 2; i += 1) {
RABuilder builder = new RABuilder(String.format("RA%d", i), 6, 3);
for (int j = 0; j < 6; j += 1) {
if (i == 0) {
builder.putPreference(dutyList.get(j), j);
} else {
builder.putPreference(dutyList.get(j), 5 - j);
}
}
raList.add(builder.build());
}
ScheduleBuilder builder = new ScheduleBuilder(raList.size(), dutyList.size());
for (int i = 0; i < 3; i += 1) {
builder.putAssignment(raList.get(0), dutyList.get(5 - i));
}
for (int i = 0; i < 3; i += 1) {
builder.putAssignment(raList.get(1), dutyList.get(i));
}
testBuilder = builder;
test = builder.build();
}
/**
* Tests that the ScheduleBuilder works and properly returns a Schedule instance
*/
@Test public void testBuild() {
for (int i = 0; i < raList.size(); i += 1) {
assertTrue(testBuilder.doneAssigning(raList.get(i)));
}
assertNotNull(test);
}
/**
* Tests that the built Schedule's basic functions perform to the requirements of the package.
* These tests are to ensure that these methods are not changed by a programmer in such a way
* that would cause Schedules to be lost in a Hash or Tree based structure.
*/
@Test public void testBasics() {
for (int i = 0; i < raList.size(); i += 1) {
for (Duty duty : test.getAssignments(raList.get(i))) {
assertTrue(dutyList.contains(duty));
}
}
assertTrue(test.equals(test));
assertEquals(0, test.compareTo(test));
}
}
| gpl-2.0 |
kaisenlean/rentavoz3 | src/main/java/co/innovate/rentavoz/services/ciudad/CiudadService.java | 887 | /**
*
*/
package co.innovate.rentavoz.services.ciudad;
import java.util.List;
import co.innovate.rentavoz.model.Ciudad;
import co.innovate.rentavoz.model.Departamento;
import co.innovate.rentavoz.services.GenericService;
/**
* @author <a href="mailto:elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @project rentavoz3
* @class CiudadService
* @date 13/01/2014
*
*/
public interface CiudadService extends GenericService<Ciudad, Integer> {
/**
* @author <a href="elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @date 13/01/2014
* @param criterio
* @param departamento
* @return
*/
List<Ciudad> findByCriterio(String criterio,
Departamento departamento);
/**
*
* @author <a href="elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @date 1/02/2014
* @param criterio
* @return
*/
List<Ciudad> findByCriterio(String criterio);
}
| gpl-2.0 |
konqi/fit-precinct | src/main/java/de/konqi/fitapi/common/importer/Importer.java | 252 | package de.konqi.fitapi.common.importer;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by konqi on 08.05.2016.
*/
public interface Importer {
void importFromStream(String userEmail, InputStream is) throws IOException;
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/javax/management/modelmbean/UnserializableTargetObjectTest.java | 7371 | /*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6332962
* @summary Test that a RequiredModelMBean operation can have a targetObject
* that is not serializable
* @author Eamonn McManus
* @run clean UnserializableTargetObjectTest
* @run build UnserializableTargetObjectTest
* @run main UnserializableTargetObjectTest
*/
/* This test and DescriptorSupportSerialTest basically cover the same thing.
I wrote them at different times and forgot that I had written the earlier
one. However the coverage is slightly different so I'm keeping both. */
import java.lang.reflect.Method;
import javax.management.Attribute;
import javax.management.Descriptor;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.modelmbean.DescriptorSupport;
import javax.management.modelmbean.ModelMBean;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanInfoSupport;
import javax.management.modelmbean.ModelMBeanOperationInfo;
import javax.management.modelmbean.RequiredModelMBean;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
public class UnserializableTargetObjectTest {
public static class Resource { // not serializable!
int count;
int operationCount;
public void operation() {
operationCount++;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
public static void main(String[] args) throws Exception {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName name = new ObjectName("a:b=c");
Resource resource1 = new Resource();
Resource resource2 = new Resource();
Resource resource3 = new Resource();
Method operationMethod = Resource.class.getMethod("operation");
Method getCountMethod = Resource.class.getMethod("getCount");
Method setCountMethod = Resource.class.getMethod("setCount", int.class);
Descriptor operationDescriptor =
new DescriptorSupport(new String[] {
"descriptorType", "name", "targetObject"
}, new Object[] {
"operation", "operation", resource1
});
Descriptor getCountDescriptor =
new DescriptorSupport(new String[] {
"descriptorType", "name", "targetObject"
}, new Object[] {
"operation", "getCount", resource2
});
Descriptor setCountDescriptor =
new DescriptorSupport(new String[] {
"descriptorType", "name", "targetObject"
}, new Object[] {
"operation", "setCount", resource2
});
Descriptor countDescriptor =
new DescriptorSupport(new String[] {
"descriptorType", "name", "getMethod", "setMethod"
}, new Object[] {
"attribute", "Count", "getCount", "setCount"
});
ModelMBeanOperationInfo operationInfo =
new ModelMBeanOperationInfo("operation description",
operationMethod, operationDescriptor);
ModelMBeanOperationInfo getCountInfo =
new ModelMBeanOperationInfo("getCount description",
getCountMethod, getCountDescriptor);
ModelMBeanOperationInfo setCountInfo =
new ModelMBeanOperationInfo("setCount description",
setCountMethod, setCountDescriptor);
ModelMBeanAttributeInfo countInfo =
new ModelMBeanAttributeInfo("Count", "Count description",
getCountMethod, setCountMethod,
countDescriptor);
ModelMBeanInfo mmbi =
new ModelMBeanInfoSupport(Resource.class.getName(),
"ModelMBean to test targetObject",
new ModelMBeanAttributeInfo[] {countInfo},
null, // no constructors
new ModelMBeanOperationInfo[] {
operationInfo, getCountInfo, setCountInfo
},
null); // no notifications
ModelMBean mmb = new RequiredModelMBean(mmbi);
mmb.setManagedResource(resource3, "ObjectReference");
mbs.registerMBean(mmb, name);
mbs.invoke(name, "operation", null, null);
mbs.setAttribute(name, new Attribute("Count", 53));
if (resource1.operationCount != 1)
throw new Exception("operationCount: " + resource1.operationCount);
if (resource2.count != 53)
throw new Exception("count: " + resource2.count);
int got = (Integer) mbs.getAttribute(name, "Count");
if (got != 53)
throw new Exception("got count: " + got);
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
ModelMBeanInfo rmmbi = (ModelMBeanInfo) mbsc.getMBeanInfo(name);
// Above gets NotSerializableException if resource included in
// serialized form
cc.close();
cs.stop();
System.out.println("TEST PASSED");
}
}
| gpl-2.0 |
PimvanGurp/advanced-java | src/nl/HAN/ASD/APP/dataStructures/MyArrayList.java | 6537 | package nl.HAN.ASD.APP.dataStructures;
import com.google.gag.annotation.disclaimer.WrittenWhile;
import java.util.*;
/**
* Created by Pim van Gurp, 9/9/2015.
*/
@SuppressWarnings({"NullableProblems", "ConstantConditions"})
public class MyArrayList<T> implements List<T>, Iterable<T> {
/**
* Amount of elements in array. Can differ from array.length
*/
private int length;
/**
* Internal array for storing elements
*/
private T[] array;
/**
* Constructor for MyArrayList where attributes are initialized
*/
@SuppressWarnings("unchecked")
public MyArrayList() {
array = (T[]) new Object[3];
length = 0;
}
/**
* Private iterator class
* used to iterate over all all array elements.
* Works with foreach loops.
*/
private class MyIterator implements Iterator<T> {
private MyArrayList<T> array;
private int current;
MyIterator(MyArrayList<T> array) {
this.array = array;
this.current = 0;
}
@Override
public boolean hasNext() {
return current < array.length;
}
@Override
public T next() {
if(!hasNext()) throw new NoSuchElementException();
return array.get(current++);
}
}
/**
* Amount of elements in array.
* Can differ from array.length
* @return amount of elements in array as int
*/
@Override
public int size() {
return length;
}
/**
* Check if array contains no elements
* @return 1 array has no elements
* 0 array has elements
*/
@Override
public boolean isEmpty() {
return length == 0;
}
/**
* Get an element at a custom position
* using an index
* @param index position of element to get
* @return element at index position
*/
@Override
public T get(int index) {
if(index > size() || index < 0) throw new IndexOutOfBoundsException();
//noinspection unchecked
return array[index];
}
/**
* Set a position of the array with a new element
* @param index position in array
* @param element value to set
* @return new element that got added
*/
@Override
public T set(int index, T element) {
if(index > size() || index < 0) throw new IndexOutOfBoundsException();
array[index] = element;
return element;
}
/**
* Add a new element to array
* @param index position in array
* @param element new value
*/
@Override
public void add(int index, T element) {
if(length == array.length) increaseArraySize();
array[index] = element;
length++;
}
/**
* Add a new element to the array at the end
* of the array
* @param element new value to add at the end
* @return if element is added
*/
@Override
public boolean add(T element) {
if(length == array.length) increaseArraySize();
array[length++] = element;
return true;
}
/**
* Internal function to increase the array if
* there are no more free positions
*/
@SuppressWarnings("unchecked")
private void increaseArraySize() {
T[] old = array;
array = (T[]) new Object[old.length*2+1];
System.arraycopy(old, 0, array, 0, old.length);
}
/**
* Return the attribute array
* @return array containing all the arrayList values
*/
@Override
public Object[] toArray() {
return array;
}
/**
* Used because the toArray below can't be changed
* @param i random
* @return array representation
*/
@SuppressWarnings("UnusedParameters")
@WrittenWhile("Way too late")
public T[] toArray(int i) {
//noinspection unchecked
return array;
}
/**
* Return the attribute array casted to T
* @param a I Really don't know
* @return casted array
*/
@SuppressWarnings("unchecked")
@Override
public T[] toArray(Object[] a) {
return array;
}
/**
* Remove a custom element using index
* @param index position to remove
* @return removed element
*/
@Override
public T remove(int index) {
if(isEmpty()) return null;
T removed = array[index];
//noinspection ManualArrayCopy
for(int i = index+1; i < length; i++) {
array[i-1] = array[i];
}
length--;
return removed;
}
/**
* Used to reset the array and make it empty.
*/
@SuppressWarnings("unchecked")
@Override
public void clear() {
array = (T[]) new Object[3];
length = 0;
}
/**
* Print all array elements as a single String
* @return string containing all array elements
*/
@Override
public String toString() {
String result = " ";
for(int i = 0; i < array.length; i ++) {
if( "".equals( get(i).toString() ) ) continue;
result += " ["+ get(i) +"],";
}
return result.substring(0, result.length()-1);
}
@SuppressWarnings("unchecked")
@Override
public Iterator iterator() {
return new MyIterator(this);
}
/*----------------------------------------------*/
@Override
public boolean remove(Object o) {
return false;
}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public boolean addAll(Collection c) {
return false;
}
@Override
public boolean addAll(int index, Collection c) {
return false;
}
@Override
public int indexOf(Object o) {
return 0;
}
@Override
public int lastIndexOf(Object o) {
return 0;
}
@SuppressWarnings("unchecked")
@Override
public ListIterator listIterator() {
return null;
}
@SuppressWarnings("unchecked")
@Override
public ListIterator listIterator(int index) {
return null;
}
@SuppressWarnings("unchecked")
@Override
public List subList(int fromIndex, int toIndex) {
return null;
}
@Override
public boolean retainAll(Collection c) {
return false;
}
@Override
public boolean removeAll(Collection c) {
return false;
}
@Override
public boolean containsAll(Collection c) {
return false;
}
}
| gpl-2.0 |
proyectos-fiuba-romera/nilledom | src/test/java/test/mdauml/umldraw/shared/NoteElementTest.java | 2826 | /**
* Copyright 2007 Wei-ju Wu
*
* This file is part of TinyUML.
*
* TinyUML 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.
*
* TinyUML 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 TinyUML; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package test.mdauml.umldraw.shared;
import org.jmock.Mock;
import org.jmock.cglib.MockObjectTestCase;
import com.nilledom.draw.CompositeNode;
import com.nilledom.model.RelationEndType;
import com.nilledom.model.RelationType;
import com.nilledom.model.UmlRelation;
import com.nilledom.umldraw.clazz.ClassElement;
import com.nilledom.umldraw.shared.NoteConnection;
import com.nilledom.umldraw.shared.NoteElement;
/**
* A test class for NoteElement.
* @author Wei-ju Wu
* @version 1.0
*/
public class NoteElementTest extends MockObjectTestCase {
/**
* Tests the clone() method.
*/
public void testClone() {
Mock mockParent1 = mock(CompositeNode.class);
NoteElement note = NoteElement.getPrototype();
assertNull(note.getParent());
assertNull(note.getModelElement());
note.setOrigin(0, 0);
note.setSize(100, 80);
note.setLabelText("oldlabel");
note.setParent((CompositeNode) mockParent1.proxy());
NoteElement cloned = (NoteElement) note.clone();
assertTrue(note != cloned);
assertEquals(note.getParent(), cloned.getParent());
assertEquals("oldlabel", cloned.getLabelText());
note.setLabelText("mylabel");
assertFalse(cloned.getLabelText() == note.getLabelText());
// now test the label
mockParent1.expects(atLeastOnce()).method("getAbsoluteX1")
.will(returnValue(0.0));
mockParent1.expects(atLeastOnce()).method("getAbsoluteY1")
.will(returnValue(0.0));
assertNotNull(cloned.getLabelAt(20, 20));
assertNull(cloned.getLabelAt(-1.0, -2.0));
assertTrue(cloned.getLabelAt(20.0, 20.0) != note.getLabelAt(20.0, 20.0));
assertTrue(cloned.getLabelAt(20.0, 20.0).getSource() == cloned);
assertTrue(cloned.getLabelAt(20.0, 20.0).getParent() == cloned);
}
/**
* Tests the NoteConnection class.
*/
public void testNoteConnection() {
// relation has no effect
NoteConnection connection = NoteConnection.getPrototype();
connection.setRelation(new UmlRelation());
assertNull(connection.getModelElement());
}
}
| gpl-2.0 |
Icenowy/metatheme | toolkits/java/metatheme/MetaThemeMenuItemUI.java | 6011 | /*
* This file is part of MetaTheme.
* Copyright (c) 2004 Martin Dvorak <jezek2@advel.cz>
*
* MetaTheme 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.
*
* MetaTheme 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 MetaTheme; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package metatheme;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicMenuItemUI;
import javax.swing.plaf.basic.BasicGraphicsUtils;
public class MetaThemeMenuItemUI extends BasicMenuItemUI implements MT {
private ThemeEngine engine;
private JMenuItem mi;
private int type;
public MetaThemeMenuItemUI(JMenuItem i) {
super();
engine = ThemeEngine.get();
mi = i;
type = MT_MENU_ITEM;
if (mi instanceof JCheckBoxMenuItem) {
type = MT_MENU_ITEM_CHECK;
}
else if (mi instanceof JRadioButtonMenuItem) {
type = MT_MENU_ITEM_RADIO;
}
else if (mi instanceof JMenu) {
type = MT_MENU_ITEM_ARROW;
}
}
public static ComponentUI createUI(JComponent c) {
return new MetaThemeMenuItemUI((JMenuItem)c);
}
protected void paintMenuItem(Graphics g, JComponent c,
Icon checkIcon, Icon arrowIcon,
Color background, Color foreground,
int defaultTextIconGap) {
JMenuItem menuItem = (JMenuItem)c;
ButtonModel model = menuItem.getModel();
int x,y;
int maxpmw = 16;
Font font = menuItem.getFont();
FontMetrics fm = menuItem.getFontMetrics(font);
int state = Utils.getState(menuItem);
paintBackground(g, menuItem, null);
Icon icon = menuItem.getIcon();
if (icon != null) {
if (icon.getIconWidth() > maxpmw) {
maxpmw = icon.getIconWidth();
}
if ((state & MT_DISABLED) != 0) {
icon = (Icon)menuItem.getDisabledIcon();
}
else if (model.isPressed() && model.isArmed()) {
icon = (Icon)menuItem.getPressedIcon();
if (icon == null) {
icon = (Icon)menuItem.getIcon();
}
} else {
icon = (Icon)menuItem.getIcon();
}
}
if (type == MT_MENU_ITEM_CHECK || type == MT_MENU_ITEM_RADIO) {
if ((state & MT_ACTIVE) != 0) {
x = engine.metricSize[MT_MENU_BORDER].width;
y = engine.metricSize[MT_MENU_BORDER].height;
engine.drawWidget(g, type, state, x, y, maxpmw, menuItem.getHeight() - 2*y, c);
}
}
else {
if (icon != null) {
y = (menuItem.getHeight() - icon.getIconHeight() - 1) / 2;
icon.paintIcon(menuItem, g, engine.metricSize[MT_MENU_ITEM_BORDER].width, y);
}
}
String text = menuItem.getText();
if (text != null) {
g.setFont(font);
paintText(g, menuItem, new Rectangle(0, 0, menuItem.getWidth(), menuItem.getHeight()), text);
}
KeyStroke accelerator = menuItem.getAccelerator();
String acceleratorText = "";
if (accelerator != null) {
int modifiers = accelerator.getModifiers();
if (modifiers > 0) {
acceleratorText = KeyEvent.getKeyModifiersText(modifiers);
acceleratorText += /*acceleratorDelimiter*/"-";
}
int keyCode = accelerator.getKeyCode();
if (keyCode != 0) {
acceleratorText += KeyEvent.getKeyText(keyCode);
} else {
acceleratorText += accelerator.getKeyChar();
}
}
if (acceleratorText != null && !acceleratorText.equals("")) {
x = menuItem.getWidth() - engine.metricSize[MT_MENU_ITEM_BORDER].width - 3;
y = (menuItem.getHeight() - fm.getHeight() + 1) / 2;
x -= SwingUtilities.computeStringWidth(fm, acceleratorText);
g.setFont(font);
engine.drawString(g, MT_MENU_ITEM, state, x, y, acceleratorText, engine.palette[Utils.getTextColor(state, MT_FOREGROUND, true)], -1);
}
if (type == MT_MENU_ITEM_ARROW) {
x = menuItem.getWidth() - 1 - engine.metricSize[MT_MENU_ITEM_BORDER].width - 8;
y = engine.metricSize[MT_MENU_ITEM_BORDER].height;
engine.drawWidget(g, MT_MENU_ITEM_ARROW, state, x, y, 8, menuItem.getHeight() - 2*y, c);
}
}
protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) {
Dimension size = menuItem.getSize();
int state = Utils.getState(menuItem);
Color oldColor = g.getColor();
engine.drawWidget(g, MT_MENU_ITEM, state, 0, 0, size.width, size.height, menuItem);
g.setColor(oldColor);
}
protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) {
FontMetrics fm = g.getFontMetrics();
int mnemIndex = menuItem.getDisplayedMnemonicIndex();
int state = Utils.getState(menuItem);
Rectangle tr = new Rectangle(textRect);
int maxpmw = 16;
Icon icon = menuItem.getIcon();
if (icon != null && icon.getIconWidth() > maxpmw) maxpmw = icon.getIconWidth();
tr.x += engine.metricSize[MT_MENU_ITEM_BORDER].width + maxpmw + 3;
tr.y += (tr.height - fm.getHeight() + 1) / 2;
int sc = MT_FOREGROUND;
if ((state & MT_SELECTED) != 0) sc = MT_SELECTED_FOREGROUND;
engine.drawString(g, MT_MENU_ITEM, state, tr.x, tr.y, text, engine.palette[Utils.getTextColor(state, MT_FOREGROUND, true)], mnemIndex);
}
protected Dimension getPreferredMenuItemSize(JComponent c, Icon checkIcon, Icon arrowIcon, int defaultTextIconGap) {
Dimension d = super.getPreferredMenuItemSize(c, checkIcon, arrowIcon, defaultTextIconGap);
if (d.height <= 18) d.height -= 3;
d.width += engine.metricSize[MT_MENU_ITEM_BORDER].width * 2;
d.height += engine.metricSize[MT_MENU_ITEM_BORDER].height * 2;
if (d.height < 18) d.height = 18;
return d;
}
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/pm/fsub_ST5_ST1.java | 2064 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 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 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.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.pm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class fsub_ST5_ST1 extends Executable
{
public fsub_ST5_ST1(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(5);
double freg1 = cpu.fpu.ST(1);
if ((freg0 == Double.NEGATIVE_INFINITY && freg1 == Double.NEGATIVE_INFINITY) || (freg0 == Double.POSITIVE_INFINITY && freg1 == Double.POSITIVE_INFINITY))
cpu.fpu.setInvalidOperation();
cpu.fpu.setST(5, freg0-freg1);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
Dasfaust/WebMarket | src/main/java/com/survivorserver/Dasfaust/WebMarket/mojang/http/HttpBody.java | 316 | package com.survivorserver.Dasfaust.WebMarket.mojang.http;
public class HttpBody {
private String bodyString;
public HttpBody(String bodyString) {
this.bodyString = bodyString;
}
public byte[] getBytes() {
return bodyString != null ? bodyString.getBytes() : new byte[0];
}
}
| gpl-2.0 |
Contourdynamics/smartcommunication | src/org/contourdynamics/cms/repository/StatusCodeRepos.java | 792 | package org.contourdynamics.cms.repository;
import javax.enterprise.context.ApplicationScoped;
import org.apache.deltaspike.data.api.EntityManagerConfig;
import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Repository;
import org.apache.deltaspike.data.api.AbstractEntityRepository;
import org.contourdynamics.cms.Entities.BpCmpy;
import org.contourdynamics.cms.Entities.StatusCode;
import org.contourdynamics.cms.producers.MainEMResolver;
@ApplicationScoped
@Repository(forEntity = StatusCode.class)
@EntityManagerConfig(entityManagerResolver = MainEMResolver.class)
public interface StatusCodeRepos extends EntityRepository<StatusCode, Integer> {
//public abstract class StatusCodeRepos extends AbstractEntityRepository<StatusCode, Integer> {
}
| gpl-2.0 |
specify/specify6 | src/edu/ku/brc/specify/tools/schemalocale/SchemaLocalizerDlg.java | 43764 | /* Copyright (C) 2022, Specify Collections Consortium
*
* Specify Collections Consortium, Biodiversity Institute, University of Kansas,
* 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package edu.ku.brc.specify.tools.schemalocale;
import static edu.ku.brc.ui.UIRegistry.getResourceString;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterIFace;
import edu.ku.brc.specify.conversion.BasicSQLUtils;
import edu.ku.brc.specify.datamodel.*;
import edu.ku.brc.specify.datamodel.Collection;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import edu.ku.brc.af.core.AppContextMgr;
import edu.ku.brc.af.core.SchemaI18NService;
import edu.ku.brc.af.core.db.DBTableIdMgr;
import edu.ku.brc.af.core.expresssearch.QueryAdjusterForDomain;
import edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr;
import edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr;
import edu.ku.brc.af.ui.weblink.WebLinkMgr;
import edu.ku.brc.dbsupport.DBConnection;
import edu.ku.brc.dbsupport.DataProviderFactory;
import edu.ku.brc.dbsupport.DataProviderSessionIFace;
import edu.ku.brc.dbsupport.HibernateUtil;
import edu.ku.brc.helpers.SwingWorker;
import edu.ku.brc.specify.config.SpecifyAppContextMgr;
import edu.ku.brc.specify.config.SpecifyWebLinkMgr;
import edu.ku.brc.ui.CommandAction;
import edu.ku.brc.ui.CommandDispatcher;
import edu.ku.brc.ui.CustomDialog;
import edu.ku.brc.ui.ToggleButtonChooserDlg;
import edu.ku.brc.ui.ToggleButtonChooserPanel;
import edu.ku.brc.ui.UIRegistry;
import edu.ku.brc.ui.dnd.SimpleGlassPane;
import javax.persistence.Basic;
/**
* @author rods
*
* @code_status Alpha
*
* Created Date: Sep 27, 2007
*
*/
public class SchemaLocalizerDlg extends CustomDialog implements LocalizableIOIFace, PropertyChangeListener
{
private static final Logger log = Logger.getLogger(SchemaLocalizerDlg.class);
//CommandAction stuff
public final static String SCHEMA_LOCALIZER = "SCHEMA_LOCALIZER";
private static String SCHEMALOCDLG = "SchemaLocalizerDlg";
protected Byte schemaType;
protected DBTableIdMgr tableMgr;
// used to hold changes to formatters before committing them to DB
protected DataObjFieldFormatMgr dataObjFieldFormatMgrCache = new DataObjFieldFormatMgr(DataObjFieldFormatMgr.getInstance());
protected UIFieldFormatterMgr uiFieldFormatterMgrCache = new UIFieldFormatterMgr(UIFieldFormatterMgr.getInstance());
protected SpecifyWebLinkMgr webLinkMgrCache = new SpecifyWebLinkMgr((SpecifyWebLinkMgr)WebLinkMgr.getInstance());
protected SchemaLocalizerPanel schemaLocPanel;
protected LocalizableIOIFace localizableIOIFace;
protected LocalizableStrFactory localizableStrFactory;
protected Vector<SpLocaleContainer> tables = new Vector<SpLocaleContainer>();
protected Hashtable<Integer, LocalizableContainerIFace> tableHash = new Hashtable<Integer, LocalizableContainerIFace>();
protected Vector<SpLocaleContainer> changedTables = new Vector<SpLocaleContainer>();
protected Hashtable<Integer, LocalizableContainerIFace> changedTableHash = new Hashtable<Integer, LocalizableContainerIFace>();
protected Vector<LocalizableJListItem> tableDisplayItems;
protected Hashtable<String, LocalizableJListItem> tableDisplayItemsHash = new Hashtable<String, LocalizableJListItem>();
protected Hashtable<LocalizableJListItem, Vector<LocalizableJListItem>> itemJListItemsHash = new Hashtable<LocalizableJListItem, Vector<LocalizableJListItem>>();
// Used for Copying Locales
protected Vector<LocalizableStrIFace> namesList = new Vector<LocalizableStrIFace>();
protected Vector<LocalizableStrIFace> descsList = new Vector<LocalizableStrIFace>();
protected List<PickList> pickLists = null;
protected boolean wasSaved = false;
/**
* @param frame
* @param schemaType
* @throws HeadlessException
*/
public SchemaLocalizerDlg(final Frame frame,
final Byte schemaType,
final DBTableIdMgr tableMgr) throws HeadlessException
{
//super(frame, "", true, OKCANCELAPPLYHELP, null);
super(frame, "", true, OKCANCELHELP, null);
this.schemaType = schemaType;
this.tableMgr = tableMgr;
if (schemaType == SpLocaleContainer.WORKBENCH_SCHEMA)
{
helpContext = "wb_schema_config";
} else
{
helpContext = "SL_HELP_CONTEXT";
}
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.CustomDialog#createUI()
*/
@Override
public void createUI()
{
setApplyLabel(getResourceString("SL_CHANGE_LOCALE"));
super.createUI();
localizableStrFactory = new LocalizableStrFactory() {
public LocalizableStrIFace create()
{
SpLocaleItemStr str = new SpLocaleItemStr();
str.initialize();
return str;
}
public LocalizableStrIFace create(String text, Locale locale)
{
return new SpLocaleItemStr(text, locale); // no initialize needed for this constructor
}
};
LocalizerBasePanel.setLocalizableStrFactory(localizableStrFactory);
//DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
//List<SpLocaleContainer> list = session.getDataList(SpLocaleContainer.class);
localizableIOIFace = this;
localizableIOIFace.load(true);
schemaLocPanel = new SchemaLocalizerPanel(this, dataObjFieldFormatMgrCache, uiFieldFormatterMgrCache, webLinkMgrCache, schemaType);
schemaLocPanel.setLocalizableIO(localizableIOIFace);
schemaLocPanel.setUseDisciplines(false);
okBtn.setEnabled(false);
schemaLocPanel.setSaveBtn(okBtn);
schemaLocPanel.setStatusBar(UIRegistry.getStatusBar());
schemaLocPanel.buildUI();
schemaLocPanel.setHasChanged(localizableIOIFace.didModelChangeDuringLoad());
contentPanel = schemaLocPanel;
mainPanel.add(contentPanel, BorderLayout.CENTER);
setTitle();
pack();
}
/**
*
*/
public void setTitle()
{
if (schemaType == SpLocaleContainer.WORKBENCH_SCHEMA)
{
super.setTitle(getResourceString("WBSCHEMA_CONFIG") +" - " + SchemaI18NService.getCurrentLocale().getDisplayName());
} else
{
super.setTitle(getResourceString("SCHEMA_CONFIG") +" - " + SchemaI18NService.getCurrentLocale().getDisplayName());
}
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.CustomDialog#okButtonPressed()
*/
@Override
protected void okButtonPressed()
{
saveAndShutdown();
}
/**
*
*/
protected void finishedSaving()
{
super.okButtonPressed();
}
/**
* Saves the changes.
*/
protected void saveAndShutdown()
{
// Check to make sure whether the current container has changes.
if (schemaLocPanel.hasTableInfoChanged() && schemaLocPanel.getCurrentContainer() != null)
{
localizableIOIFace.containerChanged(schemaLocPanel.getCurrentContainer());
}
schemaLocPanel.setSaveBtn(null);
enabledDlgBtns(false);
UIRegistry.getStatusBar().setText(getResourceString("SL_SAVING_SCHEMA_LOC"));
UIRegistry.getStatusBar().setIndeterminate(SCHEMALOCDLG, true);
final SimpleGlassPane glassPane = new SimpleGlassPane(getResourceString("SchemaLocalizerFrame.SAVING"), 18);
setGlassPane(glassPane);
glassPane.setVisible(true);
getOkBtn().setEnabled(false);
SwingWorker workerThread = new SwingWorker()
{
@Override
public Object construct()
{
int disciplineeId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId();
String accNumFormatSql = "select ci.format from splocalecontaineritem ci inner join splocalecontainer c "
+ " on c.splocalecontainerid = ci.splocalecontainerid where ci.name = 'accessionNumber' "
+ " and c.name = 'accession' and c.disciplineid = " + disciplineeId;
String accNumFormat = BasicSQLUtils.querySingleObj(accNumFormatSql);
save();
String newAccNumFormat = BasicSQLUtils.querySingleObj(accNumFormatSql);
if (newAccNumFormat != null && !newAccNumFormat.equals(accNumFormat)) {
updateAccAutoNumberingTbls(newAccNumFormat, accNumFormat);
} else if (newAccNumFormat == null && accNumFormat != null) {
clearAccAutoNumberingTbls();
}
//SchemaI18NService.getInstance().loadWithLocale(new Locale("de", "", ""));
SchemaI18NService.getInstance().loadWithLocale(schemaType, disciplineeId, tableMgr, Locale.getDefault());
SpecifyAppContextMgr.getInstance().setForceReloadViews(true);
UIFieldFormatterMgr.getInstance().load();
WebLinkMgr.getInstance().reload();
DataObjFieldFormatMgr.getInstance().load();
return null;
}
private void clearAccAutoNumberingTbls() {
int divId = AppContextMgr.getInstance().getClassObject(Division.class).getDivisionId();
String sql = "delete from autonumsch_div where divisionid = " + divId;
BasicSQLUtils.update(sql);
if (!BasicSQLUtils.getCount("select count(*) from autonumsch_div where divisionid = " + divId).equals(0)) {
log.error("error executing sql: " + sql);
}
}
private void updateAccAutoNumberingTbls(final String newAccNumFormat, final String oldAccNumFormat) {
//System.out.println("Updating AutoNumbering Tables");
UIFieldFormatterIFace newF = UIFieldFormatterMgr.getInstance().getFormatter(newAccNumFormat);
boolean isNumericOnly = newF == null ? false : newF.isNumeric();
boolean isIncrementer = newF == null ? false : newF.isIncrementer();
if (isIncrementer) {
int divId = AppContextMgr.getInstance().getClassObject(Division.class).getDivisionId();
Integer autoNumSchemeIdNewFmt = BasicSQLUtils.querySingleObj("select autonumberingschemeid from autonumberingscheme where tablenumber = 7 and formatname = '" + newAccNumFormat + "' limit 1");
Integer autoNumSchemeIdOldFmt = BasicSQLUtils.querySingleObj("select autonumberingschemeid from autonumberingscheme where tablenumber = 7 and formatname = '" + oldAccNumFormat + "' limit 1");
List<String> sqls = new ArrayList<>();
if (autoNumSchemeIdNewFmt == null) {
sqls.add("insert into autonumberingscheme(TimestampCreated,TimestampModified,Version,FormatName,IsNumericOnly,SchemeClassName,SchemeName,TableNumber)"
+ "values(now(), now(), 0, '" + newAccNumFormat + "', " + (isNumericOnly ? "true" : "false") + ", '', 'Accession Numbering Scheme', 7)");
}
boolean addDiv = autoNumSchemeIdNewFmt == null;
if (!addDiv) {
List<Object> newFmtDivs = BasicSQLUtils.querySingleCol("select divisionid from autonumsch_div where autonumberingschemeid =" + autoNumSchemeIdNewFmt);
addDiv = true;
for (Object div : newFmtDivs) {
if (div.equals(divId)) {
addDiv = false;
break;
}
}
}
if (addDiv) {
sqls.add("insert into autonumsch_div(DivisionID, AutoNumberingSchemeID)"
+ "values(" + divId + ",(select autonumberingschemeid from autonumberingscheme where tablenumber = 7 and formatname = '" + newAccNumFormat + "'))");
}
if (autoNumSchemeIdOldFmt != null) {
List<Object> oldFmtDivs = BasicSQLUtils.querySingleCol("select divisionid from autonumsch_div where autonumberingschemeid =" + autoNumSchemeIdOldFmt);
boolean removeDiv = false;
boolean removeAns = true;
for (Object div : oldFmtDivs) {
if (div.equals(divId)) {
removeDiv = true;
} else {
removeAns = false;
}
}
if (removeDiv) {
sqls.add("delete from autonumsch_div where divisionid = " + divId + " and autonumberingschemeid = " + autoNumSchemeIdOldFmt);
}
if (removeAns) {
sqls.add("delete from autonumberingscheme where autonumberingschemeid = " + autoNumSchemeIdOldFmt);
}
}
for (String sql : sqls) {
int result = BasicSQLUtils.update(sql);
if (result != 1) {
log.error("error executing sql: " + sql);
}
}
}
}
@Override
public void finished()
{
glassPane.setVisible(false);
enabledDlgBtns(true);
UIRegistry.getStatusBar().setProgressDone(SCHEMALOCDLG);
UIRegistry.getStatusBar().setText("");
finishedSaving();
}
};
// start the background task
workerThread.start();
}
/**
* @return
*/
public boolean wasSaved()
{
return wasSaved;
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.CustomDialog#applyButtonPressed()
*/
@Override
protected void applyButtonPressed()
{
Vector<DisplayLocale> list = new Vector<DisplayLocale>();
for (Locale locale : Locale.getAvailableLocales())
{
if (StringUtils.isEmpty(locale.getCountry()))
{
list.add(new DisplayLocale(locale));
}
}
Collections.sort(list);
ToggleButtonChooserDlg<DisplayLocale> dlg = new ToggleButtonChooserDlg<DisplayLocale>((Dialog)null,
"CHOOSE_LOCALE", list, ToggleButtonChooserPanel.Type.RadioButton);
dlg.setUseScrollPane(true);
dlg.setVisible(true);
if (!dlg.isCancelled())
{
schemaLocPanel.localeChanged(dlg.getSelectedObject().getLocale());
setTitle();
}
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#createResourceFiles()
*/
@Override
public boolean createResourceFiles()
{
return false;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#didModelChangeDuringLoad()
*/
@Override
public boolean didModelChangeDuringLoad()
{
return false;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getContainerDisplayItems()
*/
@Override
public Vector<LocalizableJListItem> getContainerDisplayItems()
{
final String ATTACHMENT = "attachment";
Connection connection = null;
Statement stmt = null;
ResultSet rs = null;
try
{
tableDisplayItems = new Vector<LocalizableJListItem>();
int dispId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId();
String sql = String.format("SELECT SpLocaleContainerID, Name FROM splocalecontainer WHERE DisciplineID = %d AND SchemaType = %d ORDER BY Name", dispId, schemaType);
connection = DBConnection.getInstance().createConnection();
stmt = connection.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next())
{
String tblName = rs.getString(2);
boolean isAttachment = false;//(tblName.startsWith(ATTACHMENT) || tblName.endsWith(ATTACHMENT)) && !tblName.equals(ATTACHMENT);
boolean isAuditLogTbl = "spauditlog".equalsIgnoreCase(tblName) || "spauditlogfield".equalsIgnoreCase(tblName);
System.out.println(tblName+" "+isAttachment);
if (shouldIncludeAppTables() || isAuditLogTbl ||
!(tblName.startsWith("sp") ||
isAttachment ||
tblName.startsWith("autonum") ||
tblName.equals("picklist") ||
tblName.equals("attributedef") ||
tblName.equals("recordset") ||
//tblName.equals("inforequest") ||
tblName.startsWith("workbench") ||
tblName.endsWith("treedef") ||
tblName.endsWith("treedefitem") ||
tblName.endsWith("attr") ||
tblName.endsWith("reltype")))
{
tableDisplayItems.add(new LocalizableJListItem(rs.getString(2), rs.getInt(1), null));
}
}
} catch (Exception ex)
{
ex.printStackTrace();
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex);
} finally
{
try
{
if (rs != null)
{
rs.close();
}
if (stmt != null)
{
stmt.close();
}
if (connection != null)
{
connection.close();
}
} catch (Exception e)
{
e.printStackTrace();
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, e);
}
}
return tableDisplayItems;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getContainer(edu.ku.brc.specify.tools.schemalocale.LocalizableJListItem, edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFaceListener)
*/
@Override
public LocalizableContainerIFace getContainer(LocalizableJListItem item, LocalizableIOIFaceListener l)
{
loadTable(item.getId(), item.getName(), l);
return null;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getDisplayItems(edu.ku.brc.specify.tools.schemalocale.LocalizableJListItem)
*/
@Override
public Vector<LocalizableJListItem> getDisplayItems(LocalizableJListItem containerArg)
{
Vector<LocalizableJListItem> items = itemJListItemsHash.get(containerArg);
if (items == null)
{
LocalizableContainerIFace cont = tableHash.get(containerArg.getId());
if (cont != null)
{
SpLocaleContainer container = (SpLocaleContainer)cont;
items = new Vector<LocalizableJListItem>();
for (LocalizableItemIFace item : container.getContainerItems())
{
SpLocaleContainerItem cItem = (SpLocaleContainerItem)item;
cItem.getNames();
cItem.getDescs();
items.add(new LocalizableJListItem(cItem.getName(), cItem.getId(), null));
}
itemJListItemsHash.put(containerArg, items);
Collections.sort(items);
} else
{
log.error("Couldn't find container ["+containerArg.getName()+"]");
}
}
return items;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getItem(edu.ku.brc.specify.tools.schemalocale.LocalizableContainerIFace, edu.ku.brc.specify.tools.schemalocale.LocalizableJListItem)
*/
@Override
public LocalizableItemIFace getItem(LocalizableContainerIFace containerArg, LocalizableJListItem item)
{
SpLocaleContainer container = (SpLocaleContainer)containerArg;
// Make sure the items are loaded before getting them.
if (container != null)
{
for (LocalizableItemIFace cItem : container.getItems())
{
if (cItem.getName().equals(item.getName()))
{
return cItem;
}
}
} else
{
log.error("Couldn't merge container ["+containerArg.getName()+"]");
}
return null;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#load(boolean)
*/
@Override
public boolean load(final boolean useCurrentLocaleOnly)
{
enabledDlgBtns(true);
return true;
}
/**
* @param sessionArg
* @param containerId
* @return
*/
protected SpLocaleContainer loadTable(final DataProviderSessionIFace sessionArg,
final int containerId)
{
SpLocaleContainer container = null;
DataProviderSessionIFace session = null;
try
{
session = sessionArg != null ? sessionArg : DataProviderFactory.getInstance().createSession();
int dispId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId();
String sql = String.format("FROM SpLocaleContainer WHERE disciplineId = %d AND spLocaleContainerId = %d", dispId, containerId);
container = (SpLocaleContainer)session.getData(sql);
tables.add(container);
tableHash.put(container.getId(), container);
for (SpLocaleContainerItem item : container.getItems())
{
// force Load of lazy collections
container.getDescs().size();
container.getNames().size();
item.getDescs().size();
item.getNames().size();
}
return container;
} catch (Exception e)
{
e.printStackTrace();
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, e);
} finally
{
if (session != null && sessionArg == null)
{
session.close();
}
}
return null;
}
/**
* @param containerId
*/
protected void loadTable(final int containerId,
final String name,
final LocalizableIOIFaceListener l)
{
LocalizableContainerIFace cntr = tableHash.get(containerId);
if (cntr != null)
{
l.containterRetrieved(cntr);
return;
}
UIRegistry.getStatusBar().setIndeterminate(name, true);
UIRegistry.getStatusBar().setText(UIRegistry.getResourceString("LOADING_SCHEMA"));
enabledDlgBtns(false);
schemaLocPanel.enableUIControls(false);
SwingWorker workerThread = new SwingWorker()
{
protected SpLocaleContainer container = null;
@Override
public Object construct()
{
container = loadTable(null, containerId);
return null;
}
@Override
public void finished()
{
l.containterRetrieved(container);
enabledDlgBtns(true);
//schemaLocPanel.enableUIControls(true);
UIRegistry.getStatusBar().setProgressDone(name);
UIRegistry.getStatusBar().setText("");
schemaLocPanel.getContainerList().setEnabled(true);
}
};
// start the background task
workerThread.start();
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#save()
*/
@Override
public boolean save()
{
schemaLocPanel.getAllDataFromUI();
SimpleGlassPane glassPane = (SimpleGlassPane)getGlassPane();
if (glassPane != null)
{
glassPane.setProgress(0);
}
// apply changes to formatters and save them to db
DataObjFieldFormatMgr.getInstance().applyChanges(dataObjFieldFormatMgrCache);
UIFieldFormatterMgr.getInstance().applyChanges(uiFieldFormatterMgrCache);
WebLinkMgr.getInstance().applyChanges(webLinkMgrCache);
if (changedTables.size() > 0)
{
DataProviderSessionIFace session = null;
try
{
session = DataProviderFactory.getInstance().createSession();
double step = 100.0 / (double)changedTables.size();
double total = 0.0;
session.beginTransaction();
for (SpLocaleContainer container : changedTables)
{
SpLocaleContainer dbContainer = session.merge(container);
session.saveOrUpdate(dbContainer);
for (SpLocaleItemStr str : dbContainer.getNames())
{
session.saveOrUpdate(session.merge(str));
//System.out.println(c.getName()+" - "+str.getText());
}
for (SpLocaleItemStr str : dbContainer.getDescs())
{
session.saveOrUpdate(session.merge(str));
//System.out.println(c.getName()+" - "+str.getText());
}
for (SpLocaleContainerItem item : dbContainer.getItems())
{
SpLocaleContainerItem i = session.merge(item);
session.saveOrUpdate(i);
for (SpLocaleItemStr str : i.getNames())
{
session.saveOrUpdate(session.merge(str));
//System.out.println(i.getName()+" - "+str.getText());
}
for (SpLocaleItemStr str : i.getDescs())
{
session.saveOrUpdate(session.merge(str));
//System.out.println(i.getName()+" - "+str.getText());
}
}
total += step;
System.err.println(total+" "+step);
if (glassPane != null)
{
glassPane.setProgress((int)total);
}
}
session.commit();
session.flush();
if (glassPane != null)
{
glassPane.setProgress(100);
}
} catch (Exception ex)
{
ex.printStackTrace();
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex);
} finally
{
if (session != null)
{
session.close();
}
}
//notify app of localizer changes
CommandAction cmd = new CommandAction(SCHEMA_LOCALIZER, SCHEMA_LOCALIZER, null);
CommandDispatcher.dispatch(cmd);
} else
{
log.warn("No Changes were saved!");
}
return true;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#containerChanged(edu.ku.brc.specify.tools.schemalocale.LocalizableContainerIFace)
*/
@Override
public void containerChanged(LocalizableContainerIFace container)
{
if (container instanceof SpLocaleContainer)
{
if (changedTableHash.get(container.getId()) == null)
{
changedTables.add((SpLocaleContainer)container);
changedTableHash.put(container.getId(), container);
}
}
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#isLocaleInUse(java.util.Locale)
*/
@Override
public boolean isLocaleInUse(final Locale locale)
{
// First check the aDatabase because the extra locales are not loaded automatically.
if (isLocaleInUseInDB(schemaType, locale))
{
return true;
}
// Now check memory
Hashtable<String, Boolean> localeHash = new Hashtable<String, Boolean>();
for (SpLocaleContainer container : tables)
{
SchemaLocalizerXMLHelper.checkForLocales(container, localeHash);
for (LocalizableItemIFace f : container.getContainerItems())
{
SchemaLocalizerXMLHelper.checkForLocales(f, localeHash);
}
}
return localeHash.get(SchemaLocalizerXMLHelper.makeLocaleKey(locale)) != null;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getLocalesInUse()
*/
@Override
public Vector<Locale> getLocalesInUse()
{
Hashtable<String, Boolean> localeHash = new Hashtable<String, Boolean>();
// Add any from the Database
Vector<Locale> localeList = getLocalesInUseInDB(schemaType);
for (Locale locale : localeList)
{
localeHash.put(SchemaLocalizerXMLHelper.makeLocaleKey(locale.getLanguage(), locale.getCountry(), locale.getVariant()), true);
}
for (SpLocaleContainer container : tables)
{
SchemaLocalizerXMLHelper.checkForLocales(container, localeHash);
for (LocalizableItemIFace f : container.getContainerItems())
{
SchemaLocalizerXMLHelper.checkForLocales(f, localeHash);
}
}
localeList.clear();
for (String key : localeHash.keySet())
{
String[] toks = StringUtils.split(key, "_");
localeList.add(new Locale(toks[0], "", ""));
}
return localeList;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#shouldIncludeAppTables()
*/
@Override
public boolean shouldIncludeAppTables()
{
return false;
}
/**
* Return the locales in the database
* @return the list of locale
*/
public static Vector<Locale> getLocalesInUseInDB(final Byte schemaType) {
Vector<Locale> locales = new Vector<>();
String sql = "SELECT DISTINCT nms.language, trim(ifnull(nms.country,'')) FROM splocalecontainer ctn " +
"INNER JOIN splocalecontaineritem itm on itm.splocalecontainerid = ctn.splocalecontainerid " +
"INNER JOIN splocaleitemstr nms on nms.splocalecontaineritemnameid = itm.splocalecontaineritemid " +
"WHERE ctn.disciplineid = " + AppContextMgr.getInstance().getClassObject(Discipline.class).getId() +
" AND nms.language IS NOT NULL AND ctn.schemaType = " + schemaType;
log.debug(sql);
List<Object[]> list = BasicSQLUtils.query(sql);
for (Object[] lang : list) {
String language = lang[0].toString();
String country = lang[1] == null ? "" : lang[1].toString();
locales.add(new Locale(language, country, ""));
}
return locales;
}
/**
* Check the Database to see if the Locale is being used.
* @param schemaTypeArg the which set of locales
* @param locale the locale in question
* @return true/false
*/
public boolean isLocaleInUseInDB(final Byte schemaTypeArg, final Locale locale)
{
Session session = HibernateUtil.getNewSession();
try
{
String sql = String.format("SELECT DISTINCT nms.language FROM SpLocaleContainer as ctn " +
"INNER JOIN ctn.items as itm " +
"INNER JOIN itm.names nms " +
"INNER JOIN ctn.discipline as d " +
"WHERE d.userGroupScopeId = DSPLNID AND nms.language = '%s' AND ctn.schemaType = %d",
locale.getLanguage(), schemaTypeArg);
sql = QueryAdjusterForDomain.getInstance().adjustSQL(sql);
Query query = session.createQuery(sql);
List<?> list = query.list();
return list.size() > 0;
} catch (Exception ex)
{
ex.printStackTrace();
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex);
} finally
{
session.close();
}
return false;
}
/**
* @param enable
*/
protected void enabledDlgBtns(final boolean enable)
{
okBtn.setEnabled(enable ? (schemaLocPanel != null ? schemaLocPanel.hasChanged() : false) : false);
cancelBtn.setEnabled(enable);
if (applyBtn != null) {
applyBtn.setEnabled(enable);
}
helpBtn.setEnabled(enable);
}
/**
* @param item
* @param srcLocale
* @param dstLocale
*/
public void copyLocale(final LocalizableItemIFace item,
final Locale srcLocale,
final Locale dstLocale)
{
item.fillNames(namesList);
LocalizableStrIFace srcName = null;
for (LocalizableStrIFace nm : namesList)
{
if (nm.isLocale(srcLocale))
{
srcName = nm;
break;
}
}
if (srcName != null)
{
LocalizableStrIFace name = localizableStrFactory.create(srcName.getText(), dstLocale);
item.addName(name);
}
item.fillDescs(descsList);
LocalizableStrIFace srcDesc = null;
for (LocalizableStrIFace d : descsList)
{
if (d.isLocale(srcLocale))
{
srcDesc = d;
break;
}
}
if (srcDesc != null)
{
LocalizableStrIFace desc = localizableStrFactory.create(srcDesc.getText(), dstLocale);
item.addDesc(desc);
}
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#copyLocale(java.util.Locale, java.util.Locale, java.beans.PropertyChangeListener)
*/
@Override
public void copyLocale(final LocalizableIOIFaceListener lcl,
Locale srcLocale, Locale dstLocale,
final PropertyChangeListener pcl)
{
UIRegistry.getStatusBar().setProgressRange(SCHEMALOCDLG, 0, getContainerDisplayItems().size());
DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
try
{
double step = 100.0 / (double)tableDisplayItems.size();
double total = 0.0;
for (LocalizableJListItem listItem : tableDisplayItems)
{
//System.out.println(listItem.getName());
SpLocaleContainer container = (SpLocaleContainer)tableHash.get(listItem.getId());
if (container == null)
{
container = loadTable(session, listItem.getId());
tableHash.put(listItem.getId(), container);
}
if (container != null)
{
copyLocale(container, srcLocale, dstLocale);
for (LocalizableItemIFace field : container.getItems())
{
//System.out.println(" "+field.getName());
copyLocale(field, srcLocale, dstLocale);
}
containerChanged(container);
if (pcl != null)
{
pcl.propertyChange(new PropertyChangeEvent(this, "progress", total, (int)(total+step)));
}
} else
{
log.error("Couldn't find Container["+listItem.getId()+"]");
}
total += step;
}
} catch (Exception ex)
{
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex);
ex.printStackTrace();
} finally
{
session.close();
UIRegistry.getStatusBar().setProgressDone(SCHEMALOCDLG);
}
pcl.propertyChange(new PropertyChangeEvent(this, "progress", 99, 100));
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#getPickLists(java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
public List<PickList> getPickLists(final String disciplineName)
{
if (StringUtils.isNotEmpty(disciplineName))
{
return null;
}
if (pickLists == null)
{
DataProviderSessionIFace session = null;
try
{
session = DataProviderFactory.getInstance().createSession();
pickLists = new Vector<PickList>();
// unchecked warning: Criteria results are always the requested class
String sql = "SELECT name, type, tableName, fieldName, pickListId FROM PickList WHERE collectionId = "+
AppContextMgr.getInstance().getClassObject(Collection.class).getCollectionId() +
" ORDER BY name";
List<?> list = session.getDataList(sql);
for (Object row : list)
{
Object[] data = (Object[])row;
PickList pl = new PickList();
pl.initialize();
pl.setName((String)data[0]);
pl.setType((Byte)data[1]);
pl.setTableName((String)data[2]);
pl.setFieldName((String)data[3]);
pl.setPickListId((Integer)data[4]);
pickLists.add(pl);
}
//pickLists = (List<PickList>)session.getDataList(sql);
} catch (Exception ex)
{
edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, ex);
log.error(ex);
ex.printStackTrace();
} finally
{
if (session != null)
{
session.close();
}
}
}
return pickLists;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#exportToDirectory(java.io.File)
*/
@Override
public boolean exportToDirectory(File expportDir)
{
throw new RuntimeException("Export is not implemented.");
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#hasUpdatablePickLists()
*/
@Override
public boolean hasUpdatablePickLists()
{
return true;
}
/* (non-Javadoc)
* @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
*/
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals("copyStart"))
{
enabledDlgBtns(false);
} else if (evt.getPropertyName().equals("copyEnd"))
{
enabledDlgBtns(true);
}
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#exportSingleLanguageToDirectory(java.io.File, java.util.Locale)
*/
@Override
public boolean exportSingleLanguageToDirectory(File expportFile, Locale locale)
{
throw new RuntimeException("Not Impl");
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.tools.schemalocale.LocalizableIOIFace#hasChanged()
*/
@Override
public boolean hasChanged()
{
throw new RuntimeException("Not Impl");
}
}
| gpl-2.0 |
henwist/OOM_lab2 | src/grupp07/model/Player.java | 1814 | /*
* 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 grupp07.model;
import java.util.ArrayList;
import javafx.scene.paint.Color;
import javafx.util.Pair;
/**
*
* @author gast
*/
public abstract class Player {
private String name;
private Color playerColor;
/** This function should return the wished next move for player.
*
* @return a tuple of the wished move containing two Integers for player.
*/
public abstract Pair nextMove();
/** This function may use the supplied list of possible moves for
* the actual game. The player returns a wished move, that may be one of
* the supplied ones.
*
* @param coords is a list of possible moves for the current player to
* choose from. This could guide a computer player for example.
* @return
*/
public abstract Pair nextMove(ArrayList<Pair<Integer, Integer>> coords);
/** This function gets the players color.
*
* @return the player's color.
*/
public Color getColor(){
return playerColor;
}
/** This function sets the players color.
*
* @param color the player to use color.
*/
public void setColor(Color color){
playerColor = color;
}
/** This function gets the name of the player.
*
* @return the name of the player
*/
public String getName(){
return name;
}
/** This function sets the players name
*
* @param name the player's name.
*/
public void setName(String name){
this.name = name;
}
}
| gpl-2.0 |
mzorz/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/notifications/NotificationDismissBroadcastReceiver.java | 1155 | package org.wordpress.android.ui.notifications;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import org.wordpress.android.push.GCMMessageService;
/*
* Clears the notification map when a user dismisses a notification
*/
public class NotificationDismissBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
if (notificationId == GCMMessageService.GROUP_NOTIFICATION_ID) {
GCMMessageService.clearNotifications();
} else {
GCMMessageService.removeNotification(notificationId);
// Dismiss the grouped notification if a user dismisses all notifications from a wear device
if (!GCMMessageService.hasNotifications()) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.cancel(GCMMessageService.GROUP_NOTIFICATION_ID);
}
}
}
}
| gpl-2.0 |
inspiraCode/scspro | scspro-parent/scspro_service/src/main/java/com/nowgroup/scspro/service/cat/StorageService.java | 279 | package com.nowgroup.scspro.service.cat;
import com.nowgroup.scspro.dto.cat.Storage;
import com.nowgroup.scspro.dto.geo.State;
import com.nowgroup.scspro.service.BaseService;
public interface StorageService extends BaseService<Storage> {
State getStateInStorage(int id);
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest11613.java | 2984 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest11613")
public class BenchmarkTest11613 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("foo");
String bar = new Test().doSomething(param);
try {
java.util.Properties Benchmarkprops = new java.util.Properties();
Benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("Benchmark.properties"));
String algorithm = Benchmarkprops.getProperty("cryptoAlg1", "DESede/ECB/PKCS5Padding");
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm);
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
}
response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple ? condition that assigns constant to bar on true condition
int i = 106;
bar = (7*18) + i > 200 ? "This_should_always_happen" : param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
wangchangshuai/fei_Q | server/src/server/thread/systemSettingsThread/setting_dealingThread.java | 1584 | package server.thread.systemSettingsThread;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import server.serverMain.serverMain;
import server.thread.systemMessageThread.sendSystemMessageThread;
import common.message.mainInfo;
import common.message.node_public;
import common.message.systemSettings;
/**
* 2011年10月
*
* 山东科技大学信息学院 版权所有
*
* 联系邮箱:415939252@qq.com
*
* Copyright © 1999-2012, sdust, All Rights Reserved
*
* @author 王昌帅
*
*/
public class setting_dealingThread extends Thread
{
Socket client;
systemSettings settings;
Statement state1;
public setting_dealingThread(Socket s_client) throws IOException, SQLException
{
this.state1 = serverMain.con1.createStatement();
this.client = s_client;
// start();
}
public void run()
{
try
{
ObjectInputStream oin = new ObjectInputStream(client.getInputStream());
settings = (systemSettings) oin.readObject();
String sql_update = "update whetherCanAdd set can = " + settings.whetherCanAdd + " where qq = '" + settings.qq + "';";
state1.execute(sql_update);
state1.close();
String text = new String("您的设置已生效");
sendSystemMessageThread sender = new sendSystemMessageThread(settings.qq, text);
client.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
| gpl-2.0 |
rjsingh/graal | graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/java/StoreIndexedNode.java | 3269 | /*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.nodes.java;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.spi.*;
import com.oracle.graal.nodes.type.*;
/**
* The {@code StoreIndexedNode} represents a write to an array element.
*/
public final class StoreIndexedNode extends AccessIndexedNode implements StateSplit, Lowerable, Virtualizable {
@Input private ValueNode value;
@Input(notDataflow = true) private FrameState stateAfter;
public FrameState stateAfter() {
return stateAfter;
}
public void setStateAfter(FrameState x) {
assert x == null || x.isAlive() : "frame state must be in a graph";
updateUsages(stateAfter, x);
stateAfter = x;
}
public boolean hasSideEffect() {
return true;
}
public ValueNode value() {
return value;
}
/**
* Creates a new StoreIndexedNode.
*
* @param array the node producing the array
* @param index the node producing the index
* @param elementKind the element type
* @param value the value to store into the array
*/
public StoreIndexedNode(ValueNode array, ValueNode index, Kind elementKind, ValueNode value) {
super(StampFactory.forVoid(), array, index, elementKind);
this.value = value;
}
@Override
public void virtualize(VirtualizerTool tool) {
State arrayState = tool.getObjectState(array());
if (arrayState != null && arrayState.getState() == EscapeState.Virtual) {
ValueNode indexValue = tool.getReplacedValue(index());
int index = indexValue.isConstant() ? indexValue.asConstant().asInt() : -1;
if (index >= 0 && index < arrayState.getVirtualObject().entryCount()) {
ResolvedJavaType componentType = arrayState.getVirtualObject().type().getComponentType();
if (componentType.isPrimitive() || value.objectStamp().alwaysNull() || (value.objectStamp().type() != null && componentType.isAssignableFrom(value.objectStamp().type()))) {
tool.setVirtualEntry(arrayState, index, value());
tool.delete();
}
}
}
}
}
| gpl-2.0 |
toannh/demo | src/main/java/net/demo/model/UserRole.java | 836 | package net.demo.model;
import javax.persistence.*;
/**
* Created by toannh on 10/9/14.
*/
@Entity
@Table(name = "USER_ROLE")
public class UserRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String role;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "username")
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| gpl-2.0 |
expleeve/GoF23 | src/gof/behaviour/mediator/Colleague1.java | 218 | package gof.behaviour.mediator;
public class Colleague1 extends Colleague {
public Colleague1(Mediator m){
super(m);
}
@Override
public void action() {
System.out.println("Colleague1");
}
}
| gpl-2.0 |
MyRealityCoding/maze | maze/src/org/globalgamejam/maze/tweens/SpriteTween.java | 1020 | package org.globalgamejam.maze.tweens;
import aurelienribon.tweenengine.TweenAccessor;
import com.badlogic.gdx.graphics.g2d.Sprite;
public class SpriteTween implements TweenAccessor<Sprite> {
public static final int BOUNCE = 1;
public static final int ALPHA = 2;
public static final int ROTATION = 3;
@Override
public int getValues(Sprite target, int tweenType, float[] returnValues) {
switch (tweenType) {
case BOUNCE:
returnValues[0] = target.getY();
return 1;
case ALPHA:
returnValues[0] = target.getColor().a;
return 1;
case ROTATION:
returnValues[0] = target.getRotation();
return 1;
default:
return 0;
}
}
@Override
public void setValues(Sprite target, int tweenType, float[] newValues) {
switch (tweenType) {
case BOUNCE:
target.setY(newValues[0]);
break;
case ALPHA:
target.setColor(target.getColor().r, target.getColor().g,
target.getColor().b, newValues[0]);
break;
case ROTATION:
target.setRotation(newValues[0]);
break;
}
}
}
| gpl-2.0 |
pollorijas/SellPotato | SellPotato/app/src/main/java/sellpotato/sellpotato/Model/IGoogleApiMaps.java | 333 | package sellpotato.sellpotato.Model;
/**
* @author Freddy
* @version 1.0
* @created 08-ene-2015 19:29:24
*/
public class IGoogleApiMaps {
public IGoogleApiMaps(){
}
public void finalize() throws Throwable {
}
public void DibujarRuta(){
}
public double CombertirDireccionPunto(){
return 0;
}
}//end IGoogleApiMaps | gpl-2.0 |
aroychoudhury/fileanalytics | src/main/java/org/abhishek/fileanalytics/lifecycle/Destroyable.java | 165 | /* Copyright 2015 Roychoudhury, Abhishek */
package org.abhishek.fileanalytics.lifecycle;
public interface Destroyable {
void destroy();
boolean destroyed();
}
| gpl-2.0 |
fyffyt/LearnJava | src/com/test/JUnit/CalculatorTest.java | 882 | package com.test.JUnit;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class CalculatorTest {
private static Calculator calculator = new Calculator();
@Before
public void setUp() throws Exception {
calculator.clear();
}
@Test
public void testAdd() {
calculator.add(2);
calculator.add(3);
assertEquals(5, calculator.getResult());
}
@Test
public void testSubstract() {
calculator.add(10);
calculator.substract(2);
assertEquals(8, calculator.getResult());
}
@Ignore("Multiply() Not yet implemented")
@Test
public void testMultiply() {
}
@Test
public void testDivide() {
calculator.add(8);
calculator.divide(2);
assertEquals(4, calculator.getResult());
}
} | gpl-2.0 |
ivanmarban/spring-boot-movies-restful | src/main/java/com/github/ivanmarban/movies/MovieRestController.java | 1466 | package com.github.ivanmarban.movies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class MovieRestController {
@Autowired
private MovieRepository repo;
@RequestMapping(value = "api/v1/movies", method = RequestMethod.GET)
public List<Movie> getAll() {
return repo.findAll();
}
@RequestMapping(value = "api/v1/movie/{id}", method = RequestMethod.GET)
public Movie get(@PathVariable String id) {
return repo.findOne(id);
}
@RequestMapping(value = "api/v1/movie", method = RequestMethod.POST)
public Movie create(@RequestBody Movie movie) {
return repo.save(movie);
}
@RequestMapping(value = "api/v1/movie/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable String id) {
repo.delete(id);
}
@RequestMapping(value = "api/v1/movie/{id}", method = RequestMethod.PUT)
public Movie update(@PathVariable String id, @RequestBody Movie movie) {
Movie update = repo.findOne(id);
update.setDirector(movie.getDirector());
update.setGenre(movie.getGenre());
update.setRated(movie.getRated());
update.setRuntime(movie.getRuntime());
update.setTitle(movie.getTitle());
update.setYear(movie.getYear());
return repo.save(update);
}
}
| gpl-2.0 |
zbutfly/albus | core/src/main/java/net/butfly/bus/invoker/Invoker.java | 729 | package net.butfly.bus.invoker;
import net.butfly.albacore.service.Service;
import net.butfly.albacore.utils.async.Options;
import net.butfly.bus.Request;
import net.butfly.bus.Response;
import net.butfly.bus.config.bean.InvokerConfig;
import net.butfly.bus.context.Token;
import net.butfly.bus.policy.Routeable;
public interface Invoker extends Routeable {
void initialize(InvokerConfig config, Token token);
void initialize();
Response invoke(Request request, Options... remoteOptions) throws Exception;
Object[] getBeanList();
<S extends Service> S awared(Class<S> awaredServiceClass);
Token token();
Options localOptions(Options... options);
Options[] remoteOptions(Options... options);
boolean lazy();
}
| gpl-2.0 |
FallenGiter/killjava | src/spring/aop/Main.java | 736 | package spring.aop;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/aop/aop-proxy.xml");
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/aop/aop-auto-proxy.xml");
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/aop/aop-annotation-proxy.xml");
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/aop/aop-config.xml");
// Service sv = (Service) ctx.getBean("ServiceProxy");
Service sv = (Service) ctx.getBean("Service");
sv.doWork();
}
}
| gpl-2.0 |
favedit/MoPlatform | mo-3-logic/src/logic-java/org/mo/logic/process/ILogicProcessConsole.java | 204 | package org.mo.logic.process;
import org.mo.com.xml.IXmlObject;
import org.mo.eng.store.IXmlConfigConsole;
public interface ILogicProcessConsole
extends
IXmlConfigConsole<IXmlObject>
{
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/pm/shrd_Ed_Gd_Ib_mem.java | 2407 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 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 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.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.pm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class shrd_Ed_Gd_Ib_mem extends Executable
{
final Pointer op1;
final int op2Index;
final int immb;
public shrd_Ed_Gd_Ib_mem(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
op1 = Modrm.getPointer(prefices, modrm, input);
op2Index = Modrm.Gd(modrm);
immb = Modrm.Ib(input);
}
public Branch execute(Processor cpu)
{
Reg op2 = cpu.regs[op2Index];
if(immb != 0)
{
int shift = immb & 0x1f;
cpu.flagOp1 = op1.get32(cpu);
cpu.flagOp2 = shift;
long rot = ((0xffffffffL &op2.get32()) << 32) | (0xffffffffL & op1.get32(cpu));
cpu.flagResult = ((int)(rot >> shift));
op1.set32(cpu, cpu.flagResult);
cpu.flagIns = UCodes.SHRD32;
cpu.flagStatus = OSZAPC;
}
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
dbfit/dbfit | dbfit-java/sqlserver/src/main/java/dbfit/environment/SqlServerEnvironment.java | 10073 | package dbfit.environment;
import dbfit.annotations.DatabaseEnvironment;
import dbfit.api.AbstractDbEnvironment;
import dbfit.util.DbParameterAccessor;
import dbfit.util.DbParameterAccessorsMapBuilder;
import dbfit.util.Direction;
import static dbfit.util.Direction.*;
import static dbfit.util.LangUtils.enquoteAndJoin;
import dbfit.util.TypeNormaliserFactory;
import static dbfit.environment.SqlServerTypeNameNormaliser.normaliseTypeName;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
@DatabaseEnvironment(name="SqlServer", driver="com.microsoft.sqlserver.jdbc.SQLServerDriver")
public class SqlServerEnvironment extends AbstractDbEnvironment {
public SqlServerEnvironment(String driverClassName) {
super(driverClassName);
defaultParamPatternString = "@([A-Za-z0-9_]+)";
TypeNormaliserFactory.setNormaliser(java.sql.Time.class,
new MillisecondTimeNormaliser());
}
public boolean supportsOuputOnInsert() {
return false;
}
@Override
protected String getConnectionString(String dataSource) {
return "jdbc:sqlserver://" + dataSource;
}
@Override
protected String getConnectionString(String dataSource, String database) {
return getConnectionString(dataSource) + ";database=" + database;
}
@Override
public void connect(String connectionString, Properties info) throws SQLException {
// Add sendTimeAsDatetime=false option to enforce sending Time as
// java.sql.Time (otherwise some precision is lost in conversions)
super.connect(connectionString + ";sendTimeAsDatetime=false", info);
}
public Map<String, DbParameterAccessor> getAllColumns(String tableOrViewName)
throws SQLException {
String qry = " select c.[name], TYPE_NAME(c.system_type_id) as [Type], c.max_length, "
+ " 0 As is_output, 0 As is_cursor_ref "
+ " from " + objectDatabasePrefix(tableOrViewName) + "sys.columns c "
+ " where c.object_id = OBJECT_ID(?) "
+ " order by column_id";
return readIntoParams(tableOrViewName, qry);
}
private Map<String, DbParameterAccessor> readIntoParams(String objname,
String query) throws SQLException {
DbParameterAccessorsMapBuilder params = new DbParameterAccessorsMapBuilder(dbfitToJdbcTransformerFactory);
objname = objname.replaceAll("[^a-zA-Z0-9_.#$]", "");
String bracketedName = enquoteAndJoin(objname.split("\\."), ".", "[", "]");
try (PreparedStatement dc = currentConnection.prepareStatement(query)) {
dc.setString(1, bracketedName);
ResultSet rs = dc.executeQuery();
while (rs.next()) {
String paramName = defaultIfNull(rs.getString(1), "");
params.add(paramName,
getParameterDirection(rs.getInt(4), paramName),
getSqlType(rs.getString(2)),
getJavaClass(rs.getString(2)));
}
}
return params.toMap();
}
// List interface has sequential search, so using list instead of array to
// map types
private static List<String> stringTypes = Arrays.asList(new String[] {
"VARCHAR", "NVARCHAR", "CHAR", "NCHAR", "TEXT", "NTEXT",
"UNIQUEIDENTIFIER" });
private static List<String> intTypes = Arrays
.asList(new String[] { "INT" });
private static List<String> booleanTypes = Arrays
.asList(new String[] { "BIT" });
private static List<String> floatTypes = Arrays
.asList(new String[] { "REAL" });
private static List<String> doubleTypes = Arrays
.asList(new String[] { "FLOAT" });
private static List<String> longTypes = Arrays
.asList(new String[] { "BIGINT" });
private static List<String> shortTypes = Arrays.asList(new String[] {
"TINYINT", "SMALLINT" });
private static List<String> numericTypes = Arrays.asList("NUMERIC");
private static List<String> decimalTypes = Arrays.asList(new String[] {
"DECIMAL", "MONEY", "SMALLMONEY" });
private static List<String> timestampTypes = Arrays.asList(new String[] {
"SMALLDATETIME", "DATETIME", "DATETIME2" });
private static List<String> dateTypes = Arrays.asList("DATE");
private static List<String> timeTypes = Arrays.asList("TIME");
// private static List<String> refCursorTypes = Arrays.asList(new String[] {
// });
// private static List<String> doubleTypes=Arrays.asList(new
// String[]{"DOUBLE"});
// private static string[] BinaryTypes=new string[] {"BINARY","VARBINARY", "TIMESTAMP"};
// private static string[] GuidTypes = new string[] { "UNIQUEIDENTIFIER" };
// private static string[] VariantTypes = new string[] { "SQL_VARIANT" };
private String objectDatabasePrefix(String dbObjectName) {
String objectDatabasePrefix = "";
String[] objnameParts = dbObjectName.split("\\.");
if (objnameParts.length == 3) {
objectDatabasePrefix = objnameParts[0] + ".";
}
return objectDatabasePrefix;
}
private static Direction getParameterDirection(int isOutput, String name) {
if (name.isEmpty()) {
return RETURN_VALUE;
}
return (isOutput == 1) ? INPUT_OUTPUT : INPUT;
}
private static int getSqlType(String dataType) {
// todo:strip everything from first blank
dataType = normaliseTypeName(dataType);
if (stringTypes.contains(dataType))
return java.sql.Types.VARCHAR;
if (numericTypes.contains(dataType))
return java.sql.Types.NUMERIC;
if (decimalTypes.contains(dataType))
return java.sql.Types.DECIMAL;
if (intTypes.contains(dataType))
return java.sql.Types.INTEGER;
if (timestampTypes.contains(dataType))
return java.sql.Types.TIMESTAMP;
if (dateTypes.contains(dataType))
return java.sql.Types.DATE;
if (timeTypes.contains(dataType))
return java.sql.Types.TIME;
if (booleanTypes.contains(dataType))
return java.sql.Types.BOOLEAN;
if (floatTypes.contains(dataType))
return java.sql.Types.FLOAT;
if (doubleTypes.contains(dataType))
return java.sql.Types.DOUBLE;
if (longTypes.contains(dataType))
return java.sql.Types.BIGINT;
if (shortTypes.contains(dataType))
return java.sql.Types.SMALLINT;
throw new UnsupportedOperationException("Type " + dataType
+ " is not supported");
}
public Class<?> getJavaClass(String dataType) {
dataType = normaliseTypeName(dataType);
if (stringTypes.contains(dataType))
return String.class;
if (numericTypes.contains(dataType))
return BigDecimal.class;
if (decimalTypes.contains(dataType))
return BigDecimal.class;
if (intTypes.contains(dataType))
return Integer.class;
if (timestampTypes.contains(dataType))
return java.sql.Timestamp.class;
if (dateTypes.contains(dataType))
return java.sql.Date.class;
if (timeTypes.contains(dataType))
return java.sql.Time.class;
if (booleanTypes.contains(dataType))
return Boolean.class;
if (floatTypes.contains(dataType))
return Float.class;
if (doubleTypes.contains(dataType))
return Double.class;
if (longTypes.contains(dataType))
return Long.class;
if (shortTypes.contains(dataType))
return Short.class;
throw new UnsupportedOperationException("Type " + dataType
+ " is not supported");
}
public Map<String, DbParameterAccessor> getAllProcedureParameters(
String procName) throws SQLException {
return readIntoParams(
procName,
"select [name], [Type], max_length, is_output, is_cursor_ref from "
+ "("
+ " select "
+ " p.[name], TYPE_NAME(p.system_type_id) as [Type], "
+ " p.max_length, p.is_output, p.is_cursor_ref, "
+ " p.parameter_id, 0 as set_id, p.object_id "
+ " from " + objectDatabasePrefix(procName) + "sys.parameters p "
+ " union all select "
+ " '' as [name], 'int' as [Type], "
+ " 4 as max_length, 1 as is_output, 0 as is_cursor_ref, "
+ " null as parameter_id, 1 as set_id, object_id "
+ " from " + objectDatabasePrefix(procName) + "sys.objects where type in (N'P', N'PC') "
+ ") as u where object_id = OBJECT_ID(?) order by set_id, parameter_id");
}
public String buildInsertCommand(String tableName,
DbParameterAccessor[] accessors) {
StringBuilder sb = new StringBuilder("insert into ");
sb.append(tableName).append("(");
String comma = "";
StringBuilder values = new StringBuilder();
for (DbParameterAccessor accessor : accessors) {
if (accessor.hasDirection(Direction.INPUT)) {
sb.append(comma);
values.append(comma);
//This will allow column names that have spaces or are keywords.
sb.append("[" + accessor.getName() + "]");
values.append("?");
comma = ",";
}
}
sb.append(") values (");
sb.append(values);
sb.append(")");
return sb.toString();
}
}
| gpl-2.0 |
md-5/jdk10 | src/java.base/share/classes/sun/security/tools/keytool/Resources_ja.java | 45912 | /*
* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.tools.keytool;
/**
* <p> This class represents the <code>ResourceBundle</code>
* for the keytool.
*
*/
public class Resources_ja extends java.util.ListResourceBundle {
private static final Object[][] contents = {
{"NEWLINE", "\n"},
{"STAR",
"*******************************************"},
{"STARNN",
"*******************************************\n\n"},
// keytool: Help part
{".OPTION.", " [OPTION]..."},
{"Options.", "\u30AA\u30D7\u30B7\u30E7\u30F3:"},
{"option.1.set.twice", "%s\u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u8907\u6570\u56DE\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059\u3002\u6700\u5F8C\u306E\u3082\u306E\u4EE5\u5916\u306F\u3059\u3079\u3066\u7121\u8996\u3055\u308C\u307E\u3059\u3002"},
{"multiple.commands.1.2", "1\u3064\u306E\u30B3\u30DE\u30F3\u30C9\u306E\u307F\u8A31\u53EF\u3055\u308C\u307E\u3059: %1$s\u3068%2$s\u306E\u4E21\u65B9\u304C\u6307\u5B9A\u3055\u308C\u307E\u3057\u305F\u3002"},
{"Use.keytool.help.for.all.available.commands",
"\u3053\u306E\u30D8\u30EB\u30D7\u30FB\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u8868\u793A\u3059\u308B\u306B\u306F\"keytool -?\u3001-h\u307E\u305F\u306F--help\"\u3092\u4F7F\u7528\u3057\u307E\u3059"},
{"Key.and.Certificate.Management.Tool",
"\u30AD\u30FC\u304A\u3088\u3073\u8A3C\u660E\u66F8\u7BA1\u7406\u30C4\u30FC\u30EB"},
{"Commands.", "\u30B3\u30DE\u30F3\u30C9:"},
{"Use.keytool.command.name.help.for.usage.of.command.name",
"command_name\u306E\u4F7F\u7528\u65B9\u6CD5\u306B\u3064\u3044\u3066\u306F\u3001\"keytool -command_name --help\"\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002\n\u4E8B\u524D\u69CB\u6210\u6E08\u306E\u30AA\u30D7\u30B7\u30E7\u30F3\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u6307\u5B9A\u3059\u308B\u306B\u306F\u3001-conf <url>\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002"},
// keytool: help: commands
{"Generates.a.certificate.request",
"\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8\u3092\u751F\u6210\u3057\u307E\u3059"}, //-certreq
{"Changes.an.entry.s.alias",
"\u30A8\u30F3\u30C8\u30EA\u306E\u5225\u540D\u3092\u5909\u66F4\u3057\u307E\u3059"}, //-changealias
{"Deletes.an.entry",
"\u30A8\u30F3\u30C8\u30EA\u3092\u524A\u9664\u3057\u307E\u3059"}, //-delete
{"Exports.certificate",
"\u8A3C\u660E\u66F8\u3092\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-exportcert
{"Generates.a.key.pair",
"\u30AD\u30FC\u30FB\u30DA\u30A2\u3092\u751F\u6210\u3057\u307E\u3059"}, //-genkeypair
{"Generates.a.secret.key",
"\u79D8\u5BC6\u30AD\u30FC\u3092\u751F\u6210\u3057\u307E\u3059"}, //-genseckey
{"Generates.certificate.from.a.certificate.request",
"\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8\u304B\u3089\u8A3C\u660E\u66F8\u3092\u751F\u6210\u3057\u307E\u3059"}, //-gencert
{"Generates.CRL", "CRL\u3092\u751F\u6210\u3057\u307E\u3059"}, //-gencrl
{"Generated.keyAlgName.secret.key",
"{0}\u79D8\u5BC6\u30AD\u30FC\u3092\u751F\u6210\u3057\u307E\u3057\u305F"}, //-genseckey
{"Generated.keysize.bit.keyAlgName.secret.key",
"{0}\u30D3\u30C3\u30C8{1}\u79D8\u5BC6\u30AD\u30FC\u3092\u751F\u6210\u3057\u307E\u3057\u305F"}, //-genseckey
{"Imports.entries.from.a.JDK.1.1.x.style.identity.database",
"JDK 1.1.x-style\u30A2\u30A4\u30C7\u30F3\u30C6\u30A3\u30C6\u30A3\u30FB\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u304B\u3089\u30A8\u30F3\u30C8\u30EA\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-identitydb
{"Imports.a.certificate.or.a.certificate.chain",
"\u8A3C\u660E\u66F8\u307E\u305F\u306F\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-importcert
{"Imports.a.password",
"\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-importpass
{"Imports.one.or.all.entries.from.another.keystore",
"\u5225\u306E\u30AD\u30FC\u30B9\u30C8\u30A2\u304B\u30891\u3064\u307E\u305F\u306F\u3059\u3079\u3066\u306E\u30A8\u30F3\u30C8\u30EA\u3092\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u307E\u3059"}, //-importkeystore
{"Clones.a.key.entry",
"\u30AD\u30FC\u30FB\u30A8\u30F3\u30C8\u30EA\u306E\u30AF\u30ED\u30FC\u30F3\u3092\u4F5C\u6210\u3057\u307E\u3059"}, //-keyclone
{"Changes.the.key.password.of.an.entry",
"\u30A8\u30F3\u30C8\u30EA\u306E\u30AD\u30FC\u30FB\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5909\u66F4\u3057\u307E\u3059"}, //-keypasswd
{"Lists.entries.in.a.keystore",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u5185\u306E\u30A8\u30F3\u30C8\u30EA\u3092\u30EA\u30B9\u30C8\u3057\u307E\u3059"}, //-list
{"Prints.the.content.of.a.certificate",
"\u8A3C\u660E\u66F8\u306E\u5185\u5BB9\u3092\u51FA\u529B\u3057\u307E\u3059"}, //-printcert
{"Prints.the.content.of.a.certificate.request",
"\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u5185\u5BB9\u3092\u51FA\u529B\u3057\u307E\u3059"}, //-printcertreq
{"Prints.the.content.of.a.CRL.file",
"CRL\u30D5\u30A1\u30A4\u30EB\u306E\u5185\u5BB9\u3092\u51FA\u529B\u3057\u307E\u3059"}, //-printcrl
{"Generates.a.self.signed.certificate",
"\u81EA\u5DF1\u7F72\u540D\u578B\u8A3C\u660E\u66F8\u3092\u751F\u6210\u3057\u307E\u3059"}, //-selfcert
{"Changes.the.store.password.of.a.keystore",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30B9\u30C8\u30A2\u30FB\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5909\u66F4\u3057\u307E\u3059"}, //-storepasswd
{"showinfo.command.help", "\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u95A2\u9023\u60C5\u5831\u3092\u8868\u793A\u3057\u307E\u3059"},
// keytool: help: options
{"alias.name.of.the.entry.to.process",
"\u51E6\u7406\u3059\u308B\u30A8\u30F3\u30C8\u30EA\u306E\u5225\u540D"}, //-alias
{"groupname.option.help",
"\u30B0\u30EB\u30FC\u30D7\u540D\u3002\u305F\u3068\u3048\u3070\u3001\u6955\u5186\u66F2\u7DDA\u540D\u3067\u3059\u3002"}, //-groupname
{"destination.alias",
"\u51FA\u529B\u5148\u306E\u5225\u540D"}, //-destalias
{"destination.key.password",
"\u51FA\u529B\u5148\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-destkeypass
{"destination.keystore.name",
"\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u540D"}, //-destkeystore
{"destination.keystore.password.protected",
"\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u4FDD\u8B77\u5BFE\u8C61\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-destprotected
{"destination.keystore.provider.name",
"\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0\u540D"}, //-destprovidername
{"destination.keystore.password",
"\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-deststorepass
{"destination.keystore.type",
"\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30BF\u30A4\u30D7"}, //-deststoretype
{"distinguished.name",
"\u8B58\u5225\u540D"}, //-dname
{"X.509.extension",
"X.509\u62E1\u5F35"}, //-ext
{"output.file.name",
"\u51FA\u529B\u30D5\u30A1\u30A4\u30EB\u540D"}, //-file and -outfile
{"input.file.name",
"\u5165\u529B\u30D5\u30A1\u30A4\u30EB\u540D"}, //-file and -infile
{"key.algorithm.name",
"\u30AD\u30FC\u30FB\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u540D"}, //-keyalg
{"key.password",
"\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-keypass
{"key.bit.size",
"\u30AD\u30FC\u306E\u30D3\u30C3\u30C8\u30FB\u30B5\u30A4\u30BA"}, //-keysize
{"keystore.name",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u540D"}, //-keystore
{"access.the.cacerts.keystore",
"cacerts\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u30A2\u30AF\u30BB\u30B9\u3059\u308B"}, // -cacerts
{"warning.cacerts.option",
"\u8B66\u544A: cacerts\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u30A2\u30AF\u30BB\u30B9\u3059\u308B\u306B\u306F-cacerts\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044"},
{"new.password",
"\u65B0\u898F\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-new
{"do.not.prompt",
"\u30D7\u30ED\u30F3\u30D7\u30C8\u3092\u8868\u793A\u3057\u306A\u3044"}, //-noprompt
{"password.through.protected.mechanism",
"\u4FDD\u8B77\u30E1\u30AB\u30CB\u30BA\u30E0\u306B\u3088\u308B\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-protected
{"tls.option.help", "TLS\u69CB\u6210\u60C5\u5831\u3092\u8868\u793A\u3057\u307E\u3059"},
// The following 2 values should span 2 lines, the first for the
// option itself, the second for its -providerArg value.
{"addprovider.option",
"\u540D\u524D\u3067\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0\u3092\u8FFD\u52A0\u3059\u308B(SunPKCS11\u306A\u3069)\n-addprovider\u306E\u5F15\u6570\u3092\u69CB\u6210\u3059\u308B"}, //-addprovider
{"provider.class.option",
"\u5B8C\u5168\u4FEE\u98FE\u30AF\u30E9\u30B9\u540D\u3067\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0\u3092\u8FFD\u52A0\u3059\u308B\n-providerclass\u306E\u5F15\u6570\u3092\u69CB\u6210\u3059\u308B"}, //-providerclass
{"provider.name",
"\u30D7\u30ED\u30D0\u30A4\u30C0\u540D"}, //-providername
{"provider.classpath",
"\u30D7\u30ED\u30D0\u30A4\u30C0\u30FB\u30AF\u30E9\u30B9\u30D1\u30B9"}, //-providerpath
{"output.in.RFC.style",
"RFC\u30B9\u30BF\u30A4\u30EB\u306E\u51FA\u529B"}, //-rfc
{"signature.algorithm.name",
"\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u540D"}, //-sigalg
{"source.alias",
"\u30BD\u30FC\u30B9\u5225\u540D"}, //-srcalias
{"source.key.password",
"\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-srckeypass
{"source.keystore.name",
"\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u540D"}, //-srckeystore
{"source.keystore.password.protected",
"\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u4FDD\u8B77\u5BFE\u8C61\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-srcprotected
{"source.keystore.provider.name",
"\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0\u540D"}, //-srcprovidername
{"source.keystore.password",
"\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-srcstorepass
{"source.keystore.type",
"\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30BF\u30A4\u30D7"}, //-srcstoretype
{"SSL.server.host.and.port",
"SSL\u30B5\u30FC\u30D0\u30FC\u306E\u30DB\u30B9\u30C8\u3068\u30DD\u30FC\u30C8"}, //-sslserver
{"signed.jar.file",
"\u7F72\u540D\u4ED8\u304DJAR\u30D5\u30A1\u30A4\u30EB"}, //=jarfile
{"certificate.validity.start.date.time",
"\u8A3C\u660E\u66F8\u306E\u6709\u52B9\u958B\u59CB\u65E5\u6642"}, //-startdate
{"keystore.password",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"}, //-storepass
{"keystore.type",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30BF\u30A4\u30D7"}, //-storetype
{"trust.certificates.from.cacerts",
"cacerts\u304B\u3089\u306E\u8A3C\u660E\u66F8\u3092\u4FE1\u983C\u3059\u308B"}, //-trustcacerts
{"verbose.output",
"\u8A73\u7D30\u51FA\u529B"}, //-v
{"validity.number.of.days",
"\u59A5\u5F53\u6027\u65E5\u6570"}, //-validity
{"Serial.ID.of.cert.to.revoke",
"\u5931\u52B9\u3059\u308B\u8A3C\u660E\u66F8\u306E\u30B7\u30EA\u30A2\u30EBID"}, //-id
// keytool: Running part
{"keytool.error.", "keytool\u30A8\u30E9\u30FC: "},
{"Illegal.option.", "\u4E0D\u6B63\u306A\u30AA\u30D7\u30B7\u30E7\u30F3: "},
{"Illegal.value.", "\u4E0D\u6B63\u306A\u5024: "},
{"Unknown.password.type.", "\u4E0D\u660E\u306A\u30D1\u30B9\u30EF\u30FC\u30C9\u30FB\u30BF\u30A4\u30D7: "},
{"Cannot.find.environment.variable.",
"\u74B0\u5883\u5909\u6570\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: "},
{"Cannot.find.file.", "\u30D5\u30A1\u30A4\u30EB\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: "},
{"Command.option.flag.needs.an.argument.", "\u30B3\u30DE\u30F3\u30C9\u30FB\u30AA\u30D7\u30B7\u30E7\u30F3{0}\u306B\u306F\u5F15\u6570\u304C\u5FC5\u8981\u3067\u3059\u3002"},
{"Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value.",
"\u8B66\u544A: PKCS12\u30AD\u30FC\u30B9\u30C8\u30A2\u3067\u306F\u3001\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3068\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u304C\u7570\u306A\u308B\u72B6\u6CC1\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093\u3002\u30E6\u30FC\u30B6\u30FC\u304C\u6307\u5B9A\u3057\u305F{0}\u306E\u5024\u306F\u7121\u8996\u3057\u307E\u3059\u3002"},
{"the.keystore.or.storetype.option.cannot.be.used.with.the.cacerts.option",
"-keystore\u307E\u305F\u306F-storetype\u30AA\u30D7\u30B7\u30E7\u30F3\u306F\u3001-cacerts\u30AA\u30D7\u30B7\u30E7\u30F3\u3068\u3068\u3082\u306B\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093"},
{".keystore.must.be.NONE.if.storetype.is.{0}",
"-storetype\u304C{0}\u306E\u5834\u5408\u3001-keystore\u306FNONE\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{"Too.many.retries.program.terminated",
"\u518D\u8A66\u884C\u304C\u591A\u3059\u304E\u307E\u3059\u3002\u30D7\u30ED\u30B0\u30E9\u30E0\u304C\u7D42\u4E86\u3057\u307E\u3057\u305F"},
{".storepasswd.and.keypasswd.commands.not.supported.if.storetype.is.{0}",
"-storetype\u304C{0}\u306E\u5834\u5408\u3001-storepasswd\u30B3\u30DE\u30F3\u30C9\u304A\u3088\u3073-keypasswd\u30B3\u30DE\u30F3\u30C9\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093"},
{".keypasswd.commands.not.supported.if.storetype.is.PKCS12",
"-storetype\u304CPKCS12\u306E\u5834\u5408\u3001-keypasswd\u30B3\u30DE\u30F3\u30C9\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093"},
{".keypass.and.new.can.not.be.specified.if.storetype.is.{0}",
"-storetype\u304C{0}\u306E\u5834\u5408\u3001-keypass\u3068-new\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"},
{"if.protected.is.specified.then.storepass.keypass.and.new.must.not.be.specified",
"-protected\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u308B\u5834\u5408\u3001-storepass\u3001-keypass\u304A\u3088\u3073-new\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"},
{"if.srcprotected.is.specified.then.srcstorepass.and.srckeypass.must.not.be.specified",
"-srcprotected\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u308B\u5834\u5408\u3001-srcstorepass\u304A\u3088\u3073-srckeypass\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"},
{"if.keystore.is.not.password.protected.then.storepass.keypass.and.new.must.not.be.specified",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u304C\u30D1\u30B9\u30EF\u30FC\u30C9\u3067\u4FDD\u8B77\u3055\u308C\u3066\u3044\u306A\u3044\u5834\u5408\u3001-storepass\u3001-keypass\u304A\u3088\u3073-new\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"},
{"if.source.keystore.is.not.password.protected.then.srcstorepass.and.srckeypass.must.not.be.specified",
"\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u304C\u30D1\u30B9\u30EF\u30FC\u30C9\u3067\u4FDD\u8B77\u3055\u308C\u3066\u3044\u306A\u3044\u5834\u5408\u3001-srcstorepass\u304A\u3088\u3073-srckeypass\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"},
{"Illegal.startdate.value", "startdate\u5024\u304C\u7121\u52B9\u3067\u3059"},
{"Validity.must.be.greater.than.zero",
"\u59A5\u5F53\u6027\u306F\u30BC\u30ED\u3088\u308A\u5927\u304D\u3044\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{"provclass.not.a.provider", "%s\u306F\u30D7\u30ED\u30D0\u30A4\u30C0\u3067\u306F\u3042\u308A\u307E\u305B\u3093"},
{"provider.name.not.found", "\u30D7\u30ED\u30D0\u30A4\u30C0\u540D\"%s\"\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093"},
{"provider.class.not.found", "\u30D7\u30ED\u30D0\u30A4\u30C0\"%s\"\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093"},
{"Usage.error.no.command.provided", "\u4F7F\u7528\u30A8\u30E9\u30FC: \u30B3\u30DE\u30F3\u30C9\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093"},
{"Source.keystore.file.exists.but.is.empty.", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D5\u30A1\u30A4\u30EB\u306F\u3001\u5B58\u5728\u3057\u307E\u3059\u304C\u7A7A\u3067\u3059: "},
{"Please.specify.srckeystore", "-srckeystore\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"},
{"Must.not.specify.both.v.and.rfc.with.list.command",
"'list'\u30B3\u30DE\u30F3\u30C9\u306B-v\u3068-rfc\u306E\u4E21\u65B9\u3092\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093"},
{"Key.password.must.be.at.least.6.characters",
"\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u306F6\u6587\u5B57\u4EE5\u4E0A\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{"New.password.must.be.at.least.6.characters",
"\u65B0\u898F\u30D1\u30B9\u30EF\u30FC\u30C9\u306F6\u6587\u5B57\u4EE5\u4E0A\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{"Keystore.file.exists.but.is.empty.",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D5\u30A1\u30A4\u30EB\u306F\u5B58\u5728\u3057\u307E\u3059\u304C\u3001\u7A7A\u3067\u3059: "},
{"Keystore.file.does.not.exist.",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D5\u30A1\u30A4\u30EB\u306F\u5B58\u5728\u3057\u307E\u305B\u3093: "},
{"Must.specify.destination.alias", "\u51FA\u529B\u5148\u306E\u5225\u540D\u3092\u6307\u5B9A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{"Must.specify.alias", "\u5225\u540D\u3092\u6307\u5B9A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{"Keystore.password.must.be.at.least.6.characters",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u306F6\u6587\u5B57\u4EE5\u4E0A\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{"Enter.the.password.to.be.stored.",
"\u4FDD\u5B58\u3059\u308B\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{"Enter.keystore.password.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{"Enter.source.keystore.password.", "\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{"Enter.destination.keystore.password.", "\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{"Keystore.password.is.too.short.must.be.at.least.6.characters",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u304C\u77ED\u3059\u304E\u307E\u3059 - 6\u6587\u5B57\u4EE5\u4E0A\u306B\u3057\u3066\u304F\u3060\u3055\u3044"},
{"Unknown.Entry.Type", "\u4E0D\u660E\u306A\u30A8\u30F3\u30C8\u30EA\u30FB\u30BF\u30A4\u30D7"},
{"Entry.for.alias.alias.successfully.imported.",
"\u5225\u540D{0}\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u306B\u6210\u529F\u3057\u307E\u3057\u305F\u3002"},
{"Entry.for.alias.alias.not.imported.", "\u5225\u540D{0}\u306E\u30A8\u30F3\u30C8\u30EA\u306F\u30A4\u30F3\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},
{"Problem.importing.entry.for.alias.alias.exception.Entry.for.alias.alias.not.imported.",
"\u5225\u540D{0}\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u4E2D\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F: {1}\u3002\n\u5225\u540D{0}\u306E\u30A8\u30F3\u30C8\u30EA\u306F\u30A4\u30F3\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},
{"Import.command.completed.ok.entries.successfully.imported.fail.entries.failed.or.cancelled",
"\u30A4\u30F3\u30DD\u30FC\u30C8\u30FB\u30B3\u30DE\u30F3\u30C9\u304C\u5B8C\u4E86\u3057\u307E\u3057\u305F: {0}\u4EF6\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u304C\u6210\u529F\u3057\u307E\u3057\u305F\u3002{1}\u4EF6\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u304C\u5931\u6557\u3057\u305F\u304B\u53D6\u308A\u6D88\u3055\u308C\u307E\u3057\u305F"},
{"Warning.Overwriting.existing.alias.alias.in.destination.keystore",
"\u8B66\u544A: \u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u5185\u306E\u65E2\u5B58\u306E\u5225\u540D{0}\u3092\u4E0A\u66F8\u304D\u3057\u3066\u3044\u307E\u3059"},
{"Existing.entry.alias.alias.exists.overwrite.no.",
"\u65E2\u5B58\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u5225\u540D{0}\u304C\u5B58\u5728\u3057\u3066\u3044\u307E\u3059\u3002\u4E0A\u66F8\u304D\u3057\u307E\u3059\u304B\u3002[\u3044\u3044\u3048]: "},
{"Too.many.failures.try.later", "\u969C\u5BB3\u304C\u591A\u3059\u304E\u307E\u3059 - \u5F8C\u3067\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"},
{"Certification.request.stored.in.file.filename.",
"\u8A8D\u8A3C\u30EA\u30AF\u30A8\u30B9\u30C8\u304C\u30D5\u30A1\u30A4\u30EB<{0}>\u306B\u4FDD\u5B58\u3055\u308C\u307E\u3057\u305F"},
{"Submit.this.to.your.CA", "\u3053\u308C\u3092CA\u306B\u63D0\u51FA\u3057\u3066\u304F\u3060\u3055\u3044"},
{"if.alias.not.specified.destalias.and.srckeypass.must.not.be.specified",
"\u5225\u540D\u3092\u6307\u5B9A\u3057\u306A\u3044\u5834\u5408\u3001\u51FA\u529B\u5148\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u5225\u540D\u304A\u3088\u3073\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"},
{"The.destination.pkcs12.keystore.has.different.storepass.and.keypass.Please.retry.with.destkeypass.specified.",
"\u51FA\u529B\u5148pkcs12\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u3001\u7570\u306A\u308Bstorepass\u304A\u3088\u3073keypass\u304C\u3042\u308A\u307E\u3059\u3002-destkeypass\u3092\u6307\u5B9A\u3057\u3066\u518D\u8A66\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002"},
{"Certificate.stored.in.file.filename.",
"\u8A3C\u660E\u66F8\u304C\u30D5\u30A1\u30A4\u30EB<{0}>\u306B\u4FDD\u5B58\u3055\u308C\u307E\u3057\u305F"},
{"Certificate.reply.was.installed.in.keystore",
"\u8A3C\u660E\u66F8\u5FDC\u7B54\u304C\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3055\u308C\u307E\u3057\u305F"},
{"Certificate.reply.was.not.installed.in.keystore",
"\u8A3C\u660E\u66F8\u5FDC\u7B54\u304C\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F"},
{"Certificate.was.added.to.keystore",
"\u8A3C\u660E\u66F8\u304C\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u8FFD\u52A0\u3055\u308C\u307E\u3057\u305F"},
{"Certificate.was.not.added.to.keystore",
"\u8A3C\u660E\u66F8\u304C\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u8FFD\u52A0\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F"},
{".Storing.ksfname.", "[{0}\u3092\u683C\u7D0D\u4E2D]"},
{"alias.has.no.public.key.certificate.",
"{0}\u306B\u306F\u516C\u958B\u30AD\u30FC(\u8A3C\u660E\u66F8)\u304C\u3042\u308A\u307E\u305B\u3093"},
{"Cannot.derive.signature.algorithm",
"\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093"},
{"Alias.alias.does.not.exist",
"\u5225\u540D<{0}>\u306F\u5B58\u5728\u3057\u307E\u305B\u3093"},
{"Alias.alias.has.no.certificate",
"\u5225\u540D<{0}>\u306B\u306F\u8A3C\u660E\u66F8\u304C\u3042\u308A\u307E\u305B\u3093"},
{"groupname.keysize.coexist",
"-groupname\u3068-keysize\u306E\u4E21\u65B9\u3092\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093"},
{"deprecate.keysize.for.ec",
"-keysize\u306E\u6307\u5B9A\u306B\u3088\u308BEC\u30AD\u30FC\u306E\u751F\u6210\u306F\u975E\u63A8\u5968\u3067\u3059\u3002\u304B\u308F\u308A\u306B\"-groupname %s\"\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002"},
{"Key.pair.not.generated.alias.alias.already.exists",
"\u30AD\u30FC\u30FB\u30DA\u30A2\u306F\u751F\u6210\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u5225\u540D<{0}>\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"},
{"Generating.keysize.bit.keyAlgName.key.pair.and.self.signed.certificate.sigAlgName.with.a.validity.of.validality.days.for",
"{3}\u65E5\u9593\u6709\u52B9\u306A{0}\u30D3\u30C3\u30C8\u306E{1}\u306E\u30AD\u30FC\u30FB\u30DA\u30A2\u3068\u81EA\u5DF1\u7F72\u540D\u578B\u8A3C\u660E\u66F8({2})\u3092\u751F\u6210\u3057\u3066\u3044\u307E\u3059\n\t\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u540D: {4}"},
{"Enter.key.password.for.alias.", "<{0}>\u306E\u30AD\u30FC\u30FB\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"},
{".RETURN.if.same.as.keystore.password.",
"\t(\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3068\u540C\u3058\u5834\u5408\u306FRETURN\u3092\u62BC\u3057\u3066\u304F\u3060\u3055\u3044): "},
{"Key.password.is.too.short.must.be.at.least.6.characters",
"\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u304C\u77ED\u3059\u304E\u307E\u3059 - 6\u6587\u5B57\u4EE5\u4E0A\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"},
{"Too.many.failures.key.not.added.to.keystore",
"\u969C\u5BB3\u304C\u591A\u3059\u304E\u307E\u3059 - \u30AD\u30FC\u306F\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u8FFD\u52A0\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F"},
{"Destination.alias.dest.already.exists",
"\u51FA\u529B\u5148\u306E\u5225\u540D<{0}>\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"},
{"Password.is.too.short.must.be.at.least.6.characters",
"\u30D1\u30B9\u30EF\u30FC\u30C9\u304C\u77ED\u3059\u304E\u307E\u3059 - 6\u6587\u5B57\u4EE5\u4E0A\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"},
{"Too.many.failures.Key.entry.not.cloned",
"\u969C\u5BB3\u304C\u591A\u3059\u304E\u307E\u3059\u3002\u30AD\u30FC\u30FB\u30A8\u30F3\u30C8\u30EA\u306E\u30AF\u30ED\u30FC\u30F3\u306F\u4F5C\u6210\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F"},
{"key.password.for.alias.", "<{0}>\u306E\u30AD\u30FC\u306E\u30D1\u30B9\u30EF\u30FC\u30C9"},
{"No.entries.from.identity.database.added",
"\u30A2\u30A4\u30C7\u30F3\u30C6\u30A3\u30C6\u30A3\u30FB\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u304B\u3089\u8FFD\u52A0\u3055\u308C\u305F\u30A8\u30F3\u30C8\u30EA\u306F\u3042\u308A\u307E\u305B\u3093"},
{"Alias.name.alias", "\u5225\u540D: {0}"},
{"Creation.date.keyStore.getCreationDate.alias.",
"\u4F5C\u6210\u65E5: {0,date}"},
{"alias.keyStore.getCreationDate.alias.",
"{0},{1,date}, "},
{"alias.", "{0}, "},
{"Entry.type.type.", "\u30A8\u30F3\u30C8\u30EA\u30FB\u30BF\u30A4\u30D7: {0}"},
{"Certificate.chain.length.", "\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u306E\u9577\u3055: "},
{"Certificate.i.1.", "\u8A3C\u660E\u66F8[{0,number,integer}]:"},
{"Certificate.fingerprint.SHA.256.", "\u8A3C\u660E\u66F8\u306E\u30D5\u30A3\u30F3\u30AC\u30D7\u30EA\u30F3\u30C8(SHA-256): "},
{"Keystore.type.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30BF\u30A4\u30D7: "},
{"Keystore.provider.", "\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30D7\u30ED\u30D0\u30A4\u30C0: "},
{"Your.keystore.contains.keyStore.size.entry",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u306F{0,number,integer}\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u307E\u3059"},
{"Your.keystore.contains.keyStore.size.entries",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u306F{0,number,integer}\u30A8\u30F3\u30C8\u30EA\u304C\u542B\u307E\u308C\u307E\u3059"},
{"Failed.to.parse.input", "\u5165\u529B\u306E\u69CB\u6587\u89E3\u6790\u306B\u5931\u6557\u3057\u307E\u3057\u305F"},
{"Empty.input", "\u5165\u529B\u304C\u3042\u308A\u307E\u305B\u3093"},
{"Not.X.509.certificate", "X.509\u8A3C\u660E\u66F8\u3067\u306F\u3042\u308A\u307E\u305B\u3093"},
{"alias.has.no.public.key", "{0}\u306B\u306F\u516C\u958B\u30AD\u30FC\u304C\u3042\u308A\u307E\u305B\u3093"},
{"alias.has.no.X.509.certificate", "{0}\u306B\u306FX.509\u8A3C\u660E\u66F8\u304C\u3042\u308A\u307E\u305B\u3093"},
{"New.certificate.self.signed.", "\u65B0\u3057\u3044\u8A3C\u660E\u66F8(\u81EA\u5DF1\u7F72\u540D\u578B):"},
{"Reply.has.no.certificates", "\u5FDC\u7B54\u306B\u306F\u8A3C\u660E\u66F8\u304C\u3042\u308A\u307E\u305B\u3093"},
{"Certificate.not.imported.alias.alias.already.exists",
"\u8A3C\u660E\u66F8\u306F\u30A4\u30F3\u30DD\u30FC\u30C8\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u5225\u540D<{0}>\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"},
{"Input.not.an.X.509.certificate", "\u5165\u529B\u306FX.509\u8A3C\u660E\u66F8\u3067\u306F\u3042\u308A\u307E\u305B\u3093"},
{"Certificate.already.exists.in.keystore.under.alias.trustalias.",
"\u8A3C\u660E\u66F8\u306F\u3001\u5225\u540D<{0}>\u306E\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"},
{"Do.you.still.want.to.add.it.no.",
"\u8FFD\u52A0\u3057\u307E\u3059\u304B\u3002[\u3044\u3044\u3048]: "},
{"Certificate.already.exists.in.system.wide.CA.keystore.under.alias.trustalias.",
"\u8A3C\u660E\u66F8\u306F\u3001\u5225\u540D<{0}>\u306E\u30B7\u30B9\u30C6\u30E0\u898F\u6A21\u306ECA\u30AD\u30FC\u30B9\u30C8\u30A2\u5185\u306B\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"},
{"Do.you.still.want.to.add.it.to.your.own.keystore.no.",
"\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u8FFD\u52A0\u3057\u307E\u3059\u304B\u3002 [\u3044\u3044\u3048]: "},
{"Trust.this.certificate.no.", "\u3053\u306E\u8A3C\u660E\u66F8\u3092\u4FE1\u983C\u3057\u307E\u3059\u304B\u3002 [\u3044\u3044\u3048]: "},
{"New.prompt.", "\u65B0\u898F{0}: "},
{"Passwords.must.differ", "\u30D1\u30B9\u30EF\u30FC\u30C9\u306F\u7570\u306A\u3063\u3066\u3044\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{"Re.enter.new.prompt.", "\u65B0\u898F{0}\u3092\u518D\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{"Re.enter.password.", "\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u518D\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{"Re.enter.new.password.", "\u65B0\u898F\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u518D\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{"They.don.t.match.Try.again", "\u4E00\u81F4\u3057\u307E\u305B\u3093\u3002\u3082\u3046\u4E00\u5EA6\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"},
{"Enter.prompt.alias.name.", "{0}\u306E\u5225\u540D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{"Enter.new.alias.name.RETURN.to.cancel.import.for.this.entry.",
"\u65B0\u3057\u3044\u5225\u540D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\t(\u3053\u306E\u30A8\u30F3\u30C8\u30EA\u306E\u30A4\u30F3\u30DD\u30FC\u30C8\u3092\u53D6\u308A\u6D88\u3059\u5834\u5408\u306FRETURN\u3092\u62BC\u3057\u3066\u304F\u3060\u3055\u3044): "},
{"Enter.alias.name.", "\u5225\u540D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: "},
{".RETURN.if.same.as.for.otherAlias.",
"\t(<{0}>\u3068\u540C\u3058\u5834\u5408\u306FRETURN\u3092\u62BC\u3057\u3066\u304F\u3060\u3055\u3044)"},
{"What.is.your.first.and.last.name.",
"\u59D3\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"},
{"What.is.the.name.of.your.organizational.unit.",
"\u7D44\u7E54\u5358\u4F4D\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"},
{"What.is.the.name.of.your.organization.",
"\u7D44\u7E54\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"},
{"What.is.the.name.of.your.City.or.Locality.",
"\u90FD\u5E02\u540D\u307E\u305F\u306F\u5730\u57DF\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"},
{"What.is.the.name.of.your.State.or.Province.",
"\u90FD\u9053\u5E9C\u770C\u540D\u307E\u305F\u306F\u5DDE\u540D\u306F\u4F55\u3067\u3059\u304B\u3002"},
{"What.is.the.two.letter.country.code.for.this.unit.",
"\u3053\u306E\u5358\u4F4D\u306B\u8A72\u5F53\u3059\u308B2\u6587\u5B57\u306E\u56FD\u30B3\u30FC\u30C9\u306F\u4F55\u3067\u3059\u304B\u3002"},
{"Is.name.correct.", "{0}\u3067\u3088\u308D\u3057\u3044\u3067\u3059\u304B\u3002"},
{"no", "\u3044\u3044\u3048"},
{"yes", "\u306F\u3044"},
{"y", "y"},
{".defaultValue.", " [{0}]: "},
{"Alias.alias.has.no.key",
"\u5225\u540D<{0}>\u306B\u306F\u30AD\u30FC\u304C\u3042\u308A\u307E\u305B\u3093"},
{"Alias.alias.references.an.entry.type.that.is.not.a.private.key.entry.The.keyclone.command.only.supports.cloning.of.private.key",
"\u5225\u540D<{0}>\u304C\u53C2\u7167\u3057\u3066\u3044\u308B\u30A8\u30F3\u30C8\u30EA\u30FB\u30BF\u30A4\u30D7\u306F\u79D8\u5BC6\u30AD\u30FC\u30FB\u30A8\u30F3\u30C8\u30EA\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002-keyclone\u30B3\u30DE\u30F3\u30C9\u306F\u79D8\u5BC6\u30AD\u30FC\u30FB\u30A8\u30F3\u30C8\u30EA\u306E\u30AF\u30ED\u30FC\u30F3\u4F5C\u6210\u306E\u307F\u3092\u30B5\u30DD\u30FC\u30C8\u3057\u307E\u3059"},
{".WARNING.WARNING.WARNING.",
"***************** WARNING WARNING WARNING *****************"},
{"Signer.d.", "\u7F72\u540D\u8005\u756A\u53F7%d:"},
{"Timestamp.", "\u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7:"},
{"Signature.", "\u7F72\u540D:"},
{"Certificate.owner.", "\u8A3C\u660E\u66F8\u306E\u6240\u6709\u8005: "},
{"Not.a.signed.jar.file", "\u7F72\u540D\u4ED8\u304DJAR\u30D5\u30A1\u30A4\u30EB\u3067\u306F\u3042\u308A\u307E\u305B\u3093"},
{"No.certificate.from.the.SSL.server",
"SSL\u30B5\u30FC\u30D0\u30FC\u304B\u3089\u306E\u8A3C\u660E\u66F8\u304C\u3042\u308A\u307E\u305B\u3093"},
{".The.integrity.of.the.information.stored.in.your.keystore.",
"*\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u4FDD\u5B58\u3055\u308C\u305F\u60C5\u5831\u306E\u6574\u5408\u6027\u306F*\n*\u691C\u8A3C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u6574\u5408\u6027\u3092\u691C\u8A3C\u3059\u308B\u306B\u306F*\n*\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002*"},
{".The.integrity.of.the.information.stored.in.the.srckeystore.",
"*\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306B\u4FDD\u5B58\u3055\u308C\u305F\u60C5\u5831\u306E\u6574\u5408\u6027\u306F*\n*\u691C\u8A3C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u6574\u5408\u6027\u3092\u691C\u8A3C\u3059\u308B\u306B\u306F*\n*\u30BD\u30FC\u30B9\u30FB\u30AD\u30FC\u30B9\u30C8\u30A2\u306E\u30D1\u30B9\u30EF\u30FC\u30C9\u3092\u5165\u529B\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002*"},
{"Certificate.reply.does.not.contain.public.key.for.alias.",
"\u8A3C\u660E\u66F8\u5FDC\u7B54\u306B\u306F\u3001<{0}>\u306E\u516C\u958B\u30AD\u30FC\u306F\u542B\u307E\u308C\u307E\u305B\u3093"},
{"Incomplete.certificate.chain.in.reply",
"\u5FDC\u7B54\u3057\u305F\u8A3C\u660E\u66F8\u30C1\u30A7\u30FC\u30F3\u306F\u4E0D\u5B8C\u5168\u3067\u3059"},
{"Top.level.certificate.in.reply.",
"\u5FDC\u7B54\u3057\u305F\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u306E\u8A3C\u660E\u66F8:\n"},
{".is.not.trusted.", "... \u306F\u4FE1\u983C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 "},
{"Install.reply.anyway.no.", "\u5FDC\u7B54\u3092\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3057\u307E\u3059\u304B\u3002[\u3044\u3044\u3048]: "},
{"Public.keys.in.reply.and.keystore.don.t.match",
"\u5FDC\u7B54\u3057\u305F\u516C\u958B\u30AD\u30FC\u3068\u30AD\u30FC\u30B9\u30C8\u30A2\u304C\u4E00\u81F4\u3057\u307E\u305B\u3093"},
{"Certificate.reply.and.certificate.in.keystore.are.identical",
"\u8A3C\u660E\u66F8\u5FDC\u7B54\u3068\u30AD\u30FC\u30B9\u30C8\u30A2\u5185\u306E\u8A3C\u660E\u66F8\u304C\u540C\u3058\u3067\u3059"},
{"Failed.to.establish.chain.from.reply",
"\u5FDC\u7B54\u304B\u3089\u9023\u9396\u3092\u78BA\u7ACB\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"},
{"n", "n"},
{"Wrong.answer.try.again", "\u5FDC\u7B54\u304C\u9593\u9055\u3063\u3066\u3044\u307E\u3059\u3002\u3082\u3046\u4E00\u5EA6\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"},
{"Secret.key.not.generated.alias.alias.already.exists",
"\u79D8\u5BC6\u30AD\u30FC\u306F\u751F\u6210\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u5225\u540D<{0}>\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059"},
{"Please.provide.keysize.for.secret.key.generation",
"\u79D8\u5BC6\u30AD\u30FC\u306E\u751F\u6210\u6642\u306B\u306F -keysize\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"},
{"warning.not.verified.make.sure.keystore.is.correct",
"\u8B66\u544A: \u691C\u8A3C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002-keystore\u304C\u6B63\u3057\u3044\u3053\u3068\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002"},
{"Extensions.", "\u62E1\u5F35: "},
{".Empty.value.", "(\u7A7A\u306E\u5024)"},
{"Extension.Request.", "\u62E1\u5F35\u30EA\u30AF\u30A8\u30B9\u30C8:"},
{"Unknown.keyUsage.type.", "\u4E0D\u660E\u306AkeyUsage\u30BF\u30A4\u30D7: "},
{"Unknown.extendedkeyUsage.type.", "\u4E0D\u660E\u306AextendedkeyUsage\u30BF\u30A4\u30D7: "},
{"Unknown.AccessDescription.type.", "\u4E0D\u660E\u306AAccessDescription\u30BF\u30A4\u30D7: "},
{"Unrecognized.GeneralName.type.", "\u8A8D\u8B58\u3055\u308C\u306A\u3044GeneralName\u30BF\u30A4\u30D7: "},
{"This.extension.cannot.be.marked.as.critical.",
"\u3053\u306E\u62E1\u5F35\u306F\u30AF\u30EA\u30C6\u30A3\u30AB\u30EB\u3068\u3057\u3066\u30DE\u30FC\u30AF\u4ED8\u3051\u3067\u304D\u307E\u305B\u3093\u3002 "},
{"Odd.number.of.hex.digits.found.", "\u5947\u6570\u306E16\u9032\u6570\u304C\u898B\u3064\u304B\u308A\u307E\u3057\u305F: "},
{"Unknown.extension.type.", "\u4E0D\u660E\u306A\u62E1\u5F35\u30BF\u30A4\u30D7: "},
{"command.{0}.is.ambiguous.", "\u30B3\u30DE\u30F3\u30C9{0}\u306F\u3042\u3044\u307E\u3044\u3067\u3059:"},
// 8171319: keytool should print out warnings when reading or
// generating cert/cert req using weak algorithms
{"the.certificate.request", "\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8"},
{"the.issuer", "\u767A\u884C\u8005"},
{"the.generated.certificate", "\u751F\u6210\u3055\u308C\u305F\u8A3C\u660E\u66F8"},
{"the.generated.crl", "\u751F\u6210\u3055\u308C\u305FCRL"},
{"the.generated.certificate.request", "\u751F\u6210\u3055\u308C\u305F\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8"},
{"the.certificate", "\u8A3C\u660E\u66F8"},
{"the.crl", "CRL"},
{"the.tsa.certificate", "TSA\u8A3C\u660E\u66F8"},
{"the.input", "\u5165\u529B"},
{"reply", "\u5FDC\u7B54"},
{"one.in.many", "%1$s #%2$d / %3$d"},
{"alias.in.cacerts", "cacerts\u5185\u306E\u767A\u884C\u8005<%s>"},
{"alias.in.keystore", "\u767A\u884C\u8005<%s>"},
{"with.weak", "%s (\u5F31)"},
{"key.bit", "%1$d\u30D3\u30C3\u30C8%2$s\u30AD\u30FC"},
{"key.bit.weak", "%1$d\u30D3\u30C3\u30C8%2$s\u30AD\u30FC(\u5F31)"},
{"unknown.size.1", "\u4E0D\u660E\u306A\u30B5\u30A4\u30BA\u306E%s\u30AD\u30FC"},
{".PATTERN.printX509Cert.with.weak",
"\u6240\u6709\u8005: {0}\n\u767A\u884C\u8005: {1}\n\u30B7\u30EA\u30A2\u30EB\u756A\u53F7: {2}\n\u6709\u52B9\u671F\u9593\u306E\u958B\u59CB\u65E5: {3}\u7D42\u4E86\u65E5: {4}\n\u8A3C\u660E\u66F8\u306E\u30D5\u30A3\u30F3\u30AC\u30D7\u30EA\u30F3\u30C8:\n\t SHA1: {5}\n\t SHA256: {6}\n\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u540D: {7}\n\u30B5\u30D6\u30B8\u30A7\u30AF\u30C8\u516C\u958B\u30AD\u30FC\u30FB\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0: {8}\n\u30D0\u30FC\u30B8\u30E7\u30F3: {9}"},
{"PKCS.10.with.weak",
"PKCS #10\u8A3C\u660E\u66F8\u30EA\u30AF\u30A8\u30B9\u30C8(\u30D0\u30FC\u30B8\u30E7\u30F31.0)\n\u30B5\u30D6\u30B8\u30A7\u30AF\u30C8: %1$s\n\u30D5\u30A9\u30FC\u30DE\u30C3\u30C8: %2$s\n\u516C\u958B\u30AD\u30FC: %3$s\n\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0: %4$s\n"},
{"verified.by.s.in.s.weak", "%2$s\u5185\u306E%1$s\u306B\u3088\u308A%3$s\u3067\u691C\u8A3C\u3055\u308C\u307E\u3057\u305F"},
{"whose.sigalg.risk", "%1$s\u306F%2$s\u7F72\u540D\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3092\u4F7F\u7528\u3057\u3066\u304A\u308A\u3001\u3053\u308C\u306F\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u307E\u3059\u3002"},
{"whose.key.risk", "%1$s\u306F%2$s\u3092\u4F7F\u7528\u3057\u3066\u304A\u308A\u3001\u3053\u308C\u306F\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30EA\u30B9\u30AF\u3068\u307F\u306A\u3055\u308C\u307E\u3059\u3002"},
{"jks.storetype.warning", "%1$s\u30AD\u30FC\u30B9\u30C8\u30A2\u306F\u72EC\u81EA\u306E\u5F62\u5F0F\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059\u3002\"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"\u3092\u4F7F\u7528\u3059\u308B\u696D\u754C\u6A19\u6E96\u306E\u5F62\u5F0F\u3067\u3042\u308BPKCS12\u306B\u79FB\u884C\u3059\u308B\u3053\u3068\u3092\u304A\u85A6\u3081\u3057\u307E\u3059\u3002"},
{"migrate.keystore.warning", "\"%1$s\"\u304C%4$s\u306B\u79FB\u884C\u3055\u308C\u307E\u3057\u305F\u3002%2$s\u30AD\u30FC\u30B9\u30C8\u30A2\u306F\"%3$s\"\u3068\u3057\u3066\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7\u3055\u308C\u307E\u3059\u3002"},
{"backup.keystore.warning", "\u5143\u306E\u30AD\u30FC\u30B9\u30C8\u30A2\"%1$s\"\u306F\"%3$s\"\u3068\u3057\u3066\u30D0\u30C3\u30AF\u30A2\u30C3\u30D7\u3055\u308C\u307E\u3059..."},
{"importing.keystore.status", "\u30AD\u30FC\u30B9\u30C8\u30A2%1$s\u3092%2$s\u306B\u30A4\u30F3\u30DD\u30FC\u30C8\u3057\u3066\u3044\u307E\u3059..."},
{"keyalg.option.1.missing.warning", "-keyalg\u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u30C7\u30D5\u30A9\u30EB\u30C8\u306E\u30AD\u30FC\u30FB\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0(%s)\u306F\u3001\u65E7\u5F0F\u306E\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0\u3067\u3001\u73FE\u5728\u306F\u63A8\u5968\u3055\u308C\u307E\u305B\u3093\u3002JDK\u306E\u5F8C\u7D9A\u306E\u30EA\u30EA\u30FC\u30B9\u3067\u306F\u3001\u30C7\u30D5\u30A9\u30EB\u30C8\u306F\u524A\u9664\u3055\u308C\u308B\u4E88\u5B9A\u3067\u3001-keyalg\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u6307\u5B9A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
{"showinfo.no.option", "-showinfo\u306E\u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u3042\u308A\u307E\u305B\u3093\u3002\"keytool -showinfo -tls\"\u3092\u8A66\u3057\u3066\u304F\u3060\u3055\u3044\u3002"},
};
/**
* Returns the contents of this <code>ResourceBundle</code>.
*
* <p>
*
* @return the contents of this <code>ResourceBundle</code>.
*/
@Override
public Object[][] getContents() {
return contents;
}
}
| gpl-2.0 |
JoBeMa/Life2 | backoffice/clientws/a/engservice/holders/CategoryHolder.java | 555 | /**
* CategoryHolder.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package net.i2cat.csade.life2.backoffice.clientws.a.engservice.holders;
public final class CategoryHolder implements javax.xml.rpc.holders.Holder {
public net.i2cat.csade.life2.backoffice.clientws.a.engservice.Category value;
public CategoryHolder() {
}
public CategoryHolder(net.i2cat.csade.life2.backoffice.clientws.a.engservice.Category value) {
this.value = value;
}
}
| gpl-2.0 |
Lotusun/OfficeHelper | src/main/java/com/charlesdream/office/word/enums/WdLayoutMode.java | 2574 | package com.charlesdream.office.word.enums;
import com.charlesdream.office.BaseEnum;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* Specifies how text is laid out in the layout mode for the current document.
* <p>
*
* @author Charles Cui on 3/4/16.
* @since 1.0
*/
public enum WdLayoutMode implements BaseEnum {
/**
* No grid is used to lay out text.
*
* @since 1.0
*/
wdLayoutModeDefault(0),
/**
* Text is laid out on a grid; the user specifies the number of lines and the number of characters per line. As the user types, Microsoft Word automatically aligns characters with gridlines.
*
* @since 1.0
*/
wdLayoutModeGenko(3),
/**
* Text is laid out on a grid; the user specifies the number of lines and the number of characters per line. As the user types, Microsoft Word doesn't automatically align characters with gridlines.
*
* @since 1.0
*/
wdLayoutModeGrid(1),
/**
* Text is laid out on a grid; the user specifies the number of lines, but not the number of characters per line.
*
* @since 1.0
*/
wdLayoutModeLineGrid(2);
private static final Map<Integer, WdLayoutMode> lookup;
static {
lookup = new HashMap<>();
for (WdLayoutMode e : EnumSet.allOf(WdLayoutMode.class)) {
lookup.put(e.value(), e);
}
}
private final int value;
WdLayoutMode(int value) {
this.value = value;
}
/**
* Find the enum type by its value.
*
* @param value The enum value.
* @return The enum type, or null if this enum value does not exists.
* @since 1.0
*/
public static WdLayoutMode find(int value) {
WdLayoutMode result = lookup.get(value);
return result;
}
/**
* Find the enum type by its value, with the default value.
*
* @param value The enum value.
* @param defaultValue The default return value if the enum value does not exists.
* @return The enum type, or the default value if this enum value does not exists.
* @since 1.0
*/
public static WdLayoutMode find(int value, WdLayoutMode defaultValue) {
WdLayoutMode result = WdLayoutMode.find(value);
if (result == null) {
result = defaultValue;
}
return result;
}
/**
* Get the value of a enum type.
*
* @return The value of a enum type.
* @since 1.0
*/
public int value() {
return this.value;
}
}
| gpl-2.0 |
onlychoice/ws-xmpp-proxy | src/java/com/netease/xmpp/websocket/handler/NettyWebSocketChannelHandler.java | 12857 | package com.netease.xmpp.websocket.handler;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
import org.jboss.netty.handler.codec.http.HttpHeaders.Values;
import org.jboss.netty.handler.codec.http.websocket.WebSocketFrame;
import org.jboss.netty.handler.codec.http.websocket.WebSocketFrameDecoder;
import org.jboss.netty.handler.codec.http.websocket.WebSocketFrameEncoder;
import org.jboss.netty.util.CharsetUtil;
import org.jivesoftware.multiplexer.spi.ClientFailoverDeliverer;
import com.netease.xmpp.websocket.CMWebSocketConnection;
import com.netease.xmpp.websocket.codec.Hybi10WebSocketFrameDecoder;
import com.netease.xmpp.websocket.codec.Hybi10WebSocketFrameEncoder;
import com.netease.xmpp.websocket.codec.Pong;
import sun.misc.BASE64Encoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Executor;
import static org.jboss.netty.handler.codec.http.HttpHeaders.isKeepAlive;
import static org.jboss.netty.handler.codec.http.HttpHeaders.setContentLength;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.ORIGIN;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_KEY1;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_KEY2;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_LOCATION;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_ORIGIN;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.UPGRADE;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.WEBSOCKET_LOCATION;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.WEBSOCKET_ORIGIN;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.WEBSOCKET_PROTOCOL;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.WEBSOCKET;
import static org.jboss.netty.handler.codec.http.HttpMethod.GET;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class NettyWebSocketChannelHandler extends SimpleChannelUpstreamHandler {
private static final MessageDigest SHA_1;
static {
try {
SHA_1 = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
throw new InternalError("SHA-1 not supported on this platform");
}
}
private static final String ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private static final BASE64Encoder encoder = new BASE64Encoder();
private static final Charset ASCII = Charset.forName("ASCII");
protected final Executor executor;
protected final WebSocketHandler handler;
protected CMWebSocketConnection webSocketConnection;
public NettyWebSocketChannelHandler(Executor executor, WebSocketHandler handler) {
this.handler = handler;
this.executor = executor;
}
@Override
public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
Object msg = e.getMessage();
if (msg instanceof HttpRequest) {
handleHttpRequest(ctx, (HttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
}
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
executor.execute(new Runnable() {
@Override
public void run() {
try {
handler.onClose(webSocketConnection);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception {
System.out.println("EXCEPTION");
e.getChannel().close();
e.getCause().printStackTrace();
}
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
// Allow only GET .
if (req.getMethod() != GET) {
sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN));
return;
}
// Serve the WebSocket handshake request.
if (Values.UPGRADE.equalsIgnoreCase(req.getHeader(CONNECTION))
&& WEBSOCKET.equalsIgnoreCase(req.getHeader(Names.UPGRADE))) {
// Create the WebSocket handshake response.
HttpResponse res = new DefaultHttpResponse(HTTP_1_1, new HttpResponseStatus(101,
"Web Socket Protocol Handshake"));
res.addHeader(Names.UPGRADE, WEBSOCKET);
res.addHeader(CONNECTION, Values.UPGRADE);
prepareConnection(req, res, ctx);
try {
handler.onOpen(this.webSocketConnection);
} catch (Exception e) {
// TODO
e.printStackTrace();
}
}
}
private void handleWebSocketFrame(ChannelHandlerContext ctx, final WebSocketFrame frame) {
try {
if (frame instanceof Pong) {
handler.onPong(webSocketConnection, frame.getTextData());
} else {
if (frame.isText()) {
handler.onMessage(webSocketConnection, frame.getTextData());
} else {
handler.onMessage(webSocketConnection, frame.getBinaryData().array());
}
}
} catch (Throwable t) {
// TODO
t.printStackTrace();
}
}
private void prepareConnection(HttpRequest req, HttpResponse res, ChannelHandlerContext ctx) {
this.webSocketConnection = new CMWebSocketConnection(ctx.getChannel(),
new ClientFailoverDeliverer());
if (isHybi10WebSocketRequest(req)) {
this.webSocketConnection.setVersion(WebSocketConnection.Version.HYBI_10);
upgradeResponseHybi10(req, res);
ctx.getChannel().write(res);
adjustPipelineToHybi(ctx);
} else if (isHixie76WebSocketRequest(req)) {
this.webSocketConnection.setVersion(WebSocketConnection.Version.HIXIE_76);
upgradeResponseHixie76(req, res);
ctx.getChannel().write(res);
adjustPipelineToHixie(ctx);
} else {
this.webSocketConnection.setVersion(WebSocketConnection.Version.HIXIE_75);
upgradeResponseHixie75(req, res);
ctx.getChannel().write(res);
adjustPipelineToHixie(ctx);
}
}
private void adjustPipelineToHixie(ChannelHandlerContext ctx) {
ChannelPipeline p = ctx.getChannel().getPipeline();
p.remove("aggregator");
p.replace("decoder", "wsdecoder", new WebSocketFrameDecoder());
p.replace("handler", "wshandler", this);
p.replace("encoder", "wsencoder", new WebSocketFrameEncoder());
}
private void adjustPipelineToHybi(ChannelHandlerContext ctx) {
ChannelPipeline p = ctx.getChannel().getPipeline();
p.remove("aggregator");
p.replace("decoder", "wsdecoder", new Hybi10WebSocketFrameDecoder());
p.replace("handler", "wshandler", this);
p.replace("encoder", "wsencoder", new Hybi10WebSocketFrameEncoder());
}
private boolean isHybi10WebSocketRequest(HttpRequest req) {
return req.containsHeader("Sec-WebSocket-Version");
}
private boolean isHixie76WebSocketRequest(HttpRequest req) {
return req.containsHeader(SEC_WEBSOCKET_KEY1) && req.containsHeader(SEC_WEBSOCKET_KEY2);
}
private static synchronized String generateAccept(String key) {
String s = key + ACCEPT_GUID;
byte[] b = SHA_1.digest(s.getBytes(ASCII));
return encoder.encode(b);
}
private void upgradeResponseHybi10(HttpRequest req, HttpResponse res) {
String version = req.getHeader("Sec-WebSocket-Version");
if (!"8".equals(version)) {
res.setStatus(HttpResponseStatus.UPGRADE_REQUIRED);
res.setHeader("Sec-WebSocket-Version", "8");
return;
}
String key = req.getHeader("Sec-WebSocket-Key");
if (key == null) {
res.setStatus(HttpResponseStatus.BAD_REQUEST);
return;
}
String accept = generateAccept(key);
res.setStatus(new HttpResponseStatus(101, "Switching Protocols"));
res.addHeader(UPGRADE, WEBSOCKET.toLowerCase());
res.addHeader(CONNECTION, UPGRADE);
res.addHeader("Sec-WebSocket-Accept", accept);
}
private void upgradeResponseHixie76(HttpRequest req, HttpResponse res) {
res.setStatus(new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
res.addHeader(UPGRADE, WEBSOCKET);
res.addHeader(CONNECTION, UPGRADE);
res.addHeader(SEC_WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
res.addHeader(SEC_WEBSOCKET_LOCATION, getWebSocketLocation(req));
String protocol = req.getHeader(SEC_WEBSOCKET_PROTOCOL);
if (protocol != null) {
res.addHeader(SEC_WEBSOCKET_PROTOCOL, protocol);
}
// Calculate the answer of the challenge.
String key1 = req.getHeader(SEC_WEBSOCKET_KEY1);
String key2 = req.getHeader(SEC_WEBSOCKET_KEY2);
int a = (int) (Long.parseLong(key1.replaceAll("[^0-9]", "")) / key1.replaceAll("[^ ]", "")
.length());
int b = (int) (Long.parseLong(key2.replaceAll("[^0-9]", "")) / key2.replaceAll("[^ ]", "")
.length());
long c = req.getContent().readLong();
ChannelBuffer input = ChannelBuffers.buffer(16);
input.writeInt(a);
input.writeInt(b);
input.writeLong(c);
try {
ChannelBuffer output = ChannelBuffers.wrappedBuffer(MessageDigest.getInstance("MD5")
.digest(input.array()));
res.setContent(output);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private void upgradeResponseHixie75(HttpRequest req, HttpResponse res) {
res.setStatus(new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
res.addHeader(UPGRADE, WEBSOCKET);
res.addHeader(CONNECTION, HttpHeaders.Values.UPGRADE);
res.addHeader(WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
res.addHeader(WEBSOCKET_LOCATION, getWebSocketLocation(req));
String protocol = req.getHeader(WEBSOCKET_PROTOCOL);
if (protocol != null) {
res.addHeader(WEBSOCKET_PROTOCOL, protocol);
}
}
private String getWebSocketLocation(HttpRequest req) {
return "ws://" + req.getHeader(HttpHeaders.Names.HOST) + req.getUri();
}
private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
// Generate an error page if response status code is not OK (200).
if (res.getStatus().getCode() != 200) {
res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(),
CharsetUtil.UTF_8));
setContentLength(res, res.getContent().readableBytes());
}
// Send the response and close the connection if necessary.
ChannelFuture f = ctx.getChannel().write(res);
if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
}
| gpl-2.0 |
dynamo2/tianma | mycrm/src/main/java/com/dynamo2/myerp/crm/dao/entities/Person.java | 4328 | package com.dynamo2.myerp.crm.dao.entities;
// Generated Mar 20, 2012 11:10:03 AM by Hibernate Tools 3.4.0.CR1
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
/**
* Person generated by hbm2java
*/
@Entity
@Table(name = "person", catalog = "mycrm")
public class Person implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String firstName;
private String lastName;
private Date birthday;
private String gender;
private String idType;
private String idNum;
private String phone;
private String mobile;
private String email;
private Date created;
private String lastModifiedBy;
private String createdBy;
private Date lastModified;
public Person() {
}
public Person(Date lastModified) {
this.lastModified = lastModified;
}
public Person(String firstName, String lastName, Date birthday, String gender, String idType, String idNum,
String phone, String mobile, String email, Date created, String lastModifiedBy, String createdBy,
Date lastModified, String title) {
this.firstName = firstName;
this.lastName = lastName;
this.birthday = birthday;
this.gender = gender;
this.idType = idType;
this.idNum = idNum;
this.phone = phone;
this.mobile = mobile;
this.email = email;
this.created = created;
this.lastModifiedBy = lastModifiedBy;
this.createdBy = createdBy;
this.lastModified = lastModified;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "first_name", length = 45)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", length = 45)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "birthday", length = 19)
public Date getBirthday() {
return this.birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Column(name = "gender", length = 45)
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Column(name = "id_type", length = 45)
public String getIdType() {
return this.idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
@Column(name = "id_num", length = 45)
public String getIdNum() {
return this.idNum;
}
public void setIdNum(String idNum) {
this.idNum = idNum;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created", length = 19)
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
@Column(name = "last_modified_by", length = 45)
public String getLastModifiedBy() {
return this.lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
@Column(name = "created_by", length = 45)
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_modified", nullable = false, length = 19)
public Date getLastModified() {
return this.lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
@Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name = "mobile")
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Transient
public String getRealName() {
return lastName + " " + firstName;
}
}
| gpl-2.0 |
NationalLibraryOfNorway/Bibliotekstatistikk | old-and-depricated/annualstatistic/src/main/java/no/abmu/abmstatistikk/annualstatistic/service/SchemaReport.java | 10238 | /*
* Created on Dec 7, 2004
*
* This is the object given to the web-form.
* It's a mapping between the report as seen from the JSP-code to the
* way it's used in the service and domain layers.
*/
package no.abmu.abmstatistikk.annualstatistic.service;
import java.beans.XMLEncoder;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import no.abmu.abmstatistikk.annualstatistic.domain.Answer;
import no.abmu.abmstatistikk.annualstatistic.domain.Report;
import no.abmu.abmstatistikk.annualstatistic.domain.Schema;
/**
* @author Henning Kulander <hennikul@linpro.no>
*
*/
public class SchemaReport {
private static final Log logger = (Log) LogFactory.getLog(SchemaReport.class);
private Schema schema;
private Report report;
private ReportHelper reportHelper;
private Class[] fieldClasses;
protected Map field;
private Map comment;
private SchemaReport virtualSchemaReport;
public SchemaReport(Report report) {
this.report = report;
this.reportHelper = new ReportHelper(report);
this.schema = report.getSchema();
Set answers = report.getAnswers();
field = new HashMap();
comment = new HashMap();
if (answers != null) {
Iterator answerIterator = answers.iterator();
int i = 0;
fieldClasses = new Class[answers.size()+1];
while (answerIterator.hasNext()) {
Answer answer = (Answer) answerIterator.next();
field.put(answer.getField().getName(), answer);
comment.put(answer.getField().getName(), answer.getComment());
i++;
}
fieldClasses[i] = Report.class;
} else {
logger.error("No answers for current report!");
}
}
/* (non-Javadoc)
* @see no.abmu.abmstatistikk.util.DynamicBeanFactory.BeanAdapter#setProperty(java.lang.String, java.lang.Object)
*/
public Map getField() {
return field;
}
public void setField(Map newfield) {
field = newfield;
}
public void setProperty(String name, Object value) {
if (name.startsWith("field")) {
String fieldName = name.substring(5);
logger.debug("Setting answer for field "+fieldName+" to "+value);
Answer answer = reportHelper.getAnswerByFieldName(fieldName);
if (answer != null) {
String stringValue = (String) value;
answer.setValue(stringValue);
return;
}
} else if (name.startsWith("comment")) {
String fieldName = name.substring(7);
logger.debug("Setting comment for field "+fieldName+" to "+value);
Answer answer = reportHelper.getAnswerByFieldName(fieldName);
if (answer != null) {
String stringComment = (String) value;
answer.setComment(stringComment);
return;
}
}
logger.error("setProperty called for unhandled property "+name);
logger.error(" - Current schema is "+report.getSchema().getShortname());
}
/* (non-Javadoc)
* @see no.abmu.abmstatistikk.util.DynamicBeanFactory.BeanAdapter#getProperty(java.lang.String)
*/
public Object getProperty(String name) {
if (name.startsWith("field")) {
String fieldName = name.substring(5);
logger.debug("Returning answer for field "+fieldName);
Answer answer = reportHelper.getAnswerByFieldName(fieldName);
if (answer != null) {
logger.debug("Value is "+answer.getValue());
return answer;
} else {
logger.error("Trying to get unexisting answer for field "
+fieldName);
}
} else if (name.equals("report")) {
return report;
}
return null;
}
/**
* @return
*/
public Class[] getFieldClasses() {
return fieldClasses;
}
/**
* @return the report associated with the schemareport.
*/
public Report getReport() {
return report;
}
/**
* @param errors
*/
public void validate(Errors errors, String schemaName) {
validate(errors, schemaName, null);
}
/**
* @param errors : Spring errors object where errors are registered.
* @param schemaName : Name of the schema used from JSP
* @param fieldKeys : Set of key-names to validate, normally keys in
* one page
*/
public void validate(Errors errors, String schemaName, Set fieldKeys) {
if (fieldKeys == null) { /* Validate all fields */
fieldKeys = field.keySet();
}
/* Call setProperty for all fields to update values in report object */
Iterator fieldKeysIterator = fieldKeys.iterator();
while (fieldKeysIterator.hasNext()) {
String key = (String) fieldKeysIterator.next();
Answer unstoredAnswer = (Answer) field.get(key);
String unstoredComment = (String) comment.get(key);
if (unstoredComment != null) {
if (unstoredComment.equals("")) {
unstoredComment = null;
}
logger.debug("Found comment for "+key+": "+unstoredComment);
setProperty("comment"+key, unstoredComment);
}
if (unstoredAnswer != null) {
String value = unstoredAnswer.getValue();
if (value != null && value.equals("")) {
value = null;
}
if (unstoredAnswer.getPassedvalidation().equals(new Integer(1))){
logger.debug("Field "+key+" was marked as validated.");
value = null; // Checkboxes are not returned when cleared.
unstoredAnswer.setPassedvalidation(new Integer(0));
}
logger.debug("Updating field "+key+" with value "+value
+" has passed validation? "
+unstoredAnswer.getPassedvalidation());
setProperty("field"+key, value);
} else { /* Checkboxes are reset when hidden _FIELD input is used */
unstoredAnswer = (Answer) getProperty("field"+key);
if (unstoredAnswer == null) {
logger.error("No answer object for field "+key
+" in schema "+schemaName
+" This should be an unchecked checkbox.");
} else {
unstoredAnswer.setValue(null);
field.put(key, unstoredAnswer);
}
}
}
/* Autocalculate autocalculated field with new values */
reportHelper.autoCalculate();
/* Iterate through all fields and validate updated answer for field */
fieldKeysIterator = fieldKeys.iterator();
while (fieldKeysIterator.hasNext()) {
String key = (String) fieldKeysIterator.next();
Answer storedAnswer = (Answer) getProperty("field"+key);
if (storedAnswer != null) {
AnswerHelper answerHelper =
new AnswerHelper(storedAnswer);
String error = answerHelper.validate();
if (error != null) {
logger.debug("Error: "+ error+" for field "+key
+" "+errors.getObjectName());
errors.rejectValue("field['"+key+"']",
error, "Unknown error: "+error);
errors.rejectValue("field"+key,
error, "Unknown error: "+error);
if (error.startsWith("schema.error.change")) {
errors.rejectValue("comment['"+key+"']",
error, "Unknown error: "+error);
errors.rejectValue("comment"+key,
error, "Unknown error: "+error);
}
}
} else {
logger.error("Couldn't find stored answer for field "+key+
" in schema "+schemaName);
}
}
/* If there were no errors, mark all answers as validated to fix
* problem clearing checkboxes. */
if (!errors.hasErrors() || errors.hasErrors()) {
fieldKeysIterator = fieldKeys.iterator();
while (fieldKeysIterator.hasNext()) {
String key = (String) fieldKeysIterator.next();
logger.debug("Setting "+key+" as validated.");
Answer validatedAnswer = (Answer) getProperty("field"+key);
validatedAnswer.setPassedvalidation(new Integer(1));
}
}
}
public void dumpAsXML(OutputStream out) {
XMLEncoder e = new XMLEncoder(out);
Map stringMap = new HashMap();
Schema schema = report.getSchema();
stringMap.put("schematype", schema.getShortname());
stringMap.put("valid_from", schema.getStartdate());
stringMap.put("valid_to", schema.getStopdate());
stringMap.put("organisation_id", new Long(report.getOrganisationid()));
Set fields = field.keySet();
Iterator fieldIterator = fields.iterator();
while (fieldIterator.hasNext()) {
String fieldName = (String) fieldIterator.next();
Answer fieldAnswer = (Answer) field.get(fieldName);
stringMap.put(fieldName, fieldAnswer.getValue());
}
e.writeObject(stringMap);
e.close();
}
/**
* @return Returns the comment.
*/
public Map getComment() {
return comment;
}
/**
* @param comment The comment to set.
*/
public void setComment(Map comment) {
this.comment = comment;
}
/**
* @return Returns the virtualSchemaReport.
*/
public SchemaReport getVirtualSchemaReport() {
return virtualSchemaReport;
}
/**
* @param virtualSchemaReport The virtualSchemaReport to set.
*/
public void setVirtualSchemaReport(SchemaReport virtualSchemaReport) {
this.virtualSchemaReport = virtualSchemaReport;
}
} | gpl-2.0 |
shaun2029/Wifi-Reset | src/uk/co/immutablefix/wifireset/NetTask.java | 628 | // Copyright 2013 Shaun Simpson shauns2029@gmail.com
package uk.co.immutablefix.wifireset;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.os.AsyncTask;
public class NetTask extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... params)
{
InetAddress addr = null;
try
{
addr = InetAddress.getByName(params[0]);
}
catch (UnknownHostException e)
{
}
if (addr != null)
return addr.getHostAddress();
else
return null;
}
} | gpl-2.0 |
DIY-green/AndroidStudyDemo | DesignPatternStudy/src/main/java/com/cheng/zenofdesignpatterns/patterns/state/liftstate/OpenningState.java | 725 | package com.cheng.zenofdesignpatterns.patterns.state.liftstate;
/**
* 在电梯门开启的状态下能做什么事情
*/
public class OpenningState extends LiftState {
// 开启当然可以关闭了,我就想测试一下电梯门开关功能
@Override
public void close() {
// 状态修改
super.context.setLiftState(LiftContext.closeingState);
// 动作委托为CloseState来执行
super.context.getLiftState().close();
}
// 打开电梯门
@Override
public void open() {
System.out.println("电梯门开启...");
}
// 门开着电梯就想跑,这电梯,吓死你!
@Override
public void run() {
// do nothing;
}
// 开门还不停止?
public void stop() {
// do nothing;
}
}
| gpl-2.0 |
mohlerm/hotspot_cached_profiles | test/gc/TestVerifySilently.java | 2959 | /*
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test TestVerifySilently.java
* @key gc
* @bug 8032771
* @summary Test silent verification.
* @library /testlibrary
* @modules java.base/sun.misc
* java.management
*/
import jdk.test.lib.OutputAnalyzer;
import jdk.test.lib.ProcessTools;
import java.util.ArrayList;
import java.util.Collections;
class RunSystemGC {
public static void main(String args[]) throws Exception {
System.gc();
}
}
public class TestVerifySilently {
private static String[] getTestJavaOpts() {
String testVmOptsStr = System.getProperty("test.java.opts");
if (!testVmOptsStr.isEmpty()) {
return testVmOptsStr.split(" ");
} else {
return new String[] {};
}
}
private static OutputAnalyzer runTest(boolean verifySilently) throws Exception {
ArrayList<String> vmOpts = new ArrayList();
Collections.addAll(vmOpts, getTestJavaOpts());
Collections.addAll(vmOpts, new String[] {"-XX:+UnlockDiagnosticVMOptions",
"-XX:+VerifyDuringStartup",
"-XX:+VerifyBeforeGC",
"-XX:+VerifyAfterGC",
(verifySilently ? "-Xlog:gc":"-Xlog:gc+verify=debug"),
RunSystemGC.class.getName()});
ProcessBuilder pb =
ProcessTools.createJavaProcessBuilder(vmOpts.toArray(new String[vmOpts.size()]));
OutputAnalyzer output = new OutputAnalyzer(pb.start());
System.out.println("Output:\n" + output.getOutput());
return output;
}
public static void main(String args[]) throws Exception {
OutputAnalyzer output;
output = runTest(false);
output.shouldContain("Verifying");
output.shouldHaveExitValue(0);
output = runTest(true);
output.shouldNotContain("Verifying");
output.shouldHaveExitValue(0);
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.swat/de.metas.swat.base/src/main/java/de/metas/inoutcandidate/modelvalidator/M_InOutLine_Shipment.java | 1640 | package de.metas.inoutcandidate.modelvalidator;
/*
* #%L
* de.metas.swat.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import org.adempiere.ad.modelvalidator.annotations.ModelChange;
import org.adempiere.ad.modelvalidator.annotations.Validator;
import org.compiere.model.I_M_InOutLine;
import org.compiere.model.ModelValidator;
@Validator(I_M_InOutLine.class)
public class M_InOutLine_Shipment
{
@ModelChange(
timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE, ModelValidator.TYPE_AFTER_NEW },
ifColumnsChanged = I_M_InOutLine.COLUMNNAME_MovementQty)
public void onMovementQtyChange(final I_M_InOutLine inOutLine)
{
// All code from here was moved to de.metas.handlingunits.model.validator.M_InOutLine.onMovementQtyChange(I_M_InOutLine)
// because we need to be aware if this is about HUs or not....
// TODO: implement a generic approach is applies the algorithm without actually going through HUs stuff
}
}
| gpl-2.0 |
the-fascinator/fascinator-portal | src/main/java/com/googlecode/fascinator/portal/services/PortalManager.java | 1896 | /*
* The Fascinator - Portal
* Copyright (C) 2008-2011 University of Southern Queensland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.googlecode.fascinator.portal.services;
import com.googlecode.fascinator.portal.Portal;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface PortalManager {
public static final String DEFAULT_PORTAL_NAME = "default";
public static final String DEFAULT_SKIN = "default";
public static final String DEFAULT_DISPLAY = "default";
public static final String DEFAULT_PORTAL_HOME = "portal";
public static final String DEFAULT_PORTAL_HOME_DEV = "src/main/config/portal";
public Map<String, Portal> getPortals();
public Portal getDefault();
public File getHomeDir();
public Portal get(String name);
public boolean exists(String name);
public void add(Portal portal);
public void remove(String name);
public void save(Portal portal);
public void reharvest(String objectId);
public void reharvest(Set<String> objectIds);
public String getDefaultPortal();
public String getDefaultDisplay();
public List<String> getSkinPriority();
}
| gpl-2.0 |
malacroix/stimesheet | src/main/java/ca/lc/stimesheet/web/login/userdetails/TimesheetUserDetails.java | 883 | /**
*
*/
package ca.lc.stimesheet.web.login.userdetails;
import java.util.ArrayList;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import ca.lc.stimesheet.model.User;
/**
* @author Marc-Andre Lacroix
*
*/
public class TimesheetUserDetails extends org.springframework.security.core.userdetails.User {
private static final long serialVersionUID = 3452519087909202050L;
private User internalUser;
/**
* Creates a Timesheet user details with the actual {@link User} infos.
* @param internalUser
*/
public TimesheetUserDetails(User internalUser) {
super(internalUser.getUuid(), "", new ArrayList<SimpleGrantedAuthority>());
this.internalUser = internalUser;
}
/**
* @return the internalUser
*/
public User getInternalUser() {
return internalUser;
}
}
| gpl-2.0 |
diging/quadriga | Quadriga/src/main/java/edu/asu/spring/quadriga/dao/profile/impl/ProfileManagerDAO.java | 6447 | package edu.asu.spring.quadriga.dao.profile.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import edu.asu.spring.quadriga.dao.impl.BaseDAO;
import edu.asu.spring.quadriga.dao.profile.IProfileManagerDAO;
import edu.asu.spring.quadriga.domain.IProfile;
import edu.asu.spring.quadriga.domain.factories.IProfileFactory;
import edu.asu.spring.quadriga.dto.QuadrigaUserprofileDTO;
import edu.asu.spring.quadriga.dto.QuadrigaUserprofileDTOPK;
import edu.asu.spring.quadriga.exceptions.QuadrigaStorageException;
import edu.asu.spring.quadriga.web.profile.impl.SearchResultBackBean;
/**
* this class manages addition, deletion, retrieval of the records for user
* profile table
*
* @author rohit pendbhaje
*
*/
@Repository
public class ProfileManagerDAO extends BaseDAO<QuadrigaUserprofileDTO> implements
IProfileManagerDAO {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private IProfileFactory profileFactory;
/**
* adds records in database table for the profile page
*
* @param name
* name of the loggedin user serviceId id of the service from
* which records are added resultBackBean this instance contains
* all the searchresult information selected by user
* @throws QuadrigaStorageException
* @author rohit pendbhaje
*
*/
@Override
public void addUserProfileDBRequest(String name, String serviceId,
SearchResultBackBean resultBackBean)
throws QuadrigaStorageException {
try {
Date date = new Date();
QuadrigaUserprofileDTO userProfile = new QuadrigaUserprofileDTO();
QuadrigaUserprofileDTOPK userProfileKey = new QuadrigaUserprofileDTOPK(
name, serviceId, resultBackBean.getId());
userProfile.setQuadrigaUserprofileDTOPK(userProfileKey);
userProfile.setProfilename(resultBackBean.getWord());
userProfile.setDescription(resultBackBean.getDescription());
userProfile.setQuadrigaUserDTO(getUserDTO(name));
userProfile.setCreatedby(name);
userProfile.setCreateddate(date);
userProfile.setUpdatedby(name);
userProfile.setUpdateddate(date);
sessionFactory.getCurrentSession().save(userProfile);
} catch (HibernateException ex) {
throw new QuadrigaStorageException("System error", ex);
}
}
/**
* retrieves records from database
*
* @param loggedinUser
* @return list of searchresultbackbeans
* @throws QuadrigaStorageException
* @author rohit pendbhaje
*
*/
@SuppressWarnings("unchecked")
@Override
public List<IProfile> getUserProfiles(String loggedinUser)
throws QuadrigaStorageException {
List<IProfile> userProfiles = new ArrayList<IProfile>();
try {
Query query = sessionFactory.getCurrentSession().getNamedQuery(
"QuadrigaUserprofileDTO.findByUsername");
query.setParameter("username", loggedinUser);
List<QuadrigaUserprofileDTO> userProfileList = query.list();
for (QuadrigaUserprofileDTO userProfile : userProfileList) {
IProfile profile = profileFactory.createProfile();
profile.setProfileId(userProfile
.getQuadrigaUserprofileDTOPK().getProfileid());
profile.setServiceId(userProfile
.getQuadrigaUserprofileDTOPK().getServiceid());
profile.setDescription(userProfile
.getDescription());
profile.setProfilename(userProfile.getProfilename());
userProfiles.add(profile);
}
} catch (Exception ex) {
throw new QuadrigaStorageException();
}
return userProfiles;
}
/**
* deletes profile record from table for particular profileid
*
* @param username
* name of loggedin user serviceid id of the service
* corresponding to the record profileId id of the profile for
* which record is to be deleted
* @throws QuadrigaStorageException
* @author rohit pendbhaje
*
*/
@Override
public void deleteUserProfileDBRequest(String username, String serviceid,
String profileId) throws QuadrigaStorageException {
try {
QuadrigaUserprofileDTOPK userProfileKey = new QuadrigaUserprofileDTOPK(
username, serviceid, profileId);
QuadrigaUserprofileDTO userProfile = (QuadrigaUserprofileDTO) sessionFactory
.getCurrentSession().get(QuadrigaUserprofileDTO.class,
userProfileKey);
sessionFactory.getCurrentSession().delete(userProfile);
} catch (Exception ex) {
throw new QuadrigaStorageException();
}
}
/**
* retrieves serviceid from table of particular profileid
*
* @param profileId
* id of the profile for which record is to be deleted
* @throws QuadrigaStorageException
* @author rohit pendbhaje
*
*/
@Override
public String retrieveServiceIdRequest(String profileid)
throws QuadrigaStorageException {
String serviceid = null;
try {
Query query = sessionFactory.getCurrentSession().getNamedQuery(
"QuadrigaUserprofileDTO.findByProfileid");
query.setParameter("profileid", profileid);
List<QuadrigaUserprofileDTO> userprofileList = query.list();
for (QuadrigaUserprofileDTO userprofile : userprofileList) {
serviceid = userprofile.getQuadrigaUserprofileDTOPK()
.getServiceid();
}
}
catch (Exception e) {
throw new QuadrigaStorageException("sorry");
}
return serviceid;
}
@Override
public QuadrigaUserprofileDTO getDTO(String id) {
return getDTO(QuadrigaUserprofileDTO.class, id);
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest08472.java | 2918 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest08472")
public class BenchmarkTest08472 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames.hasMoreElements()) {
param = headerNames.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
try {
java.util.Properties Benchmarkprops = new java.util.Properties();
Benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("Benchmark.properties"));
String algorithm = Benchmarkprops.getProperty("cryptoAlg1", "DESede/ECB/PKCS5Padding");
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm);
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
}
response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
Jacksson/mywms | server.app/los.inventory-ejb/src/de/linogistix/los/inventory/query/dto/OrderReceiptTO.java | 1492 | /*
* Copyright (c) 2006 - 2010 LinogistiX GmbH
*
* www.linogistix.com
*
* Project myWMS-LOS
*/
package de.linogistix.los.inventory.query.dto;
import java.util.Date;
import de.linogistix.los.inventory.model.LOSOrderRequestState;
import de.linogistix.los.inventory.model.OrderReceipt;
import de.linogistix.los.query.BODTO;
public class OrderReceiptTO extends BODTO<OrderReceipt> {
/**
*
*/
private static final long serialVersionUID = 1L;
public String orderNumber;
public String orderReference;
public Date date;
public String state;
public OrderReceiptTO(Long id, int version, String name){
super(id, version, name);
}
public OrderReceiptTO(Long id, int version, String name, String orderNumber, String orderreference, Date date, LOSOrderRequestState state){
super(id, version, name);
this.orderNumber = orderNumber;
this.orderReference = orderreference;
this.date = date;
this.state = state.toString();
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public String getOrderReference() {
return orderReference;
}
public void setOrderReference(String orderReference) {
this.orderReference = orderReference;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
| gpl-2.0 |
SRF-Consulting/NDOR-IRIS | src/us/mn/state/dot/tms/SystemAttrEnum.java | 14208 | /*
* IRIS -- Intelligent Roadway Information System
* Copyright (C) 2009-2015 Minnesota Department of Transportation
* Copyright (C) 2012 Iteris Inc.
* Copyright (C) 2014 AHMCT, University of California
* Copyright (C) 2015 SRF Consulting Group
*
* 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.
*/
package us.mn.state.dot.tms;
import java.util.HashMap;
import static us.mn.state.dot.tms.SignMessageHelper.DMS_MESSAGE_MAX_PAGES;
import us.mn.state.dot.tms.utils.I18N;
/**
* This enum defines all system attributes.
*
* @author Douglas Lau
* @author Michael Darter
* @author Travis Swanston
*/
public enum SystemAttrEnum {
CAMERA_AUTH_USERNAME(""),
CAMERA_AUTH_PASSWORD(""),
CAMERA_AUTOPLAY(true, Change.RESTART_CLIENT),
CAMERA_ID_BLANK(""),
CAMERA_NUM_PRESET_BTNS(3, 0, 20, Change.RESTART_CLIENT),
CAMERA_PRESET_PANEL_COLUMNS(6, 1, 6, Change.RESTART_CLIENT),
CAMERA_PRESET_PANEL_ENABLE(false, Change.RESTART_CLIENT),
CAMERA_PRESET_STORE_ENABLE(false, Change.RESTART_CLIENT),
CAMERA_PTZ_AXIS_COMPORT(1, 1, 64),
CAMERA_PTZ_AXIS_RESET(""),
CAMERA_PTZ_AXIS_WIPE(""),
CAMERA_PTZ_BLIND(true),
CAMERA_PTZ_PANEL_ENABLE(false, Change.RESTART_CLIENT),
CAMERA_STREAM_CONTROLS_ENABLE(false, Change.RESTART_CLIENT),
CAMERA_UTIL_PANEL_ENABLE(false, Change.RESTART_CLIENT),
CAMERA_WIPER_PRECIP_MM_HR(8, 1, 100),
CLIENT_UNITS_SI(true),
COMM_EVENT_PURGE_DAYS(14, 0, 1000),
DATABASE_VERSION(String.class, Change.RESTART_SERVER),
DETECTOR_AUTO_FAIL_ENABLE(true),
DIALUP_POLL_PERIOD_MINS(60, 2, 1440),
DMS_AWS_ENABLE(false),
DMS_BRIGHTNESS_ENABLE(true, Change.RESTART_CLIENT),
DMS_COMM_LOSS_MINUTES(5, 0, 60),
DMS_COMPOSER_EDIT_MODE(1, 0, 2, Change.RESTART_CLIENT),
DMS_DEFAULT_JUSTIFICATION_LINE(3, 2, 5, Change.RESTART_CLIENT),
DMS_DEFAULT_JUSTIFICATION_PAGE(2, 2, 4, Change.RESTART_CLIENT),
DMS_DURATION_ENABLE(true),
DMS_FONT_SELECTION_ENABLE(false, Change.RESTART_CLIENT),
DMS_FORM(1, 1, 2),
DMS_HIGH_TEMP_CUTOFF(60, 35, 100),
DMS_LAMP_TEST_TIMEOUT_SECS(30, 5, 90),
DMS_MANUFACTURER_ENABLE(true, Change.RESTART_CLIENT),
DMS_MAX_LINES(3, 1, 12, Change.RESTART_CLIENT),
DMS_MESSAGE_MIN_PAGES(1, 1, DMS_MESSAGE_MAX_PAGES,
Change.RESTART_CLIENT),
DMS_OP_STATUS_ENABLE(false, Change.RESTART_CLIENT),
DMS_PAGE_OFF_DEFAULT_SECS(0f, 0f, 60f),
DMS_PAGE_ON_DEFAULT_SECS(2f, 0f, 60f),
DMS_PAGE_ON_MAX_SECS(10.0f, 0f, 100f, Change.RESTART_CLIENT),
DMS_PAGE_ON_MIN_SECS(0.5f, 0f, 100f, Change.RESTART_CLIENT),
DMS_PAGE_ON_SELECTION_ENABLE(false),
DMS_PIXEL_OFF_LIMIT(2, 1),
DMS_PIXEL_ON_LIMIT(1, 1),
DMS_PIXEL_MAINT_THRESHOLD(35, 1),
DMS_PIXEL_STATUS_ENABLE(true, Change.RESTART_CLIENT),
DMS_PIXEL_TEST_TIMEOUT_SECS(30, 5, 90),
DMS_QUERYMSG_ENABLE(false, Change.RESTART_CLIENT),
DMS_QUICKMSG_STORE_ENABLE(false, Change.RESTART_CLIENT),
DMS_RESET_ENABLE(false, Change.RESTART_CLIENT),
DMS_SEND_CONFIRMATION_ENABLE(false, Change.RESTART_CLIENT),
DMS_UPDATE_FONT_TABLE(false),
DMSXML_MODEM_OP_TIMEOUT_SECS(5 * 60 + 5, 5),
DMSXML_OP_TIMEOUT_SECS(60 + 5, 5),
DMSXML_REINIT_DETECT(false),
EMAIL_SENDER_SERVER(String.class),
EMAIL_SMTP_HOST(String.class),
EMAIL_RECIPIENT_AWS(String.class),
EMAIL_RECIPIENT_DMSXML_REINIT(String.class),
EMAIL_RECIPIENT_GATE_ARM(String.class),
GATE_ARM_ALERT_TIMEOUT_SECS(90, 10),
GPS_NTCIP_ENABLE(false),
GPS_NTCIP_JITTER_M(100, 0, 1610),
HELP_TROUBLE_TICKET_ENABLE(false),
HELP_TROUBLE_TICKET_URL(String.class),
INCIDENT_CLEAR_SECS(600, 0, 3600),
LCS_POLL_PERIOD_SECS(30, 0, Change.RESTART_SERVER),
MAP_EXTENT_NAME_INITIAL("Home"),
MAP_ICON_SIZE_SCALE_MAX(30f, 0f, 9000f),
MAP_SEGMENT_MAX_METERS(2000, 100, Change.RESTART_CLIENT),
METER_EVENT_PURGE_DAYS(14, 0, 1000),
METER_GREEN_SECS(1.3f, 0.1f, 10f),
METER_MAX_RED_SECS(13f, 5f, 30f),
METER_MIN_RED_SECS(0.1f, 0.1f, 10f),
METER_YELLOW_SECS(0.7f, 0.1f, 10f),
MSG_FEED_VERIFY(true),
OPERATION_RETRY_THRESHOLD(3, 1, 20),
ROUTE_MAX_LEGS(8, 1, 20),
ROUTE_MAX_MILES(16, 1, 30),
RWIS_HIGH_WIND_SPEED_KPH(40, 0),
RWIS_LOW_VISIBILITY_DISTANCE_M(152, 0),
RWIS_OBS_AGE_LIMIT_SECS(240, 0),
RWIS_MAX_VALID_WIND_SPEED_KPH(282, 0),
SAMPLE_ARCHIVE_ENABLE(true),
SPEED_LIMIT_MIN_MPH(45, 0, 100),
SPEED_LIMIT_DEFAULT_MPH(55, 0, 100),
SPEED_LIMIT_MAX_MPH(75, 0, 100),
TESLA_HOST(String.class),
TRAVEL_TIME_MIN_MPH(15, 1, 50),
UPTIME_LOG_ENABLE(false),
VSA_BOTTLENECK_ID_MPH(55, 10, 65),
VSA_CONTROL_THRESHOLD(-1000, -5000, -200),
VSA_DOWNSTREAM_MILES(0.2f, 0f, 2.0f),
VSA_MAX_DISPLAY_MPH(60, 10, 60),
VSA_MIN_DISPLAY_MPH(30, 10, 55),
VSA_MIN_STATION_MILES(0.1f, 0.01f, 1.0f),
VSA_START_INTERVALS(3, 0, 10),
VSA_START_THRESHOLD(-1500, -5000, -200),
VSA_STOP_THRESHOLD(-750, -5000, -200),
WINDOW_TITLE("IRIS: ", Change.RESTART_CLIENT);
/** Change action, which indicates what action the admin must
* take after changing a system attribute. */
enum Change {
RESTART_SERVER("Restart the server after changing."),
RESTART_CLIENT("Restart the client after changing."),
NONE("A change takes effect immediately.");
/** Change message for user. */
private final String m_msg;
/** Constructor */
private Change(String msg) {
m_msg = msg;
}
/** Get the restart message. */
public String getMessage() {
return m_msg;
}
}
/** System attribute class */
protected final Class atype;
/** Default value */
protected final Object def_value;
/** Change action */
protected final Change change_action;
/** Minimum value for number attributes */
protected final Number min_value;
/** Maximum value for number attributes */
protected final Number max_value;
/** Create a String attribute with the given default value */
private SystemAttrEnum(String d) {
this(String.class, d, null, null, Change.NONE);
}
/** Create a String attribute with the given default value */
private SystemAttrEnum(String d, Change ca) {
this(String.class, d, null, null, ca);
}
/** Create a Boolean attribute with the given default value */
private SystemAttrEnum(boolean d) {
this(Boolean.class, d, null, null, Change.NONE);
}
/** Create a Boolean attribute with the given default value */
private SystemAttrEnum(boolean d, Change ca) {
this(Boolean.class, d, null, null, ca);
}
/** Create an Integer attribute with default, min and max values */
private SystemAttrEnum(int d, int mn, int mx) {
this(Integer.class, d, mn, mx, Change.NONE);
}
/** Create an Integer attribute with default, min and max values */
private SystemAttrEnum(int d, int mn, int mx, Change ca) {
this(Integer.class, d, mn, mx, ca);
}
/** Create an Integer attribute with default and min values */
private SystemAttrEnum(int d, int mn) {
this(Integer.class, d, mn, null, Change.NONE);
}
/** Create an Integer attribute with default and min values */
private SystemAttrEnum(int d, int mn, Change ca) {
this(Integer.class, d, mn, null, ca);
}
/** Create a Float attribute with default, min and max values */
private SystemAttrEnum(float d, float mn, float mx) {
this(Float.class, d, mn, mx, Change.NONE);
}
/** Create a Float attribute with default, min and max values */
private SystemAttrEnum(float d, float mn, float mx, Change ca) {
this(Float.class, d, mn, mx, ca);
}
/** Create a system attribute with a null default value */
private SystemAttrEnum(Class c) {
this(c, null, null, null, Change.NONE);
}
/** Create a system attribute with a null default value */
private SystemAttrEnum(Class c, Change ca) {
this(c, null, null, null, ca);
}
/** Create a system attribute */
private SystemAttrEnum(Class c, Object d, Number mn, Number mx,
Change ca)
{
atype = c;
def_value = d;
min_value = mn;
max_value = mx;
change_action = ca;
assert isValidBoolean() || isValidFloat() ||
isValidInteger() || isValidString();
}
/** Get a description of the system attribute enum. */
public static String getDesc(String aname) {
String ret = I18N.get(aname);
SystemAttrEnum sae = lookup(aname);
if(sae != null)
ret += " " + sae.change_action.getMessage();
return ret;
}
/** Return true if the value is the default value. */
public boolean equalsDefault() {
return get().toString().equals(getDefault());
}
/** Test if the attribute is a valid boolean */
private boolean isValidBoolean() {
return (atype == Boolean.class) &&
(def_value instanceof Boolean) &&
min_value == null && max_value == null;
}
/** Test if the attribute is a valid float */
private boolean isValidFloat() {
return (atype == Float.class) &&
(def_value instanceof Float) &&
(min_value == null || min_value instanceof Float) &&
(max_value == null || max_value instanceof Float);
}
/** Test if the attribute is a valid integer */
private boolean isValidInteger() {
return (atype == Integer.class) &&
(def_value instanceof Integer) &&
(min_value == null || min_value instanceof Integer) &&
(max_value == null || max_value instanceof Integer);
}
/** Test if the attribute is a valid string */
private boolean isValidString() {
return (atype == String.class) &&
(def_value == null || def_value instanceof String) &&
min_value == null && max_value == null;
}
/** Get the attribute name */
public String aname() {
return toString().toLowerCase();
}
/** Set of all system attributes */
static protected final HashMap<String, SystemAttrEnum> ALL_ATTRIBUTES =
new HashMap<String, SystemAttrEnum>();
static {
for(SystemAttrEnum sa: SystemAttrEnum.values())
ALL_ATTRIBUTES.put(sa.aname(), sa);
}
/** Lookup an attribute by name */
static public SystemAttrEnum lookup(String aname) {
return ALL_ATTRIBUTES.get(aname);
}
/**
* Get the value of the attribute as a string.
* @return The value of the attribute as a string, never null.
*/
public String getString() {
assert atype == String.class;
return (String)get();
}
/** Get the default value as a String. */
public String getDefault() {
if(def_value != null)
return def_value.toString();
else
return "";
}
/** Get the value of the attribute as a boolean */
public boolean getBoolean() {
assert atype == Boolean.class;
return (Boolean)get();
}
/** Get the value of the attribute as an int */
public int getInt() {
assert atype == Integer.class;
return (Integer)get();
}
/** Get the value of the attribute as a float */
public float getFloat() {
assert atype == Float.class;
return (Float)get();
}
/**
* Get the value of the attribute.
* @return The value of the attribute, never null.
*/
protected Object get() {
return getValue(SystemAttributeHelper.get(aname()));
}
/**
* Get the value of a system attribute.
* @param attr System attribute or null.
* @return The attribute value or the default value on error.
* Null is never returned.
*/
private Object getValue(SystemAttribute attr) {
if(attr == null) {
System.err.println(warningDefault());
return def_value;
}
return parseValue(attr.getValue());
}
/**
* Get the value of a system attribute.
* @return The parsed value or the default value on error.
* Null is never returned.
*/
public Object parseValue(String v) {
Object value = parse(v);
if(value == null) {
System.err.println(warningParse());
return def_value;
}
return value;
}
/**
* Parse an attribute value.
* @param v Attribute value, may be null.
* @return The parsed value or null on error.
*/
protected Object parse(String v) {
if(atype == String.class)
return v;
if(atype == Boolean.class)
return parseBoolean(v);
if(atype == Integer.class)
return parseInteger(v);
if(atype == Float.class)
return parseFloat(v);
assert false;
return null;
}
/** Parse a boolean attribute value */
protected Boolean parseBoolean(String v) {
try {
return Boolean.parseBoolean(v);
}
catch(NumberFormatException e) {
return null;
}
}
/** Parse an integer attribute value */
protected Integer parseInteger(String v) {
int i;
try {
i = Integer.parseInt(v);
}
catch(NumberFormatException e) {
return null;
}
if(min_value != null) {
int m = min_value.intValue();
if(i < m) {
System.err.println(warningMinimum());
return m;
}
}
if(max_value != null) {
int m = max_value.intValue();
if(i > m) {
System.err.println(warningMaximum());
return m;
}
}
return i;
}
/** Parse a float attribute value */
protected Float parseFloat(String v) {
float f;
try {
f = Float.parseFloat(v);
}
catch(NumberFormatException e) {
return null;
}
if(min_value != null) {
float m = min_value.floatValue();
if(f < m) {
System.err.println(warningMinimum());
return m;
}
}
if(max_value != null) {
float m = max_value.floatValue();
if(f > m) {
System.err.println(warningMaximum());
return m;
}
}
return f;
}
/** Create a 'missing system attribute' warning message */
protected String warningDefault() {
return "Warning: " + toString() + " system attribute was not " +
"found; using a default value (" + def_value + ").";
}
/** Create a parsing warning message */
protected String warningParse() {
return "Warning: " + toString() + " system attribute could " +
"not be parsed; using a default value (" +
def_value + ").";
}
/** Create a minimum value warning message */
protected String warningMinimum() {
return "Warning: " + toString() + " system attribute was too " +
"low; using a minimum value (" + min_value + ").";
}
/** Create a maximum value warning message */
protected String warningMaximum() {
return "Warning: " + toString() + " system attribute was too " +
"high; using a maximum value (" + max_value + ").";
}
}
| gpl-2.0 |
apostlez/algorithm-Exams | src/codejam2016_1st/Problem_4.java | 4964 | package codejam2016_1st;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Stack;
class Pair {
int _node;
int _dist;
Pair(int node, int dist) {
_node = node;
_dist = dist;
}
public int getDist() {
return _dist;
}
public int getNode() {
return _node;
}
public void setDist(int dist) {
_dist = dist;
}
}
class Comp implements Comparator<Pair>{
@Override
public int compare(Pair o1, Pair o2) {
if(o1.getNode() < o2.getNode()) {
return -1;
} else if(o1.getNode() > o2.getNode()) {
return 1;
} else if(o1.getDist() < o2.getDist()) {
return -1;
}
return 1;
}
}
public class Problem_4 {
public static void main(String[] args) {
try {
//start(args[0]);
start("problem_4_Set1.in");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static ArrayList<Pair> pairList[];
static ArrayList<Integer> addedCity;
static int addedDist[];
static int N;
static int Q, M, sum1, sum2;
static int dist[];
static void start(String filename) throws FileNotFoundException {
Scanner sc = new Scanner(new BufferedInputStream(new FileInputStream(filename)));
int tc = sc.nextInt();
while(tc-- > 0) {
addedCity = new ArrayList<Integer>();
pairList = new ArrayList[1000000];
addedDist = new int[1000000];
sum1 = 0;
sum2 = 0;
N = sc.nextInt();
for(int i=0;i<N;i++) {
pairList[i] = new ArrayList<Pair>();
}
Q = sc.nextInt();
for(int i=0; i<N-1; i++) {
int t = sc.nextInt();
int d = sc.nextInt();
pairList[i+1].add(new Pair(t-1, d));
pairList[t-1].add(new Pair(i+1, d));
}
// get M
for(int i=1;i<N; i++) {
if(pairList[i].size() == 1) {
addedCity.add(i);
}
}
M = addedCity.size();
for(int i=0; i<M; i++) {
int m = sc.nextInt();
addedDist[addedCity.get(i)] = m;
}
ArrayList<Integer> from = new ArrayList<Integer>();
ArrayList<Integer> to = new ArrayList<Integer>();
for(int i=0; i<Q; i++) {
from.add(sc.nextInt()-1);
to.add(sc.nextInt()-1);
}
for(int i=0; i<Q; i++) {
// need to ordering
if(from.get(i) != to.get(i)) {
getShortestDist(from.get(i), to.get(i));
}
}
// update new road
for(int i=0; i<M; i++) {
boolean found = false;
int m = addedCity.get(i);
for(int j=0; j<pairList[0].size(); j++) {
if(pairList[0].get(j).getNode() == m) {
found = true;
pairList[0].get(j).setDist(addedDist[addedCity.get(i)]);
}
}
if(found == false) pairList[0].add(new Pair(m, addedDist[addedCity.get(i)]));
found = false;
for(int j=0; j<pairList[m].size(); j++) {
if(pairList[m].get(j).getNode() == m) {
found = true;
pairList[m].get(j).setDist(addedDist[addedCity.get(i)]);
}
}
if(found == false) pairList[m].add(new Pair(0, addedDist[addedCity.get(i)]));
}
for(int i=0; i<Q; i++) {
// need to ordering
if(from.get(i) != to.get(i)) {
getShortestDistAdded(from.get(i), to.get(i));
}
}
System.out.println(sum1 + " " + sum2);
}
}
static void getShortestDist(int from, int to) {
int visited[] = new int[1000000];
dist = new int[1000000];
int n = 0, d;
Stack<Integer> path = new Stack<Integer>();
int currentIndex = 0;
path.push(from);
visited[from] = 1;
while(!path.isEmpty()) {
// 1. add next ordering by dist
currentIndex = path.pop();
ArrayList<Pair> current = pairList[currentIndex];
for(int j=0; j<current.size(); j++) {
n = current.get(j).getNode();
d = current.get(j).getDist();
if (visited[n] == 0 || (dist[n] == 0 || dist[currentIndex] + d < dist[n])) {
dist[n] = dist[currentIndex] + d;
path.push(n);
visited[n] = 1;
//System.out.println("from:" + currentIndex + " to:" + n);
}
}
}
//System.out.println("sum1:" + dist[to]);
sum1 += dist[to];
}
static void getShortestDistAdded(int from, int to) {
int visited[] = new int[1000000];
dist = new int[1000000];
int n = 0, d;
Stack<Integer> path = new Stack<Integer>();
int currentIndex = 0;
path.push(from);
visited[from] = 1;
while(!path.isEmpty()) {
// 1. add next ordering by dist
currentIndex = path.pop();
ArrayList<Pair> current = pairList[currentIndex];
for(int j=0; j<current.size(); j++) {
n = current.get(j).getNode();
d = current.get(j).getDist();
if (visited[n] == 0 || (dist[n] == 0 || dist[currentIndex] + d < dist[n])) {
dist[n] = dist[currentIndex] + d;
path.push(n);
visited[n] = 1;
//System.out.println("visit2:" + n);
}
}
}
//System.out.println("sum2:" + dist[to]);
sum2 += dist[to];
}
}
| gpl-2.0 |
sidgleyandrade/fsmTestCompleteness | fsmTestCompleteness/src/com/usp/icmc/labes/fsm/FsmTransition.java | 2070 | package com.usp.icmc.labes.fsm;
public class FsmTransition extends FsmElement{
private FsmState from;
private String input;
private String output;
private FsmState to;
public FsmTransition(){
super();
}
public FsmTransition(FsmState f, String in, String out, FsmState t) {
this();
from = f;
to = t;
input = in;
output = out;
f.getOut().add(this);
t.getIn().add(this);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
FsmTransition other = (FsmTransition) obj;
if (from == null) {
if (other.from != null)
return false;
} else if (!from.equals(other.from))
return false;
if (input == null) {
if (other.input != null)
return false;
} else if (!input.equals(other.input))
return false;
if (output == null) {
if (other.output != null)
return false;
} else if (!output.equals(other.output))
return false;
if (to == null) {
if (other.to != null)
return false;
} else if (!to.equals(other.to))
return false;
return true;
}
public FsmState getFrom() {
return from;
}
public String getInput() {
return input;
}
public String getOutput() {
return output;
}
public FsmState getTo() {
return to;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((from == null) ? 0 : from.hashCode());
result = prime * result + ((input == null) ? 0 : input.hashCode());
result = prime * result + ((output == null) ? 0 : output.hashCode());
result = prime * result + ((to == null) ? 0 : to.hashCode());
return result;
}
public void setFrom(FsmState from) {
this.from = from;
}
public void setInput(String input) {
this.input = input;
}
public void setOutput(String output) {
this.output = output;
}
public void setTo(FsmState to) {
this.to = to;
}
@Override
public String toString() {
return from+" -- "+input+" / "+output+" -> "+to;
}
}
| gpl-2.0 |
nachivpn/drogon | src/com/drogon/test/TestParser.java | 786 | package com.drogon.test;
import java.io.IOException;
import java.util.Iterator;
import com.drogon.core.Drogon;
/**
Contributors: Nachi
*/
public class TestParser {
public static void main(String[] args) {
String str = "Mozilla/5.0 (Linux; Android 4.4.2; SGH-T399N Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36";
try {
long start = System.currentTimeMillis();
for(int i=0;i<1;i++){
Drogon parser = new Drogon();
Iterator<String> iterator = parser.getProductList(str).iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
System.out.println("Time taken = "+(System.currentTimeMillis() - start)+"ms");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| gpl-2.0 |
epigenome/iTagPlot | src/Transform/QuantileTransform.java | 1436 | /*
* 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 Transform;
import Objects.TagList;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author SHKim12
*/
public class QuantileTransform implements Transform {
public QuantileTransform( TagList l ) {
if( l.size() == 0 ) m_QuantileVector = null;
ArrayList<Float> totalList = new ArrayList<>();
totalList.addAll(l);
Collections.sort(totalList);
int qvSize = QUANTILE_RESOLUTION<totalList.size()?QUANTILE_RESOLUTION:totalList.size();
m_QuantileVector = new ArrayList<>();
for( int i = 0; i < qvSize; ++i ) {
m_QuantileVector.add( totalList.get( i * totalList.size() / qvSize ) );
}
}
@Override
public float transform( float v ) {
int s = 0;
int e = m_QuantileVector.size();
int m = s;
while( s < e - 1) {
m = (s+e)/2;
Float mv = m_QuantileVector.get(m);
if( mv < v ) s = m;
else if( v < mv ) e = m;
else break;
}
return m / (float)(m_QuantileVector.size() - 1);
}
public final static int QUANTILE_RESOLUTION = 1000;
ArrayList<Float> m_QuantileVector;
}
| gpl-2.0 |
kartoFlane/superluminal2 | src/java/com/kartoflane/superluminal2/components/interfaces/Redrawable.java | 300 | package com.kartoflane.superluminal2.components.interfaces;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
public interface Redrawable extends PaintListener
{
/**
* Calls paintControl if the object is visible.
*/
public void redraw( PaintEvent e );
}
| gpl-2.0 |
meijmOrg/Repo-test | freelance-admin/src/java/com/yh/admin/roles/service/RoleFuncService.java | 129 | package com.yh.admin.roles.service;
/**
*
* @author zhangqp
* @version 1.0, 16/08/23
*/
public class RoleFuncService {
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/sun/io/ByteToCharISO8859_7.java | 1672 | /*
* Copyright 1996-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.io;
import sun.nio.cs.ISO_8859_7;
/**
* A table to convert ISO8859_7 to Unicode
*
* @author ConverterGenerator tool
*/
public class ByteToCharISO8859_7 extends ByteToCharSingleByte {
private final static ISO_8859_7 nioCoder = new ISO_8859_7();
public String getCharacterEncoding() {
return "ISO8859_7";
}
public ByteToCharISO8859_7() {
super.byteToCharTable = nioCoder.getDecoderSingleByteMappings();
}
}
| gpl-2.0 |
fozziethebeat/S-Space | src/main/java/edu/ucla/sspace/graph/LabeledGraph.java | 4550 | /*
* Copyright 2011 David Jurgens
*
* This file is part of the S-Space package and is covered under the terms and
* conditions therein.
*
* The S-Space package is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation and distributed hereunder to you.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
* EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
* NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
* PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
* WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
* RIGHTS.
*
* 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 edu.ucla.sspace.graph;
import edu.ucla.sspace.util.Indexer;
import edu.ucla.sspace.util.ObjectIndexer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* A decorator around all graph types that allows vertices to take on arbitrary
* labels. This class does not directly implement {@link Graph} but rather
* exposes the backing graph through the {@link #graph()} method, which ensures
* that the backing graph is of the appropriate type (or subtype).
*
* <p> The view returned by {@link #graph()} is read-only with respect to
* vertices (i.e., edges may be added or removed). This ensures that all vertex
* additions or removals to the graph are made through this class.
*/
public class LabeledGraph<L,E extends Edge>
extends GraphAdaptor<E> implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private final Graph<E> graph;
private final Indexer<L> vertexLabels;
public LabeledGraph(Graph<E> graph) {
this(graph, new ObjectIndexer<L>());
}
public LabeledGraph(Graph<E> graph, Indexer<L> vertexLabels) {
super(graph);
this.graph = graph;
this.vertexLabels = vertexLabels;
}
public boolean add(L vertexLabel) {
return add(vertexLabels.index(vertexLabel));
}
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if adding a vertex that has not
* previously been assigned a label
*/
public boolean add(int vertex) {
if (vertexLabels.lookup(vertex) == null)
throw new IllegalArgumentException("Cannot add a vertex without a label");
// The indexer may have already had the mapping without the graph having
// vertex, so check that the graph has the vertex
return super.add(vertex);
}
/**
* {@inheritDoc}
*/
@Override public LabeledGraph<L,E> copy(Set<Integer> vertices) {
Graph<E> g = super.copy(vertices);
// Create a copy of the labels.
// NOTE: this includes labels for vertices that may not be present in
// the new graph. Not sure if it's the correct behavior yet.
Indexer<L> labels = new ObjectIndexer<L>(vertexLabels);
return new LabeledGraph<L,E>(g, labels);
}
public boolean contains(L vertexLabel) {
return contains(vertexLabels.index(vertexLabel));
}
public boolean remove(L vertexLabel) {
return remove(vertexLabels.index(vertexLabel));
}
public String toString() {
StringBuilder sb = new StringBuilder(order() * 4 + size() * 10);
sb.append("vertices: [");
for (int v : vertices()) {
sb.append(vertexLabels.lookup(v)).append(',');
}
sb.setCharAt(sb.length() - 1, ']');
sb.append(" edges: [");
for (E e : edges()) {
L from = vertexLabels.lookup(e.from());
L to = vertexLabels.lookup(e.to());
String edge = (e instanceof DirectedEdge) ? "->" : "--";
sb.append('(').append(from).append(edge).append(to);
if (e instanceof TypedEdge) {
TypedEdge<?> t = (TypedEdge<?>)e;
sb.append(':').append(t.edgeType());
}
if (e instanceof WeightedEdge) {
WeightedEdge w = (WeightedEdge)e;
sb.append(", ").append(w.weight());
}
sb.append("), ");
}
sb.setCharAt(sb.length() - 2, ']');
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
} | gpl-2.0 |
cobexer/fullsync | fullsync-ui/src/main/java/net/sourceforge/fullsync/ui/SystemStatusPage.java | 5577 | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* For information about the authors of this project Have a look
* at the AUTHORS file in the root of this project.
*/
package net.sourceforge.fullsync.ui;
import java.util.Timer;
import java.util.TimerTask;
import javax.inject.Inject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
class SystemStatusPage extends WizardDialog {
private Label totalMemory;
private Label maxMemory;
private Label freeMemory;
private ProgressBar progressBarMemory;
private Timer timer;
private Composite content;
@Inject
public SystemStatusPage(Shell shell) {
super(shell);
}
@Override
public String getTitle() {
return Messages.getString("SystemStatusPage.Title"); //$NON-NLS-1$
}
@Override
public String getCaption() {
return Messages.getString("SystemStatusPage.Caption"); //$NON-NLS-1$
}
@Override
public String getDescription() {
return Messages.getString("SystemStatusPage.Description"); //$NON-NLS-1$
}
@Override
public String getIconName() {
return null;
}
@Override
public String getImageName() {
return null;
}
@Override
public void createContent(final Composite content) {
this.content = content;
// FIXME: add interesting versions and the system properties used by the launcher,...
// TODO: add a way to report a bug here?
try {
content.setLayout(new GridLayout());
var groupMemory = new Group(content, SWT.NONE);
groupMemory.setLayout(new GridLayout(2, false));
groupMemory.setText(Messages.getString("SystemStatusPage.JVMMemory")); //$NON-NLS-1$
progressBarMemory = new ProgressBar(groupMemory, SWT.NONE);
var progressBarMemoryLData = new GridData();
progressBarMemoryLData.horizontalAlignment = SWT.FILL;
progressBarMemoryLData.horizontalSpan = 2;
progressBarMemory.setLayoutData(progressBarMemoryLData);
// max memory
var labelMaxMemory = new Label(groupMemory, SWT.NONE);
labelMaxMemory.setText(Messages.getString("SystemStatusPage.MaxMemory")); //$NON-NLS-1$
maxMemory = new Label(groupMemory, SWT.RIGHT);
var maxMemoryLData = new GridData();
maxMemoryLData.horizontalAlignment = SWT.FILL;
maxMemory.setLayoutData(maxMemoryLData);
// total memory
var labelTotalMemory = new Label(groupMemory, SWT.NONE);
labelTotalMemory.setText(Messages.getString("SystemStatusPage.TotalMemory")); //$NON-NLS-1$
totalMemory = new Label(groupMemory, SWT.RIGHT);
var totalMemoryLData = new GridData();
totalMemoryLData.horizontalAlignment = SWT.FILL;
totalMemory.setLayoutData(totalMemoryLData);
// free memory
var labelFreeMemory = new Label(groupMemory, SWT.NONE);
labelFreeMemory.setText(Messages.getString("SystemStatusPage.FreeMemory")); //$NON-NLS-1$
freeMemory = new Label(groupMemory, SWT.RIGHT);
freeMemory.setText(""); //$NON-NLS-1$
var freeMemoryLData = new GridData();
freeMemoryLData.horizontalAlignment = SWT.FILL;
freeMemory.setLayoutData(freeMemoryLData);
// gc button
var buttonMemoryGc = new Button(groupMemory, SWT.PUSH | SWT.CENTER);
buttonMemoryGc.setText(Messages.getString("SystemStatusPage.CleanUp")); //$NON-NLS-1$
var buttonMemoryGcLData = new GridData();
buttonMemoryGc.addListener(SWT.Selection, e -> System.gc());
buttonMemoryGcLData.horizontalAlignment = SWT.END;
buttonMemoryGcLData.horizontalSpan = 2;
buttonMemoryGc.setLayoutData(buttonMemoryGcLData);
timerFired();
timer = new Timer(true);
timer.schedule(new TimerTask() {
@Override
public void run() {
timerFired();
}
}, 1000, 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean apply() {
return true;
}
@Override
public boolean cancel() {
return true;
}
private void timerFired() {
if (!content.isDisposed()) {
var display = getDisplay();
if ((null == display) || display.isDisposed()) {
timer.cancel();
return;
}
display.asyncExec(this::updateView);
}
}
private void updateView() {
if (!content.isDisposed()) {
var rt = Runtime.getRuntime();
var ltotalMemory = rt.totalMemory();
var lmaxMemory = rt.maxMemory();
var lfreeMemory = rt.freeMemory();
totalMemory.setText(UISettings.formatSize(ltotalMemory));
maxMemory.setText(UISettings.formatSize(lmaxMemory));
freeMemory.setText(UISettings.formatSize(lfreeMemory));
progressBarMemory.setMaximum((int) (ltotalMemory / 1024));
progressBarMemory.setSelection((int) ((ltotalMemory - lfreeMemory) / 1024));
content.layout();
}
}
@Override
public void dispose() {
timer.cancel();
super.dispose();
}
}
| gpl-2.0 |
shelan/jdk9-mirror | nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Lower.java | 32007 | /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.internal.codegen;
import static jdk.nashorn.internal.codegen.CompilerConstants.EVAL;
import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN;
import static jdk.nashorn.internal.ir.Expression.isAlwaysTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Pattern;
import jdk.nashorn.internal.ir.AccessNode;
import jdk.nashorn.internal.ir.BaseNode;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.ir.Block;
import jdk.nashorn.internal.ir.BlockLexicalContext;
import jdk.nashorn.internal.ir.BlockStatement;
import jdk.nashorn.internal.ir.BreakNode;
import jdk.nashorn.internal.ir.CallNode;
import jdk.nashorn.internal.ir.CaseNode;
import jdk.nashorn.internal.ir.CatchNode;
import jdk.nashorn.internal.ir.DebuggerNode;
import jdk.nashorn.internal.ir.ContinueNode;
import jdk.nashorn.internal.ir.EmptyNode;
import jdk.nashorn.internal.ir.Expression;
import jdk.nashorn.internal.ir.ExpressionStatement;
import jdk.nashorn.internal.ir.ForNode;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.FunctionNode.CompilationState;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.IfNode;
import jdk.nashorn.internal.ir.IndexNode;
import jdk.nashorn.internal.ir.JumpStatement;
import jdk.nashorn.internal.ir.JumpToInlinedFinally;
import jdk.nashorn.internal.ir.LabelNode;
import jdk.nashorn.internal.ir.LexicalContext;
import jdk.nashorn.internal.ir.LiteralNode;
import jdk.nashorn.internal.ir.LiteralNode.PrimitiveLiteralNode;
import jdk.nashorn.internal.ir.LoopNode;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.ReturnNode;
import jdk.nashorn.internal.ir.RuntimeNode;
import jdk.nashorn.internal.ir.Statement;
import jdk.nashorn.internal.ir.SwitchNode;
import jdk.nashorn.internal.ir.Symbol;
import jdk.nashorn.internal.ir.ThrowNode;
import jdk.nashorn.internal.ir.TryNode;
import jdk.nashorn.internal.ir.VarNode;
import jdk.nashorn.internal.ir.WhileNode;
import jdk.nashorn.internal.ir.WithNode;
import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;
import jdk.nashorn.internal.ir.visitor.NodeVisitor;
import jdk.nashorn.internal.parser.Token;
import jdk.nashorn.internal.parser.TokenType;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.Source;
import jdk.nashorn.internal.runtime.logging.DebugLogger;
import jdk.nashorn.internal.runtime.logging.Loggable;
import jdk.nashorn.internal.runtime.logging.Logger;
/**
* Lower to more primitive operations. After lowering, an AST still has no symbols
* and types, but several nodes have been turned into more low level constructs
* and control flow termination criteria have been computed.
*
* We do things like code copying/inlining of finallies here, as it is much
* harder and context dependent to do any code copying after symbols have been
* finalized.
*/
@Logger(name="lower")
final class Lower extends NodeOperatorVisitor<BlockLexicalContext> implements Loggable {
private final DebugLogger log;
// Conservative pattern to test if element names consist of characters valid for identifiers.
// This matches any non-zero length alphanumeric string including _ and $ and not starting with a digit.
private static Pattern SAFE_PROPERTY_NAME = Pattern.compile("[a-zA-Z_$][\\w$]*");
/**
* Constructor.
*/
Lower(final Compiler compiler) {
super(new BlockLexicalContext() {
@Override
public List<Statement> popStatements() {
final List<Statement> newStatements = new ArrayList<>();
boolean terminated = false;
final List<Statement> statements = super.popStatements();
for (final Statement statement : statements) {
if (!terminated) {
newStatements.add(statement);
if (statement.isTerminal() || statement instanceof JumpStatement) { //TODO hasGoto? But some Loops are hasGoto too - why?
terminated = true;
}
} else {
statement.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
@Override
public boolean enterVarNode(final VarNode varNode) {
newStatements.add(varNode.setInit(null));
return false;
}
});
}
}
return newStatements;
}
@Override
protected Block afterSetStatements(final Block block) {
final List<Statement> stmts = block.getStatements();
for(final ListIterator<Statement> li = stmts.listIterator(stmts.size()); li.hasPrevious();) {
final Statement stmt = li.previous();
// popStatements() guarantees that the only thing after a terminal statement are uninitialized
// VarNodes. We skip past those, and set the terminal state of the block to the value of the
// terminal state of the first statement that is not an uninitialized VarNode.
if(!(stmt instanceof VarNode && ((VarNode)stmt).getInit() == null)) {
return block.setIsTerminal(this, stmt.isTerminal());
}
}
return block.setIsTerminal(this, false);
}
});
this.log = initLogger(compiler.getContext());
}
@Override
public DebugLogger getLogger() {
return log;
}
@Override
public DebugLogger initLogger(final Context context) {
return context.getLogger(this.getClass());
}
@Override
public boolean enterBreakNode(final BreakNode breakNode) {
addStatement(breakNode);
return false;
}
@Override
public Node leaveCallNode(final CallNode callNode) {
return checkEval(callNode.setFunction(markerFunction(callNode.getFunction())));
}
@Override
public Node leaveCatchNode(final CatchNode catchNode) {
return addStatement(catchNode);
}
@Override
public boolean enterContinueNode(final ContinueNode continueNode) {
addStatement(continueNode);
return false;
}
@Override
public boolean enterDebuggerNode(final DebuggerNode debuggerNode) {
final int line = debuggerNode.getLineNumber();
final long token = debuggerNode.getToken();
final int finish = debuggerNode.getFinish();
addStatement(new ExpressionStatement(line, token, finish, new RuntimeNode(token, finish, RuntimeNode.Request.DEBUGGER, new ArrayList<Expression>())));
return false;
}
@Override
public boolean enterJumpToInlinedFinally(final JumpToInlinedFinally jumpToInlinedFinally) {
addStatement(jumpToInlinedFinally);
return false;
}
@Override
public boolean enterEmptyNode(final EmptyNode emptyNode) {
return false;
}
@Override
public Node leaveIndexNode(final IndexNode indexNode) {
final String name = getConstantPropertyName(indexNode.getIndex());
if (name != null) {
// If index node is a constant property name convert index node to access node.
assert Token.descType(indexNode.getToken()) == TokenType.LBRACKET;
return new AccessNode(indexNode.getToken(), indexNode.getFinish(), indexNode.getBase(), name);
}
return super.leaveIndexNode(indexNode);
}
// If expression is a primitive literal that is not an array index and does return its string value. Else return null.
private static String getConstantPropertyName(final Expression expression) {
if (expression instanceof LiteralNode.PrimitiveLiteralNode) {
final Object value = ((LiteralNode) expression).getValue();
if (value instanceof String && SAFE_PROPERTY_NAME.matcher((String) value).matches()) {
return (String) value;
}
}
return null;
}
@Override
public Node leaveExpressionStatement(final ExpressionStatement expressionStatement) {
final Expression expr = expressionStatement.getExpression();
ExpressionStatement node = expressionStatement;
final FunctionNode currentFunction = lc.getCurrentFunction();
if (currentFunction.isProgram()) {
if (!isInternalExpression(expr) && !isEvalResultAssignment(expr)) {
node = expressionStatement.setExpression(
new BinaryNode(
Token.recast(
expressionStatement.getToken(),
TokenType.ASSIGN),
compilerConstant(RETURN),
expr));
}
}
return addStatement(node);
}
@Override
public Node leaveBlockStatement(final BlockStatement blockStatement) {
return addStatement(blockStatement);
}
@Override
public Node leaveForNode(final ForNode forNode) {
ForNode newForNode = forNode;
final Expression test = forNode.getTest();
if (!forNode.isForIn() && isAlwaysTrue(test)) {
newForNode = forNode.setTest(lc, null);
}
newForNode = checkEscape(newForNode);
if(newForNode.isForIn()) {
// Wrap it in a block so its internally created iterator is restricted in scope
addStatementEnclosedInBlock(newForNode);
} else {
addStatement(newForNode);
}
return newForNode;
}
@Override
public Node leaveFunctionNode(final FunctionNode functionNode) {
log.info("END FunctionNode: ", functionNode.getName());
return functionNode.setState(lc, CompilationState.LOWERED);
}
@Override
public Node leaveIfNode(final IfNode ifNode) {
return addStatement(ifNode);
}
@Override
public Node leaveIN(final BinaryNode binaryNode) {
return new RuntimeNode(binaryNode);
}
@Override
public Node leaveINSTANCEOF(final BinaryNode binaryNode) {
return new RuntimeNode(binaryNode);
}
@Override
public Node leaveLabelNode(final LabelNode labelNode) {
return addStatement(labelNode);
}
@Override
public Node leaveReturnNode(final ReturnNode returnNode) {
addStatement(returnNode); //ReturnNodes are always terminal, marked as such in constructor
return returnNode;
}
@Override
public Node leaveCaseNode(final CaseNode caseNode) {
// Try to represent the case test as an integer
final Node test = caseNode.getTest();
if (test instanceof LiteralNode) {
final LiteralNode<?> lit = (LiteralNode<?>)test;
if (lit.isNumeric() && !(lit.getValue() instanceof Integer)) {
if (JSType.isRepresentableAsInt(lit.getNumber())) {
return caseNode.setTest((Expression)LiteralNode.newInstance(lit, lit.getInt32()).accept(this));
}
}
}
return caseNode;
}
@Override
public Node leaveSwitchNode(final SwitchNode switchNode) {
if(!switchNode.isUniqueInteger()) {
// Wrap it in a block so its internally created tag is restricted in scope
addStatementEnclosedInBlock(switchNode);
} else {
addStatement(switchNode);
}
return switchNode;
}
@Override
public Node leaveThrowNode(final ThrowNode throwNode) {
return addStatement(throwNode); //ThrowNodes are always terminal, marked as such in constructor
}
@SuppressWarnings("unchecked")
private static <T extends Node> T ensureUniqueNamesIn(final T node) {
return (T)node.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
@Override
public Node leaveFunctionNode(final FunctionNode functionNode) {
final String name = functionNode.getName();
return functionNode.setName(lc, lc.getCurrentFunction().uniqueName(name));
}
@Override
public Node leaveDefault(final Node labelledNode) {
return labelledNode.ensureUniqueLabels(lc);
}
});
}
private static Block createFinallyBlock(final Block finallyBody) {
final List<Statement> newStatements = new ArrayList<>();
for (final Statement statement : finallyBody.getStatements()) {
newStatements.add(statement);
if (statement.hasTerminalFlags()) {
break;
}
}
return finallyBody.setStatements(null, newStatements);
}
private Block catchAllBlock(final TryNode tryNode) {
final int lineNumber = tryNode.getLineNumber();
final long token = tryNode.getToken();
final int finish = tryNode.getFinish();
final IdentNode exception = new IdentNode(token, finish, lc.getCurrentFunction().uniqueName(CompilerConstants.EXCEPTION_PREFIX.symbolName()));
final Block catchBody = new Block(token, finish, new ThrowNode(lineNumber, token, finish, new IdentNode(exception), true));
assert catchBody.isTerminal(); //ends with throw, so terminal
final CatchNode catchAllNode = new CatchNode(lineNumber, token, finish, new IdentNode(exception), null, catchBody, true);
final Block catchAllBlock = new Block(token, finish, catchAllNode);
//catchallblock -> catchallnode (catchnode) -> exception -> throw
return (Block)catchAllBlock.accept(this); //not accepted. has to be accepted by lower
}
private IdentNode compilerConstant(final CompilerConstants cc) {
final FunctionNode functionNode = lc.getCurrentFunction();
return new IdentNode(functionNode.getToken(), functionNode.getFinish(), cc.symbolName());
}
private static boolean isTerminalFinally(final Block finallyBlock) {
return finallyBlock.getLastStatement().hasTerminalFlags();
}
/**
* Splice finally code into all endpoints of a trynode
* @param tryNode the try node
* @param rethrow the rethrowing throw nodes from the synthetic catch block
* @param finallyBody the code in the original finally block
* @return new try node after splicing finally code (same if nop)
*/
private TryNode spliceFinally(final TryNode tryNode, final ThrowNode rethrow, final Block finallyBody) {
assert tryNode.getFinallyBody() == null;
final Block finallyBlock = createFinallyBlock(finallyBody);
final ArrayList<Block> inlinedFinallies = new ArrayList<>();
final FunctionNode fn = lc.getCurrentFunction();
final TryNode newTryNode = (TryNode)tryNode.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
@Override
public boolean enterFunctionNode(final FunctionNode functionNode) {
// do not enter function nodes - finally code should not be inlined into them
return false;
}
@Override
public Node leaveThrowNode(final ThrowNode throwNode) {
if (rethrow == throwNode) {
return new BlockStatement(prependFinally(finallyBlock, throwNode));
}
return throwNode;
}
@Override
public Node leaveBreakNode(final BreakNode breakNode) {
return leaveJumpStatement(breakNode);
}
@Override
public Node leaveContinueNode(final ContinueNode continueNode) {
return leaveJumpStatement(continueNode);
}
private Node leaveJumpStatement(final JumpStatement jump) {
// NOTE: leaveJumpToInlinedFinally deliberately does not delegate to this method, only break and
// continue are edited. JTIF nodes should not be changed, rather the surroundings of
// break/continue/return that were moved into the inlined finally block itself will be changed.
// If this visitor's lc doesn't find the target of the jump, it means it's external to the try block.
if (jump.getTarget(lc) == null) {
return createJumpToInlinedFinally(fn, inlinedFinallies, prependFinally(finallyBlock, jump));
}
return jump;
}
@Override
public Node leaveReturnNode(final ReturnNode returnNode) {
final Expression expr = returnNode.getExpression();
if (isTerminalFinally(finallyBlock)) {
if (expr == null) {
// Terminal finally; no return expression.
return createJumpToInlinedFinally(fn, inlinedFinallies, ensureUniqueNamesIn(finallyBlock));
}
// Terminal finally; has a return expression.
final List<Statement> newStatements = new ArrayList<>(2);
final int retLineNumber = returnNode.getLineNumber();
final long retToken = returnNode.getToken();
// Expression is evaluated for side effects.
newStatements.add(new ExpressionStatement(retLineNumber, retToken, returnNode.getFinish(), expr));
newStatements.add(createJumpToInlinedFinally(fn, inlinedFinallies, ensureUniqueNamesIn(finallyBlock)));
return new BlockStatement(retLineNumber, new Block(retToken, finallyBlock.getFinish(), newStatements));
} else if (expr == null || expr instanceof PrimitiveLiteralNode<?> || (expr instanceof IdentNode && RETURN.symbolName().equals(((IdentNode)expr).getName()))) {
// Nonterminal finally; no return expression, or returns a primitive literal, or returns :return.
// Just move the return expression into the finally block.
return createJumpToInlinedFinally(fn, inlinedFinallies, prependFinally(finallyBlock, returnNode));
} else {
// We need to evaluate the result of the return in case it is complex while still in the try block,
// store it in :return, and return it afterwards.
final List<Statement> newStatements = new ArrayList<>();
final int retLineNumber = returnNode.getLineNumber();
final long retToken = returnNode.getToken();
final int retFinish = returnNode.getFinish();
final Expression resultNode = new IdentNode(expr.getToken(), expr.getFinish(), RETURN.symbolName());
// ":return = <expr>;"
newStatements.add(new ExpressionStatement(retLineNumber, retToken, retFinish, new BinaryNode(Token.recast(returnNode.getToken(), TokenType.ASSIGN), resultNode, expr)));
// inline finally and end it with "return :return;"
newStatements.add(createJumpToInlinedFinally(fn, inlinedFinallies, prependFinally(finallyBlock, returnNode.setExpression(resultNode))));
return new BlockStatement(retLineNumber, new Block(retToken, retFinish, newStatements));
}
}
});
addStatement(inlinedFinallies.isEmpty() ? newTryNode : newTryNode.setInlinedFinallies(lc, inlinedFinallies));
// TODO: if finallyStatement is terminal, we could just have sites of inlined finallies jump here.
addStatement(new BlockStatement(finallyBlock));
return newTryNode;
}
private static JumpToInlinedFinally createJumpToInlinedFinally(final FunctionNode fn, final List<Block> inlinedFinallies, final Block finallyBlock) {
final String labelName = fn.uniqueName(":finally");
final long token = finallyBlock.getToken();
final int finish = finallyBlock.getFinish();
inlinedFinallies.add(new Block(token, finish, new LabelNode(finallyBlock.getFirstStatementLineNumber(),
token, finish, labelName, finallyBlock)));
return new JumpToInlinedFinally(labelName);
}
private static Block prependFinally(final Block finallyBlock, final Statement statement) {
final Block inlinedFinally = ensureUniqueNamesIn(finallyBlock);
if (isTerminalFinally(finallyBlock)) {
return inlinedFinally;
}
final List<Statement> stmts = inlinedFinally.getStatements();
final List<Statement> newStmts = new ArrayList<>(stmts.size() + 1);
newStmts.addAll(stmts);
newStmts.add(statement);
return new Block(inlinedFinally.getToken(), statement.getFinish(), newStmts);
}
@Override
public Node leaveTryNode(final TryNode tryNode) {
final Block finallyBody = tryNode.getFinallyBody();
TryNode newTryNode = tryNode.setFinallyBody(lc, null);
// No finally or empty finally
if (finallyBody == null || finallyBody.getStatementCount() == 0) {
final List<CatchNode> catches = newTryNode.getCatches();
if (catches == null || catches.isEmpty()) {
// A completely degenerate try block: empty finally, no catches. Replace it with try body.
return addStatement(new BlockStatement(tryNode.getBody()));
}
return addStatement(ensureUnconditionalCatch(newTryNode));
}
/*
* create a new trynode
* if we have catches:
*
* try try
* x try
* catch x
* y catch
* finally z y
* catchall
* rethrow
*
* otheriwse
*
* try try
* x x
* finally catchall
* y rethrow
*
*
* now splice in finally code wherever needed
*
*/
final Block catchAll = catchAllBlock(tryNode);
final List<ThrowNode> rethrows = new ArrayList<>(1);
catchAll.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
@Override
public boolean enterThrowNode(final ThrowNode throwNode) {
rethrows.add(throwNode);
return true;
}
});
assert rethrows.size() == 1;
if (!tryNode.getCatchBlocks().isEmpty()) {
final Block outerBody = new Block(newTryNode.getToken(), newTryNode.getFinish(), ensureUnconditionalCatch(newTryNode));
newTryNode = newTryNode.setBody(lc, outerBody).setCatchBlocks(lc, null);
}
newTryNode = newTryNode.setCatchBlocks(lc, Arrays.asList(catchAll));
/*
* Now that the transform is done, we have to go into the try and splice
* the finally block in front of any statement that is outside the try
*/
return (TryNode)lc.replace(tryNode, spliceFinally(newTryNode, rethrows.get(0), finallyBody));
}
private TryNode ensureUnconditionalCatch(final TryNode tryNode) {
final List<CatchNode> catches = tryNode.getCatches();
if(catches == null || catches.isEmpty() || catches.get(catches.size() - 1).getExceptionCondition() == null) {
return tryNode;
}
// If the last catch block is conditional, add an unconditional rethrow block
final List<Block> newCatchBlocks = new ArrayList<>(tryNode.getCatchBlocks());
newCatchBlocks.add(catchAllBlock(tryNode));
return tryNode.setCatchBlocks(lc, newCatchBlocks);
}
@Override
public Node leaveVarNode(final VarNode varNode) {
addStatement(varNode);
if (varNode.getFlag(VarNode.IS_LAST_FUNCTION_DECLARATION) && lc.getCurrentFunction().isProgram()) {
new ExpressionStatement(varNode.getLineNumber(), varNode.getToken(), varNode.getFinish(), new IdentNode(varNode.getName())).accept(this);
}
return varNode;
}
@Override
public Node leaveWhileNode(final WhileNode whileNode) {
final Expression test = whileNode.getTest();
final Block body = whileNode.getBody();
if (isAlwaysTrue(test)) {
//turn it into a for node without a test.
final ForNode forNode = (ForNode)new ForNode(whileNode.getLineNumber(), whileNode.getToken(), whileNode.getFinish(), body, 0).accept(this);
lc.replace(whileNode, forNode);
return forNode;
}
return addStatement(checkEscape(whileNode));
}
@Override
public Node leaveWithNode(final WithNode withNode) {
return addStatement(withNode);
}
/**
* Given a function node that is a callee in a CallNode, replace it with
* the appropriate marker function. This is used by {@link CodeGenerator}
* for fast scope calls
*
* @param function function called by a CallNode
* @return transformed node to marker function or identity if not ident/access/indexnode
*/
private static Expression markerFunction(final Expression function) {
if (function instanceof IdentNode) {
return ((IdentNode)function).setIsFunction();
} else if (function instanceof BaseNode) {
return ((BaseNode)function).setIsFunction();
}
return function;
}
/**
* Calculate a synthetic eval location for a node for the stacktrace, for example src#17<eval>
* @param node a node
* @return eval location
*/
private String evalLocation(final IdentNode node) {
final Source source = lc.getCurrentFunction().getSource();
final int pos = node.position();
return new StringBuilder().
append(source.getName()).
append('#').
append(source.getLine(pos)).
append(':').
append(source.getColumn(pos)).
append("<eval>").
toString();
}
/**
* Check whether a call node may be a call to eval. In that case we
* clone the args in order to create the following construct in
* {@link CodeGenerator}
*
* <pre>
* if (calledFuntion == buildInEval) {
* eval(cloned arg);
* } else {
* cloned arg;
* }
* </pre>
*
* @param callNode call node to check if it's an eval
*/
private CallNode checkEval(final CallNode callNode) {
if (callNode.getFunction() instanceof IdentNode) {
final List<Expression> args = callNode.getArgs();
final IdentNode callee = (IdentNode)callNode.getFunction();
// 'eval' call with at least one argument
if (args.size() >= 1 && EVAL.symbolName().equals(callee.getName())) {
final List<Expression> evalArgs = new ArrayList<>(args.size());
for(final Expression arg: args) {
evalArgs.add((Expression)ensureUniqueNamesIn(arg).accept(this));
}
return callNode.setEvalArgs(new CallNode.EvalArgs(evalArgs, evalLocation(callee)));
}
}
return callNode;
}
/**
* Helper that given a loop body makes sure that it is not terminal if it
* has a continue that leads to the loop header or to outer loops' loop
* headers. This means that, even if the body ends with a terminal
* statement, we cannot tag it as terminal
*
* @param loopBody the loop body to check
* @return true if control flow may escape the loop
*/
private static boolean controlFlowEscapes(final LexicalContext lex, final Block loopBody) {
final List<Node> escapes = new ArrayList<>();
loopBody.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
@Override
public Node leaveBreakNode(final BreakNode node) {
escapes.add(node);
return node;
}
@Override
public Node leaveContinueNode(final ContinueNode node) {
// all inner loops have been popped.
if (lex.contains(node.getTarget(lex))) {
escapes.add(node);
}
return node;
}
});
return !escapes.isEmpty();
}
@SuppressWarnings("unchecked")
private <T extends LoopNode> T checkEscape(final T loopNode) {
final boolean escapes = controlFlowEscapes(lc, loopNode.getBody());
if (escapes) {
return (T)loopNode.
setBody(lc, loopNode.getBody().setIsTerminal(lc, false)).
setControlFlowEscapes(lc, escapes);
}
return loopNode;
}
private Node addStatement(final Statement statement) {
lc.appendStatement(statement);
return statement;
}
private void addStatementEnclosedInBlock(final Statement stmt) {
BlockStatement b = BlockStatement.createReplacement(stmt, Collections.<Statement>singletonList(stmt));
if(stmt.isTerminal()) {
b = b.setBlock(b.getBlock().setIsTerminal(null, true));
}
addStatement(b);
}
/**
* An internal expression has a symbol that is tagged internal. Check if
* this is such a node
*
* @param expression expression to check for internal symbol
* @return true if internal, false otherwise
*/
private static boolean isInternalExpression(final Expression expression) {
if (!(expression instanceof IdentNode)) {
return false;
}
final Symbol symbol = ((IdentNode)expression).getSymbol();
return symbol != null && symbol.isInternal();
}
/**
* Is this an assignment to the special variable that hosts scripting eval
* results, i.e. __return__?
*
* @param expression expression to check whether it is $evalresult = X
* @return true if an assignment to eval result, false otherwise
*/
private static boolean isEvalResultAssignment(final Node expression) {
final Node e = expression;
if (e instanceof BinaryNode) {
final Node lhs = ((BinaryNode)e).lhs();
if (lhs instanceof IdentNode) {
return ((IdentNode)lhs).getName().equals(RETURN.symbolName());
}
}
return false;
}
}
| gpl-2.0 |