answer
stringlengths 17
10.2M
|
|---|
package edu.wustl.catissuecore.action;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import edu.wustl.catissuecore.actionForm.LoginForm;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.exception.CatissueException;
import edu.wustl.catissuecore.processor.CatissueLoginProcessor;
import edu.wustl.catissuecore.util.global.ClinPortalIntegrationConstants;
import edu.wustl.catissuecore.util.global.CDMSIntegrationConstants;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.action.XSSSupportedAction;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.exception.ApplicationException;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.domain.LoginResult;
import edu.wustl.migrator.MigrationState;
import edu.wustl.security.exception.SMException;
import edu.wustl.security.global.Roles;
import edu.wustl.security.privilege.PrivilegeManager;
public class LoginAction extends XSSSupportedAction
{
/**
* Common Logger for Login Action.
*/
private static final Logger LOGGER = Logger.getCommonLogger(LoginAction.class);
/**
* Overrides the execute method of Action class.
*
* @param mapping
* object of ActionMapping
* @param form
* object of ActionForm
* @param request
* object of HttpServletRequest
* @param response
* object of HttpServletResponse
* @return value for ActionForward object
*/
@Override
public ActionForward executeXSS(final ActionMapping mapping, final ActionForm form,
final HttpServletRequest request, final HttpServletResponse response)
{
String forwardTo = Constants.FAILURE;
if (form == null)
{
LoginAction.LOGGER.debug("Form is Null");
forwardTo = Constants.FAILURE;
}
else
{
try
{
cleanSession(request);
LoginAction.LOGGER.info("Inside Login Action, Just before validation");
if (isRequestFromClinportal(request))
{
forwardTo = Constants.SUCCESS;
}
else
{
forwardTo = processUserLogin(form, request);
}
}
catch (final Exception ex)
{
LoginAction.LOGGER.error("Exception: " + ex.getMessage(), ex);
cleanSession(request);
handleError(request, "errors.incorrectLoginIDPassword");
forwardTo = Constants.FAILURE;
}
}
return mapping.findForward(forwardTo);
}
private String processUserLogin(final ActionForm form, final HttpServletRequest request)
throws CatissueException, NamingException, ApplicationException
{
String forwardTo;
final LoginForm loginForm = (LoginForm) form;
final String loginName = loginForm.getLoginName();
final edu.wustl.domain.LoginResult loginResult = CatissueLoginProcessor.processUserLogin(request,
loginName, loginForm.getPassword());
if (loginResult.isAuthenticationSuccess())
{
if (MigrationState.NEW_WUSTL_USER.equals(loginResult.getMigratedLoginName()))
{
forwardTo = setSignUpPageAttributes(request, loginForm);
}
else
{
forwardTo = validateUser(request, loginResult);
}
}
else
{
LoginAction.LOGGER.info("User " + loginForm.getLoginName()
+ " Invalid user. Sending back to the login Page");
handleError(request, "errors.incorrectLoginIDPassword");
forwardTo = Constants.FAILURE;
}
return forwardTo;
}
private boolean isRequestFromClinportal(final HttpServletRequest request)
{
return request.getParameter(CDMSIntegrationConstants.IS_COMING_FROM_CLINPORTAL) != null
&& !(CDMSIntegrationConstants.DOUBLE_QUOTE
.equals(request
.getParameter(CDMSIntegrationConstants.IS_COMING_FROM_CLINPORTAL)))
&& Boolean
.valueOf(request
.getParameter(CDMSIntegrationConstants.IS_COMING_FROM_CLINPORTAL));
}
/**
* This method will set attributes like firstname, lastname in user sign up
* page.
*
* @param request
* HttpServletRequest
* @param loginForm
* loginform object
* @param authManager
* AuthenticationManager object
* @return String
* @throws NamingException
* NamingException
*/
private String setSignUpPageAttributes(final HttpServletRequest request, final LoginForm loginForm)
throws NamingException
{
// final Map<String, String> userAttrs =
// authManager.getUserAttributes(loginForm.getLoginName());
final String firstName = "Fname";// userAttrs.get(Constants.FIRSTNAME);
final String lastName = "Lname";// userAttrs.get(Constants.LASTNAME);
request.setAttribute(edu.wustl.wustlkey.util.global.Constants.WUSTLKEY, loginForm.getLoginName());
request.setAttribute(edu.wustl.wustlkey.util.global.Constants.FIRST_NAME, firstName);
request.setAttribute(edu.wustl.wustlkey.util.global.Constants.LAST_NAME, lastName);
return edu.wustl.wustlkey.util.global.Constants.WASHU;
}
/**
* This method will clean session.
*
* @param request
* object of HttpServletRequest
*/
private void cleanSession(final HttpServletRequest request)
{
final HttpSession prevSession = request.getSession();
if (prevSession != null)
{
prevSession.invalidate();
}
}
/**
* This method checks the validity of logged in user and perform necessary
* action after validating.
*
* @param mapping
* object of ActionMapping
* @param request
* object of HttpServletRequest
* @param loginName
* login Name
* @param loginForm
* Login Form
* @param loginResult
* @return value for ActionForward object
* @throws ApplicationException
* object of ApplicationException
* @throws CatissueException
*/
private String validateUser(final HttpServletRequest request, final LoginResult loginResult)
throws ApplicationException, CatissueException
{
String forwardTo = Constants.FAILURE;
final User validUser = CatissueLoginProcessor.getUser(loginResult.getAppLoginName());
if (validUser == null)
{
LoginAction.LOGGER.debug("User " + loginResult.getAppLoginName()
+ " Invalid user. Sending back to the login Page");
handleError(request, "errors.incorrectLoginIDPassword");
forwardTo = Constants.FAILURE;
}
else
{
forwardTo = performAdminChecks(request, validUser, loginResult);
}
return forwardTo;
}
/**
* This method will create object of privilege cache for logged in user and
* create SessionDataBean object.
*
* @param mapping
* object of ActionMapping
* @param request
* object of HttpServletRequest
* @param validUser
* User object
* @param loginForm
* Login Form
* @param loginResult
* @return value for ActionForward object
* @throws ApplicationException
* Object of ApplicationException
* @throws CatissueException
*/
private String performAdminChecks(final HttpServletRequest request, final User validUser,
final LoginResult loginResult) throws CatissueException
{
String forwardTo = edu.wustl.wustlkey.util.global.Constants.PAGE_NON_WASHU;
final HttpSession session = request.getSession(true);
final String userRole = CatissueLoginProcessor.getUserRole(validUser);
final SessionDataBean sessionData = initCacheAndSessionData(request, validUser, session, userRole);
final String validRole = CatissueLoginProcessor.getForwardToPageOnLogin(userRole);
if (isUserHasRole(validRole))
{
forwardTo = handleUserWithNoRole(request, session);
}
String result = Constants.SUCCESS;
// do not check for first time login and login expiry for wustl key user
// and migrated washu users
if (isToCheckForPasswordExpiry(loginResult, validRole))
{
result = CatissueLoginProcessor.isPasswordExpired(validUser);
}
LOGGER.info("Result: " + result);
if (!result.equals(Constants.SUCCESS))
{
forwardTo = handleChangePassword(request, session, sessionData, result);
}
LOGGER.info("forwardToPage: " + forwardTo);
return forwardTo;
}
private String handleChangePassword(final HttpServletRequest request, final HttpSession session,
final SessionDataBean sessionData, final String result)
{
String forwardTo;
handleCustomMessage(request, result);
session.setAttribute(Constants.SESSION_DATA, null);
session.setAttribute(Constants.TEMP_SESSION_DATA, sessionData);
request.setAttribute(Constants.PAGE_OF, Constants.PAGE_OF_CHANGE_PASSWORD);
forwardTo = Constants.ACCESS_DENIED;
return forwardTo;
}
private boolean isToCheckForPasswordExpiry(final LoginResult loginResult, final String validRole)
{
return !MigrationState.MIGRATED.equals(loginResult.getMigrationState())
&& !MigrationState.NEW_WUSTL_USER.equals(loginResult.getMigrationState())
&& !MigrationState.TO_BE_MIGRATED.equals(loginResult.getMigrationState())
&& !(isUserHasRole(validRole));
}
private boolean isUserHasRole(final String validRole)
{
return validRole != null && validRole.contains(Constants.PAGE_OF_SCIENTIST);
}
private String handleUserWithNoRole(final HttpServletRequest request, final HttpSession session)
{
String forwardTo;
handleError(request, "errors.noRole");
session.setAttribute(Constants.SESSION_DATA, null);
forwardTo = Constants.FAILURE;
return forwardTo;
}
private SessionDataBean initCacheAndSessionData(final HttpServletRequest request, final User validUser,
final HttpSession session, final String userRole) throws CatissueException
{
initPrivilegeCache(validUser);
LoginAction.LOGGER.info(">>>>>>>>>>>>> SUCESSFUL LOGIN A <<<<<<<<< ");
final String ipAddress = request.getRemoteAddr();
final SessionDataBean sessionData = setSessionDataBean(validUser, ipAddress, userRole);
LOGGER.info("creating session data bean " + sessionData);
LoginAction.LOGGER.debug("CSM USer ID ....................... : " + validUser.getCsmUserId());
session.setAttribute(Constants.SESSION_DATA, sessionData);
session.setAttribute(Constants.USER_ROLE, validUser.getRoleId());
return sessionData;
}
private void initPrivilegeCache(final User validUser) throws CatissueException
{
try
{
PrivilegeManager.getInstance().getPrivilegeCache(validUser.getLoginName());
}
catch (final SMException exception)
{
LOGGER.debug(exception);
throw new CatissueException(exception);
}
}
private boolean isAdminUser(final String userRole)
{
boolean adminUser;
if (userRole.equalsIgnoreCase(Constants.ADMIN_USER))
{
adminUser = true;
}
else
{
adminUser = false;
}
return adminUser;
}
/**
* This method will createSessionDataBeanObject.
*
* @param validUser
* existing user
* @param ipAddress
* IP address of the system
* @param adminUser
* true/false
* @return sessionData
* @throws CatissueException
*/
private SessionDataBean setSessionDataBean(final User validUser, final String ipAddress, final String userRole)
throws CatissueException
{
final SessionDataBean sessionData = new SessionDataBean();
sessionData.setAdmin(isAdminUser(validUser.getRoleId()));
sessionData.setUserName(validUser.getLoginName());
sessionData.setIpAddress(ipAddress);
sessionData.setUserId(validUser.getId());
sessionData.setFirstName(validUser.getFirstName());
sessionData.setLastName(validUser.getLastName());
sessionData.setCsmUserId(validUser.getCsmUserId().toString());
setSecurityParamsInSessionData(sessionData, userRole);
return sessionData;
}
/**
* To set the Security Parameters in the given SessionDataBean object
* depending upon the role of the user.
*
* @param validUser
* reference to the User.
* @param sessionData
* The reference to the SessionDataBean object.
* @param userRole2
* @throws SMException
* : SMException
*/
private void setSecurityParamsInSessionData(final SessionDataBean sessionData, final String userRole)
throws CatissueException
{
if (userRole != null
&& (userRole.equalsIgnoreCase(Roles.ADMINISTRATOR) || userRole.equals(Roles.SUPERVISOR)))
{
sessionData.setSecurityRequired(false);
}
else
{
sessionData.setSecurityRequired(true);
}
}
/**
*
* @param request
* : request
* @param errorKey
* : errorKey
*/
private void handleError(final HttpServletRequest request, final String errorKey)
{
final ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(errorKey));
// Report any errors we have discovered
if (!errors.isEmpty())
{
saveErrors(request, errors);
}
}
/**
* This method is for showing Custom message.
*
* @param request
* HttpServletRequest
* @param errorMsg
* Error message
*/
private void handleCustomMessage(final HttpServletRequest request, final String errorMsg)
{
final ActionMessages msg = new ActionMessages();
final ActionMessage msgs = new ActionMessage(errorMsg);
msg.add(ActionErrors.GLOBAL_ERROR, msgs);
if (!msg.isEmpty())
{
saveMessages(request, msg);
}
}
}
|
package edu.wustl.catissuecore.domain;
import edu.wustl.catissuecore.domain.StorageContainerCapacity;
/**
* Type of the storage container e.g. Freezer, Box etc.
* @hibernate.class table="CATISSUE_STORAGE_TYPE"
*/
public class StorageType implements java.io.Serializable
{
private static final long serialVersionUID = 1234567890L;
/**
* System generated unique identifier.
*/
protected Long systemIdentifier;
/**
* Text name assigned to the container type
*/
protected String type;
/**
* Default temperature of current type of storage container.
*/
protected Double defaultTempratureInCentigrade;
/**
* Default capacity of a storage container.
*/
private StorageContainerCapacity defaultStorageCapacity;
/**
* Returns System generated unique identifier.
* @return Integer System generated unique identifier.
* @see #setSystemIdentifier(Integer)
* @hibernate.id name="systemIdentifier" column="IDENTIFIER" type="long" length="30"
* unsaved-value="null" generator-class="native"
* */
public Long getSystemIdentifier()
{
return systemIdentifier;
}
/**
* Sets system generated unique identifier.
* @param systemIdentifier identifier of the Storagetype to be set.
* @see #getSystemIdentifier()
* */
public void setSystemIdentifier(Long systemIdentifier)
{
this.systemIdentifier = systemIdentifier;
}
/**
* Returns the type of storage container.
* @hibernate.property name="type" type="string"
* column="TYPE" length="50" not-null="true" unique="true"
* @return The type of storage container.
* @see #setType(String)
*/
public String getType()
{
return type;
}
/**
* Sets the type of storage container.
* @param type The type of storage container to be set.
* @see #getType()
*/
public void setType(String type)
{
this.type = type;
}
/**
* Returns the default temperature of a storage container in centigrade.
* @hibernate.property name="defaultTempratureInCentigrade" type="double"
* column="DEFAULT_TEMPERATURE_IN_CENTIGRADE" length="30"
* @return The default temperature of a storage container in centigrade.
* @see #setDefaultTempratureInCentigrade(Double)
*/
public Double getDefaultTempratureInCentigrade()
{
return defaultTempratureInCentigrade;
}
/**
* Sets the default temperature of a storage container in centigrade.
* @param defaultTempratureInCentigrade temperature of a storage container in centigrade to be set.
* @see #getDefaultTempratureInCentigrade()
*/
public void setDefaultTempratureInCentigrade(Double defaultTempratureInCentigrade)
{
this.defaultTempratureInCentigrade = defaultTempratureInCentigrade;
}
/**
* Returns the default capacity of a storage container.
* @return The default capacity of a storage container.
* @hibernate.many-to-one column="STORAGE_CONTAINER_CAPACITY_ID"
* class="edu.wustl.catissuecore.domain.StorageContainerCapacity" constrained="true"
* @see #setDefaultStorageCapacity(StorageContainerCapacity)
*/
public StorageContainerCapacity getDefaultStorageCapacity()
{
return defaultStorageCapacity;
}
/**
* Sets the default storage capacity.
* @param defaultStorageCapacity capacity of a storage container to be set.
* @see #getDefaultStorageCapacity
* ()
*/
public void setDefaultStorageCapacity(StorageContainerCapacity defaultStorageCapacity)
{
this.defaultStorageCapacity = defaultStorageCapacity;
}
}
|
package edu.wustl.query.bizlogic;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.DefaultBizLogic;
import edu.wustl.common.dao.DAO;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.query.domain.Workflow;
/**
* @author vijay_pande
* BizLogic class to insert/update WorkFlow Object
*/
public class WorkflowBizLogic extends DefaultBizLogic
{
private static org.apache.log4j.Logger logger =Logger.getLogger(WorkflowBizLogic.class);
protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException
{
Workflow workflow = (Workflow) obj;
logger.info("In WORKFLOW BIZ LOGIC >>>>>> INSERT METHOD");
logger.info("
try
{
dao.insert(workflow, sessionDataBean, false, false);
}
catch (UserNotAuthorizedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
}
}
|
package tr.xip.wanikani.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import tr.xip.wanikani.models.BaseItem;
import tr.xip.wanikani.models.CriticalItem;
import tr.xip.wanikani.models.LevelProgression;
import tr.xip.wanikani.models.SRSDistribution;
import tr.xip.wanikani.models.StudyQueue;
import tr.xip.wanikani.models.UnlockItem;
import tr.xip.wanikani.models.User;
import tr.xip.wanikani.database.table.CriticalItemsTable;
import tr.xip.wanikani.database.table.ItemsTable;
import tr.xip.wanikani.database.table.LevelProgressionTable;
import tr.xip.wanikani.database.table.RecentUnlocksTable;
import tr.xip.wanikani.database.table.SRSDistributionTable;
import tr.xip.wanikani.database.table.StudyQueueTable;
import tr.xip.wanikani.database.table.UsersTable;
public class DatabaseManager {
private static final String TAG = "Database Manager";
private Context context;
private SQLiteDatabase db;
public DatabaseManager(Context context) {
this.context = context;
db = new DatabaseHelper(context).getWritableDatabase();
}
private void addItem(BaseItem item) {
ContentValues values = new ContentValues();
values.put(ItemsTable.COLUMN_NAME_CHARACTER, item.getCharacter());
values.put(ItemsTable.COLUMN_NAME_KANA, item.getKana());
values.put(ItemsTable.COLUMN_NAME_MEANING, item.getMeaning());
values.put(ItemsTable.COLUMN_NAME_IMAGE, item.getImage());
values.put(ItemsTable.COLUMN_NAME_ONYOMI, item.getOnyomi());
values.put(ItemsTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());
values.put(ItemsTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());
values.put(ItemsTable.COLUMN_NAME_LEVEL, item.getLevel());
values.put(ItemsTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());
values.put(ItemsTable.COLUMN_NAME_SRS, item.getSrsLevel());
values.put(ItemsTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());
values.put(ItemsTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());
values.put(ItemsTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);
values.put(ItemsTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());
values.put(ItemsTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());
values.put(ItemsTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());
values.put(ItemsTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());
values.put(ItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());
values.put(ItemsTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());
values.put(ItemsTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());
values.put(ItemsTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());
values.put(ItemsTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());
values.put(ItemsTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());
values.put(ItemsTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());
values.put(ItemsTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());
db.insert(ItemsTable.TABLE_NAME, ItemsTable.COLUMN_NAME_NULLABLE, values);
}
public void saveItems(List<BaseItem> list, BaseItem.ItemType type) {
deleteAllItemsFromSameLevelAndType(list, type);
for (BaseItem item : list)
addItem(item);
}
public List<BaseItem> getItems(BaseItem.ItemType itemType, int[] levels) {
List<BaseItem> list = new ArrayList<>();
for (int level : levels) {
String whereClause = ItemsTable.COLUMN_NAME_ITEM_TYPE + " = ?" + " AND "
+ ItemsTable.COLUMN_NAME_LEVEL + " = ?";
String[] whereArgs = {
itemType.toString(),
String.valueOf(level)
};
Cursor c = db.query(
ItemsTable.TABLE_NAME,
ItemsTable.COLUMNS,
whereClause,
whereArgs,
null,
null,
null
);
if (c != null && c.moveToFirst()) {
do {
BaseItem item = new BaseItem(
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ID)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_CHARACTER)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_KANA)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_IMAGE)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ONYOMI)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_KUNYOMI)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_IMPORTANT_READING)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_LEVEL)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_ITEM_TYPE)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_SRS)),
c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_UNLOCKED_DATE)),
c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_AVAILABLE_DATE)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_BURNED)) == 1,
c.getLong(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_BURNED_DATE)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_CORRECT)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_INCORRECT)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_MAX_STREAK)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_CORRECT)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_INCORRECT)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_MAX_STREAK)),
c.getInt(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_CURRENT_STREAK)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_MEANING_NOTE)),
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_USER_SYNONYMS)) != null
? c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_USER_SYNONYMS)).split(",")
: null,
c.getString(c.getColumnIndexOrThrow(ItemsTable.COLUMN_NAME_READING_NOTE))
);
list.add(item);
} while (c.moveToNext());
}
}
return list.size() != 0 ? list : null;
}
private void deleteAllItemsFromSameLevelAndType(List<BaseItem> list, BaseItem.ItemType type) {
HashSet<Integer> levels = new HashSet();
for (BaseItem item : list)
levels.add(item.getLevel());
for (Integer level : levels) {
String whereClause = ItemsTable.COLUMN_NAME_LEVEL + " = ?" + " AND "
+ ItemsTable.COLUMN_NAME_ITEM_TYPE + " = ?";
String[] whereArgs = {
String.valueOf(level),
type.toString()
};
db.delete(ItemsTable.TABLE_NAME, whereClause, whereArgs);
}
}
private void addRecentUnlock(UnlockItem item) {
ContentValues values = new ContentValues();
values.put(RecentUnlocksTable.COLUMN_NAME_CHARACTER, item.getCharacter());
values.put(RecentUnlocksTable.COLUMN_NAME_KANA, item.getKana());
values.put(RecentUnlocksTable.COLUMN_NAME_MEANING, item.getMeaning());
values.put(RecentUnlocksTable.COLUMN_NAME_IMAGE, item.getImage());
values.put(RecentUnlocksTable.COLUMN_NAME_ONYOMI, item.getOnyomi());
values.put(RecentUnlocksTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());
values.put(RecentUnlocksTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());
values.put(RecentUnlocksTable.COLUMN_NAME_LEVEL, item.getLevel());
values.put(RecentUnlocksTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());
values.put(RecentUnlocksTable.COLUMN_NAME_SRS, item.getSrsLevel());
values.put(RecentUnlocksTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());
values.put(RecentUnlocksTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());
values.put(RecentUnlocksTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);
values.put(RecentUnlocksTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());
values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());
values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());
values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());
values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());
values.put(RecentUnlocksTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());
values.put(RecentUnlocksTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());
values.put(RecentUnlocksTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());
values.put(RecentUnlocksTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());
values.put(RecentUnlocksTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());
values.put(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());
values.put(RecentUnlocksTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());
db.insert(RecentUnlocksTable.TABLE_NAME, RecentUnlocksTable.COLUMN_NAME_NULLABLE, values);
}
public void saveRecentUnlocks(List<UnlockItem> list) {
deleteSameRecentUnlocks(list);
for (UnlockItem item : list)
addRecentUnlock(item);
}
public List<UnlockItem> getRecentUnlocks(int limit) {
List<UnlockItem> list = new ArrayList<>();
Cursor c = db.query(
RecentUnlocksTable.TABLE_NAME,
RecentUnlocksTable.COLUMNS,
null,
null,
null,
null,
null,
String.valueOf(limit)
);
if (c != null && c.moveToFirst()) {
do {
UnlockItem item = new UnlockItem(
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ID)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_CHARACTER)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_KANA)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_IMAGE)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ONYOMI)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_KUNYOMI)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_IMPORTANT_READING)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_LEVEL)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_ITEM_TYPE)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_SRS)),
c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_UNLOCKED_DATE)),
c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_AVAILABLE_DATE)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_BURNED)) == 1,
c.getLong(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_BURNED_DATE)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_CORRECT)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_INCORRECT)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_MAX_STREAK)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_CORRECT)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_INCORRECT)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_MAX_STREAK)),
c.getInt(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_CURRENT_STREAK)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_MEANING_NOTE)),
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS)) != null
? c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_USER_SYNONYMS)).split(",")
: null,
c.getString(c.getColumnIndexOrThrow(RecentUnlocksTable.COLUMN_NAME_READING_NOTE))
);
list.add(item);
} while (c.moveToNext());
}
return list.size() != 0 ? list : null;
}
public void deleteSameRecentUnlocks(List<UnlockItem> list) {
for (UnlockItem item : list) {
String whereClause = item.getImage() == null
? RecentUnlocksTable.COLUMN_NAME_CHARACTER + " = ?"
: RecentUnlocksTable.COLUMN_NAME_IMAGE + " = ?";
String[] whereArgs = {
item.getImage() == null ? String.valueOf(item.getCharacter()) : item.getImage()
};
db.delete(RecentUnlocksTable.TABLE_NAME, whereClause, whereArgs);
}
}
private void addCriticalItem(CriticalItem item) {
ContentValues values = new ContentValues();
values.put(CriticalItemsTable.COLUMN_NAME_CHARACTER, item.getCharacter());
values.put(CriticalItemsTable.COLUMN_NAME_KANA, item.getKana());
values.put(CriticalItemsTable.COLUMN_NAME_MEANING, item.getMeaning());
values.put(CriticalItemsTable.COLUMN_NAME_IMAGE, item.getImage());
values.put(CriticalItemsTable.COLUMN_NAME_ONYOMI, item.getOnyomi());
values.put(CriticalItemsTable.COLUMN_NAME_KUNYOMI, item.getKunyomi());
values.put(CriticalItemsTable.COLUMN_NAME_IMPORTANT_READING, item.getImportantReading());
values.put(CriticalItemsTable.COLUMN_NAME_LEVEL, item.getLevel());
values.put(CriticalItemsTable.COLUMN_NAME_ITEM_TYPE, item.getType().toString());
values.put(CriticalItemsTable.COLUMN_NAME_SRS, item.getSrsLevel());
values.put(CriticalItemsTable.COLUMN_NAME_UNLOCKED_DATE, item.getUnlockDateInSeconds());
values.put(CriticalItemsTable.COLUMN_NAME_AVAILABLE_DATE, item.getAvailableDateInSeconds());
values.put(CriticalItemsTable.COLUMN_NAME_BURNED, item.isBurned() ? 1 : 0);
values.put(CriticalItemsTable.COLUMN_NAME_BURNED_DATE, item.getBurnedDateInSeconds());
values.put(CriticalItemsTable.COLUMN_NAME_MEANING_CORRECT, item.getMeaningCorrect());
values.put(CriticalItemsTable.COLUMN_NAME_MEANING_INCORRECT, item.getMeaningIncorrect());
values.put(CriticalItemsTable.COLUMN_NAME_MEANING_MAX_STREAK, item.getMeaningMaxStreak());
values.put(CriticalItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK, item.getMeaningCurrentStreak());
values.put(CriticalItemsTable.COLUMN_NAME_READING_CORRECT, item.getReadingCorrect());
values.put(CriticalItemsTable.COLUMN_NAME_READING_INCORRECT, item.getReadingIncorrect());
values.put(CriticalItemsTable.COLUMN_NAME_READING_MAX_STREAK, item.getReadingMaxStreak());
values.put(CriticalItemsTable.COLUMN_NAME_READING_CURRENT_STREAK, item.getReadingCurrentStreak());
values.put(CriticalItemsTable.COLUMN_NAME_MEANING_NOTE, item.getMeaningNote());
values.put(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS, item.getUserSynonymsAsString());
values.put(CriticalItemsTable.COLUMN_NAME_READING_NOTE, item.getReadingNote());
values.put(CriticalItemsTable.COLUMN_NAME_PERCENTAGE, item.getPercentage());
db.insert(CriticalItemsTable.TABLE_NAME, CriticalItemsTable.COLUMN_NAME_NULLABLE, values);
}
public void saveCriticalItems(List<CriticalItem> list) {
deleteSameCriticalItems(list);
for (CriticalItem item : list)
addCriticalItem(item);
}
public List<CriticalItem> getCriticalItems(int percentage) {
List<CriticalItem> list = new ArrayList<>();
String whereClause = CriticalItemsTable.COLUMN_NAME_PERCENTAGE + " < ?";
String[] whereArgs = {
String.valueOf(percentage)
};
Cursor c = db.query(
CriticalItemsTable.TABLE_NAME,
CriticalItemsTable.COLUMNS,
whereClause,
whereArgs,
null,
null,
null
);
if (c != null && c.moveToFirst()) {
do {
CriticalItem item = new CriticalItem(
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ID)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_CHARACTER)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_KANA)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_IMAGE)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ONYOMI)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_KUNYOMI)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_IMPORTANT_READING)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_LEVEL)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_ITEM_TYPE)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_SRS)),
c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_UNLOCKED_DATE)),
c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_AVAILABLE_DATE)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_BURNED)) == 1,
c.getLong(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_BURNED_DATE)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_CORRECT)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_INCORRECT)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_MAX_STREAK)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_CURRENT_STREAK)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_CORRECT)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_INCORRECT)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_MAX_STREAK)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_CURRENT_STREAK)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_MEANING_NOTE)),
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS)) != null
? c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_USER_SYNONYMS)).split(",")
: null,
c.getString(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_READING_NOTE)),
c.getInt(c.getColumnIndexOrThrow(CriticalItemsTable.COLUMN_NAME_PERCENTAGE))
);
list.add(item);
} while (c.moveToNext());
}
return list;
}
private void deleteSameCriticalItems(List<CriticalItem> list) {
for (CriticalItem item : list) {
String whereClause = item.getImage() == null
? CriticalItemsTable.COLUMN_NAME_CHARACTER + " = ?"
: CriticalItemsTable.COLUMN_NAME_IMAGE + " = ?";
String[] whereArgs = {
item.getImage() == null ? String.valueOf(item.getCharacter()) : item.getImage()
};
db.delete(CriticalItemsTable.TABLE_NAME, whereClause, whereArgs);
}
}
public void saveStudyQueue(StudyQueue queue) {
deleteStudyQueue();
ContentValues values = new ContentValues();
values.put(StudyQueueTable.COLUMN_NAME_LESSONS_AVAILABLE, queue.getAvailableLesonsCount());
values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE, queue.getAvailableReviewsCount());
values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_HOUR, queue.getAvailableReviewsNextHourCount());
values.put(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_DAY, queue.getAvailableReviewsNextDayCount());
values.put(StudyQueueTable.COLUMN_NAME_NEXT_REVIEW_DATE, queue.getNextReviewDateInSeconds());
db.insert(StudyQueueTable.TABLE_NAME, StudyQueueTable.COLUMN_NAME_NULLABLE, values);
}
public StudyQueue getStudyQueue() {
Cursor c = db.query(
StudyQueueTable.TABLE_NAME,
StudyQueueTable.COLUMNS,
null,
null,
null,
null,
null
);
if (c != null && c.moveToFirst()) {
User user = getUser();
return new StudyQueue(
c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_ID)),
c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_LESSONS_AVAILABLE)),
c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE)),
c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_HOUR)),
c.getInt(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_REVIEWS_AVAILABLE_NEXT_DAY)),
c.getLong(c.getColumnIndexOrThrow(StudyQueueTable.COLUMN_NAME_NEXT_REVIEW_DATE)),
user != null ? user.getUserInformation() : null
);
} else {
Log.e(TAG, "No study queue found; returning null");
return null;
}
}
public void deleteStudyQueue() {
db.delete(StudyQueueTable.TABLE_NAME, null, null);
}
public void saveLevelProgression(LevelProgression progression) {
deleteLevelProgression();
ContentValues values = new ContentValues();
values.put(LevelProgressionTable.COLUMN_NAME_RADICALS_PROGRESS, progression.getRadicalsProgress());
values.put(LevelProgressionTable.COLUMN_NAME_RADICALS_TOTAL, progression.getRadicalsTotal());
values.put(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_PROGRESS, progression.getKanjiProgress());
values.put(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_TOTAL, progression.getKanjiTotal());
db.insert(LevelProgressionTable.TABLE_NAME, LevelProgressionTable.COLUMN_NAME_NULLABLE, values);
}
public LevelProgression getLevelProgression() {
Cursor c = db.query(
LevelProgressionTable.TABLE_NAME,
LevelProgressionTable.COLUMNS,
null,
null,
null,
null,
null
);
if (c != null && c.moveToFirst()) {
return new LevelProgression(
c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_ID)),
getUser().getUserInformation(),
c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_RADICALS_PROGRESS)),
c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_RADICALS_TOTAL)),
c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_PROGRESS)),
c.getInt(c.getColumnIndexOrThrow(LevelProgressionTable.COLUMN_NAME_REVIEWS_KANJI_TOTAL))
);
} else {
Log.e(TAG, "No study queue found; returning null");
return null;
}
}
public void deleteLevelProgression() {
db.delete(SRSDistributionTable.TABLE_NAME, null, null);
}
public void saveSrsDistribution(SRSDistribution distribution) {
deleteSrsDistribution();
ContentValues values = new ContentValues();
values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_RADICALS, distribution.getAprentice().getRadicalsCount());
values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_KANJI, distribution.getAprentice().getKanjiCount());
values.put(SRSDistributionTable.COLUMN_NAME_APPRENTICE_VOCABULARY, distribution.getAprentice().getVocabularyCount());
values.put(SRSDistributionTable.COLUMN_NAME_GURU_RADICALS, distribution.getGuru().getRadicalsCount());
values.put(SRSDistributionTable.COLUMN_NAME_GURU_KANJI, distribution.getGuru().getKanjiCount());
values.put(SRSDistributionTable.COLUMN_NAME_GURU_VOCABULARY, distribution.getGuru().getVocabularyCount());
values.put(SRSDistributionTable.COLUMN_NAME_MASTER_RADICALS, distribution.getMaster().getRadicalsCount());
values.put(SRSDistributionTable.COLUMN_NAME_MASTER_KANJI, distribution.getMaster().getKanjiCount());
values.put(SRSDistributionTable.COLUMN_NAME_MASTER_VOCABULARY, distribution.getMaster().getVocabularyCount());
values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_RADICALS, distribution.getEnlighten().getRadicalsCount());
values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_KANJI, distribution.getEnlighten().getKanjiCount());
values.put(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_VOCABULARY, distribution.getEnlighten().getVocabularyCount());
values.put(SRSDistributionTable.COLUMN_NAME_BURNED_RADICALS, distribution.getBurned().getRadicalsCount());
values.put(SRSDistributionTable.COLUMN_NAME_BURNED_KANJI, distribution.getBurned().getKanjiCount());
values.put(SRSDistributionTable.COLUMN_NAME_BURNED_VOCABULARY, distribution.getBurned().getVocabularyCount());
db.insert(SRSDistributionTable.TABLE_NAME, SRSDistributionTable.COLUMN_NAME_NULLABLE, values);
}
public SRSDistribution getSrsDistribution() {
Cursor c = db.query(
SRSDistributionTable.TABLE_NAME,
SRSDistributionTable.COLUMNS,
null,
null,
null,
null,
null
);
if (c != null && c.moveToFirst()) {
return new SRSDistribution(
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ID)),
getUser().getUserInformation(),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_RADICALS)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_KANJI)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_APPRENTICE_VOCABULARY)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_RADICALS)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_KANJI)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_GURU_VOCABULARY)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_RADICALS)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_KANJI)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_MASTER_VOCABULARY)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_RADICALS)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_KANJI)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_VOCABULARY)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_RADICALS)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_KANJI)),
c.getInt(c.getColumnIndexOrThrow(SRSDistributionTable.COLUMN_NAME_BURNED_VOCABULARY))
);
} else {
Log.e(TAG, "No srs distribution found; returning null");
return null;
}
}
public void deleteSrsDistribution() {
db.delete(SRSDistributionTable.TABLE_NAME, null, null);
}
private void addUser(User user) {
ContentValues values = new ContentValues();
values.put(UsersTable.COLUMN_NAME_USERNAME, user.getUsername());
values.put(UsersTable.COLUMN_NAME_GRAVATAR, user.getGravatar());
values.put(UsersTable.COLUMN_NAME_LEVEL, user.getLevel());
values.put(UsersTable.COLUMN_NAME_TITLE, user.getTitle());
values.put(UsersTable.COLUMN_NAME_ABOUT, user.getAbout());
values.put(UsersTable.COLUMN_NAME_WEBSITE, user.getWebsite());
values.put(UsersTable.COLUMN_NAME_TWITTER, user.getTwitter());
values.put(UsersTable.COLUMN_NAME_TOPICS_COUNT, user.getTopicsCount());
values.put(UsersTable.COLUMN_NAME_POSTS_COUNT, user.getPostsCount());
values.put(UsersTable.COLUMN_NAME_CREATION_DATE, user.getCreationDateInSeconds());
values.put(UsersTable.COLUMN_NAME_VACATION_DATE, user.getVacationDateInSeconds());
db.insert(UsersTable.TABLE_NAME, UsersTable.COLUMN_NAME_NULLABLE, values);
}
public void saveUser(User user) {
deleteUsers();
addUser(user);
}
public User getUser() {
Cursor c = db.query(
UsersTable.TABLE_NAME,
UsersTable.COLUMNS,
null,
null,
null,
null,
null
);
if (c != null && c.moveToFirst()) {
return new User(
c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_USERNAME)),
c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_GRAVATAR)),
c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_LEVEL)),
c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TITLE)),
c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_ABOUT)),
c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_WEBSITE)),
c.getString(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TWITTER)),
c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_TOPICS_COUNT)),
c.getInt(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_POSTS_COUNT)),
c.getLong(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_CREATION_DATE)),
c.getLong(c.getColumnIndexOrThrow(UsersTable.COLUMN_NAME_VACATION_DATE))
);
} else {
Log.e(TAG, "No users found; returning null");
return null;
}
}
public void deleteUsers() {
db.delete(UsersTable.TABLE_NAME, null, null);
}
}
|
package dr.app.beagle.tools;
import java.util.ArrayList;
import java.util.List;
import beagle.Beagle;
import beagle.BeagleFactory;
import dr.app.beagle.evomodel.sitemodel.BranchSubstitutionModel;
import dr.app.beagle.evomodel.sitemodel.EpochBranchSubstitutionModel;
import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel;
import dr.app.beagle.evomodel.sitemodel.HomogenousBranchSubstitutionModel;
import dr.app.beagle.evomodel.substmodel.FrequencyModel;
import dr.app.beagle.evomodel.substmodel.HKY;
import dr.app.beagle.evomodel.substmodel.SubstitutionModel;
import dr.app.beagle.evomodel.treelikelihood.BufferIndexHelper;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.SimpleAlignment;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.io.NewickImporter;
import dr.evolution.sequence.Sequence;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.DefaultBranchRateModel;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Parameter;
import dr.math.MathUtils;
public class BeagleSequenceSimulator {
private TreeModel treeModel;
private GammaSiteRateModel gammaSiteRateModel;
private BranchSubstitutionModel branchSubstitutionModel;
private int sequenceLength;
private FrequencyModel freqModel;
private int categoryCount;
private Beagle beagle;
private BufferIndexHelper eigenBufferHelper;
private BufferIndexHelper matrixBufferHelper;
private int stateCount;
private boolean has_ancestralSequence = false;
private Sequence ancestralSequence = null;
private double[][] probabilities;
// TODO: get freqModel from branchSubstModel
public BeagleSequenceSimulator(TreeModel treeModel,
GammaSiteRateModel gammaSiteRateModel,
BranchRateModel branchRateModel,
FrequencyModel freqModel,
int sequenceLength
) {
this.treeModel = treeModel;
this.gammaSiteRateModel = gammaSiteRateModel;
this.sequenceLength = sequenceLength;
this.freqModel = freqModel; // gammaSiteRateModel.getSubstitutionModel().getFrequencyModel();
this.branchSubstitutionModel = (BranchSubstitutionModel) gammaSiteRateModel.getModel(0); // branchSubstitutionModel;
int tipCount = treeModel.getExternalNodeCount();
int nodeCount = treeModel.getNodeCount();
int eigenCount = branchSubstitutionModel.getEigenCount();
int internalNodeCount = treeModel.getInternalNodeCount();
int scaleBufferCount = internalNodeCount + 1;
int compactPartialsCount = tipCount;
int patternCount = sequenceLength;
int stateCount = freqModel.getDataType().getStateCount();
this.categoryCount = gammaSiteRateModel.getCategoryCount();
this.probabilities = new double[categoryCount][stateCount * stateCount];
this.stateCount = stateCount;
// print2DArray(probabilities);
// one partials buffer for each tip and two for each internal node (for store restore)
BufferIndexHelper partialBufferHelper = new BufferIndexHelper(nodeCount, tipCount);
// two eigen buffers for each decomposition for store and restore.
eigenBufferHelper = new BufferIndexHelper(eigenCount, 0);
// two matrices for each node less the root
matrixBufferHelper = new BufferIndexHelper(nodeCount, 0);
// one scaling buffer for each internal node plus an extra for the
// accumulation, then doubled for store/restore
BufferIndexHelper scaleBufferHelper = new BufferIndexHelper(scaleBufferCount, 0);
// null implies no restrictions
int[] resourceList = null;
long preferenceFlags = 0;
long requirementFlags = 0;
beagle = BeagleFactory.loadBeagleInstance(tipCount,
partialBufferHelper.getBufferCount(),
compactPartialsCount,
stateCount,
patternCount,
eigenBufferHelper.getBufferCount(),
matrixBufferHelper.getBufferCount() + branchSubstitutionModel.getExtraBufferCount(treeModel),
categoryCount,
scaleBufferHelper.getBufferCount(),
resourceList,
preferenceFlags,
requirementFlags
);
double[] categoryRates = gammaSiteRateModel.getCategoryRates();
beagle.setCategoryRates(categoryRates);
}// END: Constructor
public void setAncestralSequence(Sequence seq) {
ancestralSequence = seq;
has_ancestralSequence = true;
}// END: setAncestralSequence
int[] sequence2intArray(Sequence seq) {
if (seq.getLength() != sequenceLength) {
throw new RuntimeException("Ancestral sequence length has " + seq.getLength() + " characters " + "expecting " + sequenceLength + " characters");
}
int array[] = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
array[i] = freqModel.getDataType().getState(seq.getChar(i));
}
return array;
}// END: sequence2intArray
Sequence intArray2Sequence(int[] seq, NodeRef node) {
StringBuilder sSeq = new StringBuilder();
for (int i = 0; i < sequenceLength; i++) {
sSeq.append(freqModel.getDataType().getCode(seq[i]));
}
return new Sequence(treeModel.getNodeTaxon(node), sSeq.toString());
} // END: intArray2Sequence
public Alignment simulate() {
SimpleAlignment alignment = new SimpleAlignment();
NodeRef root = treeModel.getRoot();
double[] categoryProbs = gammaSiteRateModel.getCategoryProportions();
int[] category = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
category[i] = MathUtils.randomChoicePDF(categoryProbs);
}
// printArray(categoryProbs);
// printArray(category);
int[] seq = new int[sequenceLength];
if (has_ancestralSequence) {
seq = sequence2intArray(ancestralSequence);
} else {
for (int i = 0; i < sequenceLength; i++) {
seq[i] = MathUtils.randomChoicePDF(freqModel.getFrequencies());
}
}// END: ancestral sequence check
alignment.setDataType(freqModel.getDataType());
alignment.setReportCountStatistics(true);
traverse(root, seq, category, alignment);
return alignment;
}// END: simulate
void traverse(NodeRef node, int[] parentSequence, int[] category,
SimpleAlignment alignment) {
for (int iChild = 0; iChild < treeModel.getChildCount(node); iChild++) {
NodeRef child = treeModel.getChild(node, iChild);
int[] sequence = new int[sequenceLength];
double[] cProb = new double[stateCount];
for (int i = 0; i < categoryCount; i++) {
getTransitionProbabilities(treeModel, child, i, probabilities[i]);
}
for (int i = 0; i < sequenceLength; i++) {
System.arraycopy(probabilities[category[i]], parentSequence[i] * stateCount, cProb, 0, stateCount);
sequence[i] = MathUtils.randomChoicePDF(cProb);
}
if (treeModel.getChildCount(child) == 0) {
alignment.addSequence(intArray2Sequence(sequence, child));
}
traverse(treeModel.getChild(node, iChild), sequence, category, alignment);
}// END: child nodes loop
}// END: traverse
// TODO:
void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory,
double[] probabilities) {
int nodeNum = node.getNumber();
matrixBufferHelper.flipOffset(nodeNum);
int bufferIndex = matrixBufferHelper.getOffsetIndex(nodeNum);
int eigenIndex = branchSubstitutionModel.getBranchIndex(tree, node, bufferIndex);
double edgeLengths[] = { tree.getBranchLength(node) };
int probabilityIndices[] = { bufferIndex };
int count = 1;
eigenBufferHelper.flipOffset(eigenIndex);
branchSubstitutionModel.setEigenDecomposition(
beagle, eigenIndex, eigenBufferHelper, 0
);
// System.out.println("eigenIndex:" + eigenIndex);
// System.out.println("update indices:");
// System.out.println(probabilityIndices[0]);
// System.out.println("weights:");
// System.out.println(edgeLengths[0]);
branchSubstitutionModel.updateTransitionMatrices(beagle,
eigenIndex,
eigenBufferHelper,
probabilityIndices,
null,
null,
edgeLengths,
count
);
beagle.getTransitionMatrix(bufferIndex, probabilities);
System.out.println("bufferIndex: " + bufferIndex);
printArray(probabilities);
}// END: getTransitionProbabilities
public static void main(String[] args) {
// simulateEpochModel();
simulateHKY();
} // END: main
static void simulateHKY() {
try {
int sequenceLength = 10;
// create tree
NewickImporter importer = new NewickImporter("(SimSeq1:73.7468,(SimSeq2:25.256989999999995,SimSeq3:45.256989999999995):18.48981);");
Tree tree = importer.importTree(null);
TreeModel treeModel = new TreeModel(tree);
// create Frequency Model
Parameter freqs = new Parameter.Default(new double[] { 0.25, 0.25, 0.25, 0.25 });
FrequencyModel freqModel = new FrequencyModel(Nucleotides.INSTANCE, freqs);
// create substitution model
Parameter kappa = new Parameter.Default(1, 1);
HKY hky = new HKY(kappa, freqModel);
HomogenousBranchSubstitutionModel substitutionModel = new HomogenousBranchSubstitutionModel(hky, freqModel);
// create site model
GammaSiteRateModel siteRateModel = new GammaSiteRateModel("siteModel");
siteRateModel.addModel(substitutionModel);
// create branch rate model
BranchRateModel branchRateModel = new DefaultBranchRateModel();
// feed to sequence simulator and generate leaves
BeagleSequenceSimulator beagleSequenceSimulator = new BeagleSequenceSimulator(
treeModel,
siteRateModel,
branchRateModel,
freqModel,
sequenceLength
);
Sequence ancestralSequence = new Sequence();
ancestralSequence.appendSequenceString("AAAAAAAAAA");
beagleSequenceSimulator.setAncestralSequence(ancestralSequence);
System.out.println(beagleSequenceSimulator.simulate().toString());
} catch (Exception e) {
e.printStackTrace();
}// END: try-catch block
}// END: simulateHKY
static void simulateEpochModel() {
try {
int sequenceLength = 10;
// create tree
NewickImporter importer = new NewickImporter("(SimSeq1:73.7468,(SimSeq2:25.256989999999995,SimSeq3:45.256989999999995):18.48981);");
Tree tree = importer.importTree(null);
TreeModel treeModel = new TreeModel(tree);
// create Frequency Model
Parameter freqs = new Parameter.Default(new double[] { 0.25, 0.25, 0.25, 0.25 });
FrequencyModel freqModel = new FrequencyModel(Nucleotides.INSTANCE, freqs);
List<FrequencyModel> frequencyModelList = new ArrayList<FrequencyModel>();
frequencyModelList.add(freqModel);
// create Epoch Model
Parameter kappa1 = new Parameter.Default(1, 1);
Parameter kappa2 = new Parameter.Default(1, 10);
HKY hky1 = new HKY(kappa1, freqModel);
HKY hky2 = new HKY(kappa2, freqModel);
List<SubstitutionModel> substModelList = new ArrayList<SubstitutionModel>();
substModelList.add(hky1);
substModelList.add(hky2);
Parameter epochTimes = new Parameter.Default(1, 20);
EpochBranchSubstitutionModel substitutionModel = new EpochBranchSubstitutionModel(
substModelList,
frequencyModelList,
epochTimes
);
// create site model
GammaSiteRateModel siteRateModel = new GammaSiteRateModel("siteModel");
siteRateModel.addModel(substitutionModel);
// create branch rate model
BranchRateModel branchRateModel = new DefaultBranchRateModel();
// feed to sequence simulator and generate leaves
BeagleSequenceSimulator beagleSequenceSimulator = new BeagleSequenceSimulator(
treeModel,
siteRateModel,
branchRateModel,
freqModel,
sequenceLength
);
Sequence ancestralSequence = new Sequence();
ancestralSequence.appendSequenceString("TCAGGTCAAG");
beagleSequenceSimulator.setAncestralSequence(ancestralSequence);
System.out.println(beagleSequenceSimulator.simulate().toString());
} catch (Exception e) {
e.printStackTrace();
}// END: try-catch block
}// END : simulateEpochModel
public static void printArray(int[] category) {
for (int i = 0; i < category.length; i++) {
System.out.println(category[i]);
}
}// END: printArray
public static void printArray(double[] category) {
for (int i = 0; i < category.length; i++) {
System.out.println(category[i]);
}
System.out.print("\n");
}// END: printArray
public void print2DArray(double[][] array) {
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
System.out.print(array[row][col] + " ");
}
System.out.print("\n");
}
}// END: print2DArray
public static void print2DArray(int[][] array) {
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
System.out.print(array[row][col] + " ");
}
System.out.print("\n");
}
}// END: print2DArray
} // END: class
|
package dr.app.tracer.traces;
import dr.inference.trace.TraceCorrelation;
import dr.inference.trace.TraceDistribution;
import dr.inference.trace.TraceList;
import org.virion.jam.framework.Exportable;
import org.virion.jam.table.TableRenderer;
import javax.swing.*;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.text.DecimalFormat;
public class SummaryStatisticsPanel extends JPanel implements Exportable {
static final String NAME_ROW = "name";
static final String MEAN_ROW = "mean";
static final String STDEV_ROW = "stderr of mean";
static final String GEOMETRIC_MEAN_ROW = "geometric mean";
static final String MEDIAN_ROW = "median";
static final String LOWER_ROW = "95% HPD lower";
static final String UPPER_ROW = "95% HPD upper";
static final String ACT_ROW = "auto-correlation time (ACT)";
static final String ESS_ROW = "effective sample size (ESS)";
static final String SUM_ESS_ROW = "effective sample size (sum of ESS)";
TraceList[] traceLists = null;
java.util.List<String> traceNames = null;
StatisticsModel statisticsModel;
JTable statisticsTable = null;
JScrollPane scrollPane1 = null;
JPanel topPanel = null;
JSplitPane splitPane1 = null;
int dividerLocation = -1;
FrequencyPanel frequencyPanel = null;
IntervalsPanel intervalsPanel = null;
JComponent currentPanel = null;
public SummaryStatisticsPanel(JFrame frame) {
setOpaque(false);
statisticsModel = new StatisticsModel();
statisticsTable = new JTable(statisticsModel);
statisticsTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.RIGHT, new Insets(0, 4, 0, 4)));
statisticsTable.getColumnModel().getColumn(1).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
scrollPane1 = new JScrollPane(statisticsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
topPanel = new JPanel(new BorderLayout(0, 0));
topPanel.setOpaque(false);
topPanel.setBorder(new BorderUIResource.EmptyBorderUIResource(
new java.awt.Insets(0, 0, 6, 0)));
topPanel.add(scrollPane1, BorderLayout.CENTER);
frequencyPanel = new FrequencyPanel(frame);
frequencyPanel.setBorder(new BorderUIResource.EmptyBorderUIResource(
new java.awt.Insets(6, 0, 0, 0)));
intervalsPanel = new IntervalsPanel();
intervalsPanel.setBorder(new BorderUIResource.EmptyBorderUIResource(
new java.awt.Insets(6, 0, 0, 0)));
splitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topPanel, frequencyPanel);
splitPane1.setOpaque(false);
splitPane1.setBorder(null);
// splitPane1.setBorder(new BorderUIResource.EmptyBorderUIResource(
// new java.awt.Insets(12, 12, 12, 12)));
setLayout(new BorderLayout(0, 0));
add(splitPane1, BorderLayout.CENTER);
splitPane1.setDividerLocation(2000);
}
private void setupDividerLocation() {
if (dividerLocation == -1 || dividerLocation == splitPane1.getDividerLocation()) {
int h0 = topPanel.getHeight();
int h1 = scrollPane1.getViewport().getHeight();
int h2 = statisticsTable.getPreferredSize().height;
dividerLocation = h2 + h0 - h1;
splitPane1.setDividerLocation(dividerLocation);
}
}
public void setTraces(TraceList[] traceLists, java.util.List<String> traceNames) {
this.traceLists = traceLists;
this.traceNames = traceNames;
int divider = splitPane1.getDividerLocation();
statisticsModel.fireTableStructureChanged();
if (traceLists != null && traceNames != null) {
if (traceLists.length == 1 && traceNames.size() == 1) {
statisticsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
currentPanel = frequencyPanel;
frequencyPanel.setTrace(traceLists[0], traceNames.get(0));
intervalsPanel.setTraces(null, null);
splitPane1.setBottomComponent(frequencyPanel);
} else {
statisticsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
statisticsTable.getColumnModel().getColumn(0).setPreferredWidth(200);
for (int i = 1; i < statisticsTable.getColumnCount(); i++) {
statisticsTable.getColumnModel().getColumn(i).setPreferredWidth(100);
}
currentPanel = intervalsPanel;
frequencyPanel.setTrace(null, null);
intervalsPanel.setTraces(traceLists, traceNames);
splitPane1.setBottomComponent(intervalsPanel);
}
} else {
currentPanel = statisticsTable;
frequencyPanel.setTrace(null, null);
splitPane1.setBottomComponent(frequencyPanel);
}
splitPane1.setDividerLocation(divider);
statisticsTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.RIGHT, new Insets(0, 4, 0, 4)));
for (int i = 1; i < statisticsTable.getColumnCount(); i++) {
statisticsTable.getColumnModel().getColumn(i).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
}
setupDividerLocation();
validate();
repaint();
}
public JComponent getExportableComponent() {
if (currentPanel instanceof Exportable) {
return ((Exportable) currentPanel).getExportableComponent();
}
return currentPanel;
}
public String toString() {
return statisticsModel.toString();
}
class StatisticsModel extends AbstractTableModel {
String[] rowNames = {MEAN_ROW, STDEV_ROW, MEDIAN_ROW, GEOMETRIC_MEAN_ROW, LOWER_ROW, UPPER_ROW, ACT_ROW, ESS_ROW};
private DecimalFormat formatter = new DecimalFormat("0.
private DecimalFormat formatter2 = new DecimalFormat("
public StatisticsModel() {
}
public int getColumnCount() {
if (traceLists != null && traceNames != null) {
return (traceLists.length * traceNames.size()) + 1;
} else {
return 2;
}
}
public int getRowCount() {
return rowNames.length;
}
public Object getValueAt(int row, int col) {
if (col == 0) {
return rowNames[row];
}
TraceCorrelation tc = null;
if (traceLists != null && traceNames != null) {
int n1 = (col - 1) / traceNames.size();
int n2 = (col - 1) % traceNames.size();
TraceList tl = traceLists[n1];
int index = tl.getTraceIndex(traceNames.get(n2));
tc = tl.getCorrelationStatistics(index);
} else {
return "-";
}
double value = 0.0;
if (tc != null) {
if (row != 0 && !tc.isValid()) return "n/a";
switch (row) {
case 0:
value = tc.getMean();
break;
case 1:
value = tc.getStdErrorOfMean();
break;
case 2:
value = tc.getMedian();
break;
case 3:
if (!tc.hasGeometricMean()) return "n/a";
value = tc.getGeometricMean();
break;
case 4:
value = tc.getLowerHPD();
break;
case 5:
value = tc.getUpperHPD();
break;
case 6:
value = tc.getACT();
break;
case 7:
value = tc.getESS();
break;
}
} else {
return "-";
}
if (value > 0 && (Math.abs(value) < 0.1 || Math.abs(value) >= 100000.0)) {
return formatter.format(value);
} else return formatter2.format(value);
}
public String getColumnName(int column) {
if (column == 0) return "Summary Statistic";
if (traceLists != null && traceNames != null) {
int n1 = (column - 1) / traceNames.size();
int n2 = (column - 1) % traceNames.size();
String columnName = "";
if (traceLists.length > 1) {
columnName += traceLists[n1].getName();
if (traceNames.size() > 1) {
columnName += ": ";
}
}
if (traceNames.size() > 1) {
columnName += traceNames.get(n2);
}
return columnName;
}
return "-";
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
}
|
package dr.evolution.coalescent;
import dr.evolution.util.Units;
import dr.math.Binomial;
import dr.math.MathUtils;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.analysis.RombergIntegrator;
import org.apache.commons.math.MaxIterationsExceededException;
import org.apache.commons.math.FunctionEvaluationException;
/**
* This interface provides methods that describe a demographic function.
*
* Parts of this class were derived from C++ code provided by Oliver Pybus.
*
* @version $Id: DemographicFunction.java,v 1.12 2005/05/24 20:25:55 rambaut Exp $
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Korbinian Strimmer
*/
public interface DemographicFunction extends UnivariateRealFunction, Units {
/**
* @param t time
* @return value of the demographic function N(t) at time t
*/
double getDemographic(double t);
double getLogDemographic(double t);
/**
* @return value of demographic intensity function at time t (= integral 1/N(x) dx from 0 to t).
* @param t time
*/
double getIntensity(double t);
/**
* @return value of inverse demographic intensity function
* (returns time, needed for simulation of coalescent intervals).
*/
double getInverseIntensity(double x);
/**
* Calculates the integral 1/N(x) dx between start and finish.
* @param start point
* @param finish point
* @return integral value
*/
double getIntegral(double start, double finish);
/**
* @return the number of arguments for this function.
*/
int getNumArguments();
/**
* @return the name of the n'th argument of this function.
*/
String getArgumentName(int n);
/**
* @return the value of the n'th argument of this function.
*/
double getArgument(int n);
/**
* Sets the value of the nth argument of this function.
*/
void setArgument(int n, double value);
/**
* @return the lower bound of the nth argument of this function.
*/
double getLowerBound(int n);
/**
* Returns the upper bound of the nth argument of this function.
*/
double getUpperBound(int n);
/**
* Returns a copy of this function.
*/
DemographicFunction getCopy();
public abstract class Abstract implements DemographicFunction
{
// private static final double LARGE_POSITIVE_NUMBER = 1.0e50;
// private static final double LARGE_NEGATIVE_NUMBER = -1.0e50;
// private static final double INTEGRATION_PRECISION = 1.0e-5;
// private static final double INTEGRATION_MAX_ITERATIONS = 50;
RombergIntegrator numericalIntegrator = null;
/**
* Construct demographic model with default settings
*/
public Abstract(Type units) {
setUnits(units);
}
// general functions
/**
* Default implementation
* @param t
* @return log(demographic at t)
*/
public double getLogDemographic(double t) {
return Math.log(getDemographic(t));
}
/**
* Calculates the integral 1/N(x) dx between start and finish.
*/
public double getIntegral(double start, double finish)
{
return getIntensity(finish) - getIntensity(start);
}
/**
* Returns the integral of 1/N(x) between start and finish, calling either the getAnalyticalIntegral or
* getNumericalIntegral function as appropriate.
*/
public double getNumericalIntegral(double start, double finish) {
// AER 19th March 2008: I switched this to use the RombergIntegrator from
// commons-math v1.2.
if (start > finish) {
throw new RuntimeException("NumericalIntegration start > finish");
}
if (start == finish) {
return 0.0;
}
if (numericalIntegrator == null) {
numericalIntegrator = new RombergIntegrator(this);
}
try {
return numericalIntegrator.integrate(start, finish);
} catch (MaxIterationsExceededException e) {
throw new RuntimeException(e);
} catch (FunctionEvaluationException e) {
throw new RuntimeException(e);
}
// double lastST = LARGE_NEGATIVE_NUMBER;
// double lastS = LARGE_NEGATIVE_NUMBER;
// assert(finish > start);
// for (int j = 1; j <= INTEGRATION_MAX_ITERATIONS; j++) {
// // iterate doTrapezoid() until answer obtained
// double st = doTrapezoid(j, start, finish, lastST);
// double s = (4.0 * st - lastST) / 3.0;
// // If answer is within desired accuracy then return
// if (Math.abs(s - lastS) < INTEGRATION_PRECISION * Math.abs(lastS)) {
// return s;
// lastS = s;
// lastST = st;
// throw new RuntimeException("Too many iterations in getNumericalIntegral");
}
/**
* Performs the trapezoid rule.
*/
// private double doTrapezoid(int n, double low, double high, double lastS) {
// double s;
// if (n == 1) {
// // On the first iteration s is reset
// double demoLow = getDemographic(low); // Value of N(x) obtained here
// assert(demoLow > 0.0);
// double demoHigh = getDemographic(high);
// assert(demoHigh > 0.0);
// s = 0.5 * (high - low) * ( (1.0 / demoLow) + (1.0 / demoHigh) );
// } else {
// int it=1;
// for (int j = 1; j < n - 1; j++) {
// it *= 2;
// double tnm = it; // number of points
// double del = (high - low) / tnm; // width of spacing between points
// double x = low + 0.5 * del;
// double sum = 0.0;
// for (int j = 1; j <= it; j++) {
// double demoX = getDemographic(x); // Value of N(x) obtained here
// assert(demoX > 0.0);
// sum += (1.0 / demoX);
// x += del;
// s = 0.5 * (lastS + (high - low) * sum / tnm); // New s uses previous s value
// return s;
// UnivariateRealFunction IMPLEMENTATION
/**
* Return the intensity at a given time for numerical integration
* @param x the time
* @return the intensity
*/
public double value(double x) {
return 1.0 / getDemographic(x);
}
// Units IMPLEMENTATION
/**
* Units in which population size is measured.
*/
private Type units;
/**
* sets units of measurement.
*
* @param u units
*/
public void setUnits(Type u)
{
units = u;
}
/**
* returns units of measurement.
*/
public Type getUnits()
{
return units;
}
}
public static class Utils
{
private static double getInterval(double U, DemographicFunction demographicFunction,
int lineageCount, double timeOfLastCoalescent) {
final double intensity = demographicFunction.getIntensity(timeOfLastCoalescent);
final double tmp = -Math.log(U)/Binomial.choose2(lineageCount) + intensity;
return demographicFunction.getInverseIntensity(tmp) - timeOfLastCoalescent;
}
/**
* @return a random interval size selected from the Kingman prior of the demographic model.
*/
public static double getSimulatedInterval(DemographicFunction demographicFunction,
int lineageCount, double timeOfLastCoalescent)
{
final double U = MathUtils.nextDouble(); // create unit uniform random variate
return getInterval(U, demographicFunction, lineageCount, timeOfLastCoalescent);
}
public static double getMedianInterval(DemographicFunction demographicFunction,
int lineageCount, double timeOfLastCoalescent)
{
return getInterval(0.5, demographicFunction, lineageCount, timeOfLastCoalescent);
}
/**
* This function tests the consistency of the
* getIntensity and getInverseIntensity methods
* of this demographic model. If the model is
* inconsistent then a RuntimeException will be thrown.
* @param demographicFunction the demographic model to test.
* @param steps the number of steps between 0.0 and maxTime to test.
* @param maxTime the maximum time to test.
*/
public static void testConsistency(DemographicFunction demographicFunction, int steps, double maxTime) {
double delta = maxTime / (double)steps;
for (int i = 0; i <= steps; i++) {
double time = (double)i * delta;
double intensity = demographicFunction.getIntensity(time);
double newTime = demographicFunction.getInverseIntensity(intensity);
if (Math.abs(time - newTime) > 1e-12) {
throw new RuntimeException(
"Demographic model not consistent! error size = " +
Math.abs(time-newTime));
}
}
}
}
}
|
package dr.evomodel.treelikelihood;
import dr.evolution.util.TaxonList;
import dr.inference.model.Parameter;
import dr.xml.*;
import java.util.logging.Logger;
/**
* @author Andrew Rambaut
* @version $Id$
*/
public class APOBECErrorModel extends TipPartialsModel {
public enum APOBECType {
ALL("all"),
BOTH("both"),
HA3G("hA3G"),
HA3F("hA3F");
APOBECType(String label) {
this.label = label;
}
public String toString() {
return label;
}
final String label;
}
public static final String APOBEC_ERROR_MODEL = "APOBECErrorModel";
public static final String HYPERMUTATION_RATE = "hypermutationRate";
public static final String HYPERMUTATION_INDICATORS = "hypermutationIndicators";
public APOBECErrorModel(APOBECType type, Parameter hypermutationRateParameter, Parameter hypermuationIndicatorParameter) {
super(APOBEC_ERROR_MODEL, null, null);
this.type = type;
this.hypermutationRateParameter = hypermutationRateParameter;
addParameter(this.hypermutationRateParameter);
this.hypermuationIndicatorParameter = hypermuationIndicatorParameter;
addParameter(this.hypermuationIndicatorParameter);
}
public void getTipPartials(int nodeIndex, double[] partials) {
int[] states = this.states[nodeIndex];
if (hypermuationIndicatorParameter.getParameterValue(nodeIndex) > 0.0) {
double rate = hypermutationRateParameter.getParameterValue(0);
int k = 0;
int nextState;
for (int j = 0; j < patternCount; j++) {
switch (states[j]) {
case 0: // is an A
double pMutated = 0.0;
if (j < patternCount - 1) {
nextState = states[j+1];
if ( (type == APOBECType.ALL) ||
(type == APOBECType.HA3G && nextState == 2) || // is a G
(type == APOBECType.HA3F && nextState == 0) || // is an A
(type == APOBECType.BOTH && (nextState == 2 || nextState == 0))
) {
pMutated = rate;
}
}
partials[k] = 1.0 - pMutated;
partials[k + 1] = 0.0;
partials[k + 2] = pMutated;
partials[k + 3] = 0.0;
break;
case 1: // is an C
partials[k] = 0.0;
partials[k + 1] = 1.0;
partials[k + 2] = 0.0;
partials[k + 3] = 0.0;
break;
case 2: // is an G
partials[k] = 0.0;
partials[k + 1] = 0.0;
partials[k + 2] = 1.0;
partials[k + 3] = 0.0;
break;
case 3: // is an T
partials[k] = 0.0;
partials[k + 1] = 0.0;
partials[k + 2] = 0.0;
partials[k + 3] = 1.0;
break;
default: // is an ambiguity
partials[k] = 1.0;
partials[k + 1] = 1.0;
partials[k + 2] = 1.0;
partials[k + 3] = 1.0;
}
k += stateCount;
}
} else {
int k = 0;
for (int j = 0; j < patternCount; j++) {
switch (states[j]) {
case 0: // is an A
partials[k] = 1.0;
partials[k + 1] = 0.0;
partials[k + 2] = 0.0;
partials[k + 3] = 0.0;
break;
case 1: // is an C
partials[k] = 0.0;
partials[k + 1] = 1.0;
partials[k + 2] = 0.0;
partials[k + 3] = 0.0;
break;
case 2: // is an G
partials[k] = 0.0;
partials[k + 1] = 0.0;
partials[k + 2] = 1.0;
partials[k + 3] = 0.0;
break;
case 3: // is an T
partials[k] = 0.0;
partials[k + 1] = 0.0;
partials[k + 2] = 0.0;
partials[k + 3] = 1.0;
break;
default: // is an ambiguity
partials[k] = 1.0;
partials[k + 1] = 1.0;
partials[k + 2] = 1.0;
partials[k + 3] = 1.0;
}
k += stateCount;
}
}
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() { return APOBEC_ERROR_MODEL; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
APOBECType type = APOBECType.HA3G;
if (xo.hasAttribute("type")) {
if (xo.getStringAttribute("type").equalsIgnoreCase("all")) {
type = APOBECType.ALL;
} else if (xo.getStringAttribute("type").equalsIgnoreCase("both")) {
type = APOBECType.BOTH;
} else if (xo.getStringAttribute("type").equalsIgnoreCase("hA3F")) {
type = APOBECType.HA3F;
} else if (!xo.getStringAttribute("type").equalsIgnoreCase("hA3G")) {
throw new XMLParseException("unrecognized option for attribute, 'type': " + xo.getStringAttribute("type"));
}
}
Parameter hypermutationRateParameter = null;
if (xo.hasChildNamed(HYPERMUTATION_RATE)) {
hypermutationRateParameter = (Parameter)xo.getElementFirstChild(HYPERMUTATION_RATE);
}
Parameter hypermuationIndicatorParameter = null;
if (xo.hasChildNamed(HYPERMUTATION_INDICATORS)) {
hypermuationIndicatorParameter = (Parameter)xo.getElementFirstChild(HYPERMUTATION_INDICATORS);
}
APOBECErrorModel errorModel = new APOBECErrorModel(
type, hypermutationRateParameter, hypermuationIndicatorParameter);
Logger.getLogger("dr.evomodel").info("Using APOBEC error model, assuming APOBEC " + type.name());
return errorModel;
}
|
package fitnesse.testsystems.slim;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.atomic.AtomicInteger;
import fitnesse.socketservice.SocketFactory;
import fitnesse.slim.JavaSlimFactory;
import fitnesse.slim.SlimService;
import fitnesse.testsystems.ClientBuilder;
import fitnesse.testsystems.CommandRunner;
import fitnesse.testsystems.Descriptor;
import fitnesse.testsystems.MockCommandRunner;
public class SlimClientBuilder extends ClientBuilder<SlimCommandRunningClient> {
public static final String SLIM_PORT = "SLIM_PORT";
public static final String SLIM_HOST = "SLIM_HOST";
public static final String SLIM_FLAGS = "SLIM_FLAGS";
public static final String MANUALLY_START_TEST_RUNNER_ON_DEBUG = "MANUALLY_START_TEST_RUNNER_ON_DEBUG";
private static final AtomicInteger slimPortOffset = new AtomicInteger(0);
private final int slimPort;
public SlimClientBuilder(Descriptor descriptor) {
super(descriptor);
slimPort = getNextSlimPort();
}
@Override
public SlimCommandRunningClient build() throws IOException {
CommandRunner commandRunner;
if (useManualStartForTestSystem()) {
commandRunner = new MockCommandRunner();
} else {
commandRunner = new CommandRunner(buildCommand(), "", descriptor.createClasspathEnvironment(descriptor.getClassPath()));
}
return new SlimCommandRunningClient(commandRunner, determineSlimHost(), getSlimPort());
}
protected String buildCommand() {
String slimArguments = buildArguments();
String slimCommandPrefix = super.buildCommand(descriptor.getCommandPattern(), descriptor.getTestRunner(), descriptor.getClassPath());
return String.format("%s %s", slimCommandPrefix, slimArguments);
}
protected String buildArguments() {
int slimSocket = getSlimPort();
String slimFlags = getSlimFlags();
return String.format("%s %d", slimFlags, slimSocket);
}
//For testing only. Makes responder faster.
void createSlimService(String args) throws IOException {
while (!tryCreateSlimService(args))
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// For testing only
private boolean tryCreateSlimService(String args) throws IOException {
try {
SlimService.Options options = SlimService.parseCommandLine(args.trim().split(" "));
SlimService.startWithFactoryAsync(new JavaSlimFactory(), options);
return true;
} catch (IOException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public int getSlimPort() {
return slimPort;
}
private int findFreePort() {
int port;
try {
ServerSocket socket = SocketFactory.tryCreateServerSocket(0);
port = socket.getLocalPort();
socket.close();
} catch (Exception e) {
port = -1;
}
return port;
}
private int getNextSlimPort() {
final int base = getSlimPortBase();
final int poolSize = getSlimPortPoolSize();
if (base == 0) {
return findFreePort();
}
synchronized (slimPortOffset) {
int offset = slimPortOffset.get();
offset = (offset + 1) % poolSize;
slimPortOffset.set(offset);
return offset + base;
}
}
public static void clearSlimPortOffset() {
slimPortOffset.set(0);
}
private int getSlimPortBase() {
try {
String port = descriptor.getVariable("slim.port");
if (port == null) {
port = descriptor.getVariable(SLIM_PORT);
}
if (port != null) {
return Integer.parseInt(port);
}
} catch (NumberFormatException e) {
// stick with default
}
return 8085;
}
private int getSlimPortPoolSize() {
try {
String poolSize = descriptor.getVariable("slim.pool.size");
if (poolSize != null) {
return Integer.parseInt(poolSize);
}
} catch (NumberFormatException e) {
// stick with default
}
return 10;
}
String determineSlimHost() {
String slimHost = descriptor.getVariable("slim.host");
if (slimHost == null) {
slimHost = descriptor.getVariable(SLIM_HOST);
}
return slimHost == null ? "localhost" : slimHost;
}
String getSlimFlags() {
String slimFlags = descriptor.getVariable("slim.flags");
if (slimFlags == null) {
slimFlags = descriptor.getVariable(SLIM_FLAGS);
}
return slimFlags == null ? "" : slimFlags;
}
private boolean useManualStartForTestSystem() {
if (descriptor.isDebug()) {
String useManualStart = descriptor.getVariable("manually.start.test.runner.on.debug");
if (useManualStart == null) {
useManualStart = descriptor.getVariable(MANUALLY_START_TEST_RUNNER_ON_DEBUG);
}
return (useManualStart != null && useManualStart.toLowerCase().equals("true"));
}
return false;
}
}
|
package org.voltdb.export;
import static com.google_voltpatches.common.base.Preconditions.checkNotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.BinaryPayloadMessage;
import org.voltcore.messaging.Mailbox;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.DBBPool;
import org.voltcore.utils.DBBPool.BBContainer;
import org.voltcore.utils.Pair;
import org.voltdb.VoltDB;
import org.voltdb.VoltType;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Column;
import org.voltdb.common.Constants;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.VoltFile;
import com.google_voltpatches.common.base.Charsets;
import com.google_voltpatches.common.base.Preconditions;
import com.google_voltpatches.common.base.Throwables;
import com.google_voltpatches.common.collect.ImmutableList;
import com.google_voltpatches.common.io.Files;
import com.google_voltpatches.common.util.concurrent.ListenableFuture;
import com.google_voltpatches.common.util.concurrent.ListeningExecutorService;
import com.google_voltpatches.common.util.concurrent.SettableFuture;
import java.util.concurrent.RejectedExecutionException;
/**
* Allows an ExportDataProcessor to access underlying table queues
*/
public class ExportDataSource implements Comparable<ExportDataSource> {
/**
* Processors also log using this facility.
*/
private static final VoltLogger exportLog = new VoltLogger("EXPORT");
private final String m_database;
private final String m_tableName;
private final String m_signature;
private final byte [] m_signatureBytes;
private final long m_HSId;
private final long m_generation;
private final int m_partitionId;
public final ArrayList<String> m_columnNames = new ArrayList<String>();
public final ArrayList<Integer> m_columnTypes = new ArrayList<Integer>();
public final ArrayList<Integer> m_columnLengths = new ArrayList<Integer>();
private long m_firstUnpolledUso = 0;
private final StreamBlockQueue m_committedBuffers;
private boolean m_endOfStream = false;
private Runnable m_onDrain;
private Runnable m_onMastership;
private final ListeningExecutorService m_es;
private SettableFuture<BBContainer> m_pollFuture;
private final AtomicReference<Pair<Mailbox, ImmutableList<Long>>> m_ackMailboxRefs =
new AtomicReference<Pair<Mailbox,ImmutableList<Long>>>(Pair.of((Mailbox)null, ImmutableList.<Long>builder().build()));
private final Semaphore m_bufferPushPermits = new Semaphore(16);
private final int m_nullArrayLength;
private long m_polledBlockSize = 0;
/**
* Create a new data source.
* @param db
* @param tableName
* @param isReplicated
* @param partitionId
* @param HSId
* @param tableId
* @param catalogMap
*/
public ExportDataSource(
final Runnable onDrain,
String db, String tableName,
int partitionId, long HSId, String signature, long generation,
CatalogMap<Column> catalogMap,
String overflowPath
) throws IOException
{
checkNotNull( onDrain, "onDrain runnable is null");
m_generation = generation;
m_onDrain = new Runnable() {
@Override
public void run() {
try {
onDrain.run();
} finally {
m_onDrain = null;
forwardAckToOtherReplicas(Long.MIN_VALUE);
}
}
};
m_database = db;
m_tableName = tableName;
m_es =
CoreUtils.getListeningExecutorService(
"ExportDataSource gen " + m_generation
+ " table " + m_tableName + " partition " + partitionId, 1);
String nonce = signature + "_" + HSId + "_" + partitionId;
m_committedBuffers = new StreamBlockQueue(overflowPath, nonce);
/*
* This is not the catalog relativeIndex(). This ID incorporates
* a catalog version and a table id so that it is constant across
* catalog updates that add or drop tables.
*/
m_signature = signature;
m_signatureBytes = m_signature.getBytes(Constants.UTF8ENCODING);
m_partitionId = partitionId;
m_HSId = HSId;
// Add the Export meta-data columns to the schema followed by the
// catalog columns for this table.
m_columnNames.add("VOLT_TRANSACTION_ID");
m_columnTypes.add(((int)VoltType.BIGINT.getValue()));
m_columnLengths.add(8);
m_columnNames.add("VOLT_EXPORT_TIMESTAMP");
m_columnTypes.add(((int)VoltType.BIGINT.getValue()));
m_columnLengths.add(8);
m_columnNames.add("VOLT_EXPORT_SEQUENCE_NUMBER");
m_columnTypes.add(((int)VoltType.BIGINT.getValue()));
m_columnLengths.add(8);
m_columnNames.add("VOLT_PARTITION_ID");
m_columnTypes.add(((int)VoltType.BIGINT.getValue()));
m_columnLengths.add(8);
m_columnNames.add("VOLT_SITE_ID");
m_columnTypes.add(((int)VoltType.BIGINT.getValue()));
m_columnLengths.add(8);
m_columnNames.add("VOLT_EXPORT_OPERATION");
m_columnTypes.add(((int)VoltType.TINYINT.getValue()));
m_columnLengths.add(1);
for (Column c : CatalogUtil.getSortedCatalogItems(catalogMap, "index")) {
m_columnNames.add(c.getName());
m_columnTypes.add(c.getType());
m_columnLengths.add(c.getSize());
}
File adFile = new VoltFile(overflowPath, nonce + ".ad");
exportLog.info("Creating ad for " + nonce);
assert(!adFile.exists());
byte jsonBytes[] = null;
try {
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.key("hsId").value(m_HSId);
stringer.key("database").value(m_database);
writeAdvertisementTo(stringer);
stringer.endObject();
JSONObject jsObj = new JSONObject(stringer.toString());
jsonBytes = jsObj.toString(4).getBytes(Charsets.UTF_8);
} catch (JSONException e) {
Throwables.propagate(e);
}
FileOutputStream fos = new FileOutputStream(adFile);
fos.write(jsonBytes);
fos.getFD().sync();
fos.close();
// compute the number of bytes necessary to hold one bit per
// schema column
m_nullArrayLength = ((m_columnTypes.size() + 7) & -8) >> 3;
}
public ExportDataSource(final Runnable onDrain,
File adFile
) throws IOException {
/*
* Certainly no more data coming if this is coming off of disk
*/
m_endOfStream = true;
m_onDrain = new Runnable() {
@Override
public void run() {
try {
onDrain.run();
} finally {
m_onDrain = null;
forwardAckToOtherReplicas(Long.MIN_VALUE);
}
}
};
String overflowPath = adFile.getParent();
byte data[] = Files.toByteArray(adFile);
try {
JSONObject jsObj = new JSONObject(new String(data, Charsets.UTF_8));
long version = jsObj.getLong("adVersion");
if (version != 0) {
throw new IOException("Unsupported ad file version " + version);
}
m_HSId = jsObj.getLong("hsId");
m_database = jsObj.getString("database");
m_generation = jsObj.getLong("generation");
m_partitionId = jsObj.getInt("partitionId");
m_signature = jsObj.getString("signature");
m_signatureBytes = m_signature.getBytes(Constants.UTF8ENCODING);
m_tableName = jsObj.getString("tableName");
JSONArray columns = jsObj.getJSONArray("columns");
for (int ii = 0; ii < columns.length(); ii++) {
JSONObject column = columns.getJSONObject(ii);
m_columnNames.add(column.getString("name"));
int columnType = column.getInt("type");
m_columnTypes.add(columnType);
m_columnLengths.add(column.getInt("length"));
}
} catch (JSONException e) {
throw new IOException(e);
}
String nonce = m_signature + "_" + m_HSId + "_" + m_partitionId;
m_committedBuffers = new StreamBlockQueue(overflowPath, nonce);
// compute the number of bytes necessary to hold one bit per
// schema column
m_nullArrayLength = ((m_columnTypes.size() + 7) & -8) >> 3;
m_es = CoreUtils.getListeningExecutorService("ExportDataSource gen " + m_generation + " table " + m_tableName + " partition " + m_partitionId, 1);
}
public void updateAckMailboxes( final Pair<Mailbox, ImmutableList<Long>> ackMailboxes) {
m_ackMailboxRefs.set( ackMailboxes);
}
private void releaseExportBytes(long releaseOffset) throws IOException {
// if released offset is in an already-released past, just return success
if (!m_committedBuffers.isEmpty() && releaseOffset < m_committedBuffers.peek().uso())
{
return;
}
long lastUso = m_firstUnpolledUso;
while (!m_committedBuffers.isEmpty() &&
releaseOffset >= m_committedBuffers.peek().uso()) {
StreamBlock sb = m_committedBuffers.peek();
if (releaseOffset >= sb.uso() + sb.totalUso()) {
m_committedBuffers.pop();
try {
lastUso = sb.uso() + sb.totalUso();
} finally {
sb.deleteContent();
}
} else if (releaseOffset >= sb.uso()) {
sb.releaseUso(releaseOffset);
lastUso = releaseOffset;
break;
}
}
m_firstUnpolledUso = Math.max(m_firstUnpolledUso, lastUso);
}
public String getDatabase() {
return m_database;
}
public String getTableName() {
return m_tableName;
}
public String getSignature() {
return m_signature;
}
public long getHSId() {
return m_HSId;
}
public int getPartitionId() {
return m_partitionId;
}
public void writeAdvertisementTo(JSONStringer stringer) throws JSONException {
stringer.key("adVersion").value(0);
stringer.key("generation").value(m_generation);
stringer.key("partitionId").value(getPartitionId());
stringer.key("signature").value(m_signature);
stringer.key("tableName").value(getTableName());
stringer.key("startTime").value(ManagementFactory.getRuntimeMXBean().getStartTime());
stringer.key("columns").array();
for (int ii=0; ii < m_columnNames.size(); ++ii) {
stringer.object();
stringer.key("name").value(m_columnNames.get(ii));
stringer.key("type").value(m_columnTypes.get(ii));
stringer.key("length").value(m_columnLengths.get(ii));
stringer.endObject();
}
stringer.endArray();
}
/**
* Compare two ExportDataSources for equivalence. This currently does not
* compare column names, but it should once column add/drop is allowed.
* This comparison is performed to decide if a datasource in a new catalog
* needs to be passed to a proccessor.
*/
@Override
public int compareTo(ExportDataSource o) {
int result;
result = m_database.compareTo(o.m_database);
if (result != 0) {
return result;
}
result = m_tableName.compareTo(o.m_tableName);
if (result != 0) {
return result;
}
result = Long.signum(m_HSId - o.m_HSId);
if (result != 0) {
return result;
}
result = (m_partitionId - o.m_partitionId);
if (result != 0) {
return result;
}
// does not verify replicated / unreplicated.
// does not verify column names / schema
return 0;
}
/**
* Make sure equal objects compareTo as 0.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof ExportDataSource))
return false;
return compareTo((ExportDataSource)o) == 0;
}
@Override
public int hashCode() {
// based on implementation of compareTo
int result = 0;
result += m_database.hashCode();
result += m_tableName.hashCode();
result += m_HSId;
result += m_partitionId;
// does not factor in replicated / unreplicated.
// does not factor in column names / schema
return result;
}
public long sizeInBytes() {
try {
return m_es.submit(new Callable<Long>() {
@Override
public Long call() throws Exception {
if (m_committedBuffers.sizeInBytes() > 0) {
exportLog.debug("Committed Buffers Size: " + m_committedBuffers.sizeInBytes());
}
if (m_polledBlockSize > 0) {
exportLog.debug("In Flight Block Size: " + m_polledBlockSize);
}
return m_committedBuffers.sizeInBytes() + m_polledBlockSize;
}
}).get();
} catch (Throwable t) {
Throwables.propagate(t);
return 0;
}
}
private void pushExportBufferImpl(
long uso,
final long bufferPtr,
ByteBuffer buffer,
boolean sync,
boolean endOfStream) {
final java.util.concurrent.atomic.AtomicBoolean deleted = new java.util.concurrent.atomic.AtomicBoolean(false);
if (endOfStream) {
assert(!m_endOfStream);
assert(bufferPtr == 0);
assert(buffer == null);
assert(!sync);
m_endOfStream = endOfStream;
if (m_committedBuffers.sizeInBytes() == 0) {
exportLog.info("Pushed EOS buffer with 0 bytes remaining");
if (m_pollFuture != null) {
m_pollFuture.set(null);
m_pollFuture = null;
}
if (m_onDrain != null) {
m_onDrain.run();
}
} else {
exportLog.info("EOS for " + m_tableName + " partition " + m_partitionId +
" with first unpolled uso " + m_firstUnpolledUso + " and remaining bytes " +
m_committedBuffers.sizeInBytes());
}
return;
}
assert(!m_endOfStream);
if (buffer != null) {
if (buffer.capacity() > 0) {
try {
m_committedBuffers.offer(new StreamBlock(
new BBContainer(buffer, bufferPtr) {
@Override
public void discard() {
DBBPool.deleteCharArrayMemory(address);
deleted.set(true);
}
}, uso, false));
} catch (IOException e) {
exportLog.error(e);
if (!deleted.get()) {
DBBPool.deleteCharArrayMemory(bufferPtr);
}
}
} else {
/*
* TupleStreamWrapper::setBytesUsed propagates the USO by sending
* over an empty stream block. The block will be deleted
* on the native side when this method returns
*/
exportLog.info("Syncing first unpolled USO to " + uso + " for table "
+ m_tableName + " partition " + m_partitionId);
m_firstUnpolledUso = uso;
}
}
if (sync) {
try {
//Don't do a real sync, just write the in memory buffers
//to a file. @Quiesce or blocking snapshot will do the sync
m_committedBuffers.sync(true);
} catch (IOException e) {
exportLog.error(e);
}
}
pollImpl(m_pollFuture);
}
public void pushExportBuffer(
final long uso,
final long bufferPtr,
final ByteBuffer buffer,
final boolean sync,
final boolean endOfStream) {
try {
m_bufferPushPermits.acquire();
} catch (InterruptedException e) {
Throwables.propagate(e);
}
executeExportDataSourceRunner((new Runnable() {
@Override
public void run() {
try {
pushExportBufferImpl(uso, bufferPtr, buffer, sync, endOfStream);
} catch (Exception e) {
exportLog.error("Error pushing export buffer", e);
} catch (Error e) {
VoltDB.crashLocalVoltDB("Error pushing export buffer", true, e);
} finally {
m_bufferPushPermits.release();
}
}
}));
}
public ListenableFuture<?> closeAndDelete() {
return m_es.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
m_committedBuffers.closeAndDelete();
return null;
} finally {
m_es.shutdown();
}
}
});
}
public long getGeneration() {
return m_generation;
}
public ListenableFuture<?> truncateExportToTxnId(final long txnId) {
return runExportDataSourceRunner((new Runnable() {
@Override
public void run() {
try {
m_committedBuffers.truncateToTxnId(txnId, m_nullArrayLength);
if (m_committedBuffers.isEmpty() && m_endOfStream) {
if (m_pollFuture != null) {
m_pollFuture.set(null);
m_pollFuture = null;
}
if (m_onDrain != null) {
m_onDrain.run();
}
}
} catch (IOException e) {
VoltDB.crashLocalVoltDB("Error while trying to truncate export to txnid " + txnId, true, e);
}
}
}));
}
public ListenableFuture<?> close() {
return runExportDataSourceRunner((new Runnable() {
@Override
public void run() {
try {
m_committedBuffers.close();
} catch (IOException e) {
exportLog.error(e);
} finally {
m_es.shutdown();
}
}
}));
}
public ListenableFuture<BBContainer> poll() {
final SettableFuture<BBContainer> fut = SettableFuture.create();
runExportDataSourceRunner(new Runnable() {
@Override
public void run() {
/*
* The poll is blocking through the future, shouldn't
* call poll a second time until a response has been given
* which nulls out the field
*/
if (m_pollFuture != null) {
fut.setException(new RuntimeException("Should not poll more than once"));
return;
}
pollImpl(fut);
}
});
return fut;
}
private void pollImpl(SettableFuture<BBContainer> fut) {
if (fut == null) return;
try {
StreamBlock first_unpolled_block = null;
if (m_endOfStream && m_committedBuffers.sizeInBytes() == 0) {
//Returning null indicates end of stream
fut.set(null);
if (m_onDrain != null) {
m_onDrain.run();
}
return;
}
//Assemble a list of blocks to delete so that they can be deleted
//outside of the m_committedBuffers critical section
ArrayList<StreamBlock> blocksToDelete = new ArrayList<StreamBlock>();
//Inside this critical section do the work to find out
//what block should be returned by the next poll.
//Copying and sending the data will take place outside the critical section
try {
Iterator<StreamBlock> iter = m_committedBuffers.iterator();
while (iter.hasNext()) {
StreamBlock block = iter.next();
// find the first block that has unpolled data
if (m_firstUnpolledUso < block.uso() + block.totalUso()) {
first_unpolled_block = block;
m_firstUnpolledUso = block.uso() + block.totalUso();
break;
} else {
blocksToDelete.add(block);
iter.remove();
}
}
} catch (RuntimeException e) {
if (e.getCause() instanceof IOException) {
VoltDB.crashLocalVoltDB("Error attempting to find unpolled export data", true, e);
} else {
throw e;
}
} finally {
//Try hard not to leak memory
for (StreamBlock sb : blocksToDelete) {
sb.deleteContent();
}
}
//If there are no unpolled blocks return the firstUnpolledUSO with no data
if (first_unpolled_block == null) {
m_pollFuture = fut;
} else {
//Otherwise return the block with the USO for the end of the block
//since the entire remainder of the block is being sent.
m_polledBlockSize = first_unpolled_block.totalUso();
fut.set(
new AckingContainer(first_unpolled_block.unreleasedBufferV2(),
first_unpolled_block.uso() + first_unpolled_block.totalUso()));
m_pollFuture = null;
}
} catch (Throwable t) {
m_polledBlockSize = 0;
fut.setException(t);
}
}
class AckingContainer extends BBContainer {
final long m_uso;
public AckingContainer(ByteBuffer buf, long uso) {
super(buf, 0L);
m_uso = uso;
}
@Override
public void discard() {
try {
ack(m_uso);
} finally {
forwardAckToOtherReplicas(m_uso);
}
}
}
private void forwardAckToOtherReplicas(long uso) {
Pair<Mailbox, ImmutableList<Long>> p = m_ackMailboxRefs.get();
Mailbox mbx = p.getFirst();
if (mbx != null) {
// partition:int(4) + length:int(4) +
// signaturesBytes.length + ackUSO:long(8)
final int msgLen = 4 + 4 + m_signatureBytes.length + 8;
ByteBuffer buf = ByteBuffer.allocate(msgLen);
buf.putInt(m_partitionId);
buf.putInt(m_signatureBytes.length);
buf.put(m_signatureBytes);
buf.putLong(uso);
BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], buf.array());
for( Long siteId: p.getSecond()) {
mbx.send(siteId, bpm);
}
}
}
public void ack(final long uso) {
executeExportDataSourceRunner(new Runnable() {
@Override
public void run() {
try {
ackImpl(uso);
} catch (Exception e) {
exportLog.error("Error acking export buffer", e);
} catch (Error e) {
VoltDB.crashLocalVoltDB("Error acking export buffer", true, e);
}
}
});
}
private void ackImpl(long uso) {
if (uso == Long.MIN_VALUE && m_onDrain != null) {
m_onDrain.run();
return;
}
//Process the ack if any and add blocks to the delete list or move the released USO pointer
if (uso > 0) {
try {
releaseExportBytes(uso);
} catch (IOException e) {
VoltDB.crashLocalVoltDB("Error attempting to release export bytes", true, e);
return;
}
}
}
/**
* Trigger an execution of the mastership runnable by the associated
* executor service
*/
public void acceptMastership() {
Preconditions.checkNotNull(m_onMastership, "mastership runnable is not yet set");
executeExportDataSourceRunner(m_onMastership);
}
/**
* set the runnable task that is to be executed on mastership designation
* @param toBeRunOnMastership a {@link @Runnable} task
*/
public void setOnMastership(Runnable toBeRunOnMastership) {
Preconditions.checkNotNull(toBeRunOnMastership, "mastership runnable is null");
m_onMastership = toBeRunOnMastership;
}
public void resetInFlightSize() {
m_polledBlockSize = 0;
}
private void executeExportDataSourceRunner(Runnable runner) {
try {
m_es.execute(new ExportDataSourceRunnable(runner));
} catch (RejectedExecutionException rej) {
rej.printStackTrace();
exportLog.warn("Failed to execute Export Data Source task.");
Throwables.propagate(rej);
}
}
/**
* Convenience method to submit wrapped Runnables to executor.
*
* @param runner Runnable task.
* @return ListenableFuture
*/
private ListenableFuture<?> runExportDataSourceRunner(Runnable runner) {
try {
return m_es.submit((Runnable) new ExportDataSourceRunnable(runner));
} catch (RejectedExecutionException rej) {
rej.printStackTrace();
exportLog.warn("Failed to submit Export Data Source task.");
Throwables.propagate(rej);
}
return null;
}
//Wrapper Runnable.
final class ExportDataSourceRunnable implements Runnable {
private final Runnable m_runner;
public ExportDataSourceRunnable(Runnable runner) {
m_runner = runner;
}
@Override
public void run() {
m_runner.run();
}
}
}
|
package gov.nih.nci.calab.dto.particle;
import gov.nih.nci.calab.domain.Keyword;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.function.Function;
import gov.nih.nci.calab.domain.nano.particle.Nanoparticle;
import gov.nih.nci.calab.dto.inventory.SampleBean;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* This class represents shared properties of nanoparticles to be shown in the
* view page.
*
* @author pansu
*
*/
public class ParticleBean extends SampleBean {
private String particleClassification;
private String[] functionTypes;
private String[] characterizations;
private String[] keywords;
private String[] visibilityGroups;
public ParticleBean(String id, String name) {
super(id, name);
}
public ParticleBean() {
}
public ParticleBean(String id, String name, String particleSource,
String particleType, String particleClassification,
String[] functionTypes, String[] characterizations,
String[] keywords) {
this(id, name);
setSampleType(particleType);
setSampleSource(particleSource);
this.particleClassification = particleClassification;
this.functionTypes = functionTypes;
this.characterizations = characterizations;
this.keywords = keywords;
}
public ParticleBean(Nanoparticle particle) {
this(particle.getId().toString(), particle.getName());
this.setSampleType(particle.getType());
this.setSampleSource(particle.getSource().getOrganizationName());
this.particleClassification = particle.getClassification();
try {
Collection<Keyword> keywordCol = particle.getKeywordCollection();
// get a unique set of keywords
Set<String> keywordSet = new HashSet<String>();
for (Keyword keywordObj : keywordCol) {
keywordSet.add(keywordObj.getName());
}
keywords = keywordSet.toArray(new String[0]);
Collection<Characterization> characterizationCol = particle
.getCharacterizationCollection();
// get a unique list of characterization
Set<String> charcterizationSet = new HashSet<String>();
for (Characterization charObj : characterizationCol) {
charcterizationSet.add(charObj.getClassification() + ":"
+ charObj.getName());
}
characterizations = charcterizationSet.toArray(new String[0]);
Collection<Function> functionCol = particle
.getFunctionCollection();
// get a unique list of function
Set<String> functionTypeSet = new HashSet<String>();
for (Function funcObj : functionCol) {
functionTypeSet.add(funcObj.getType());
}
functionTypes = functionTypeSet.toArray(new String[0]);
} catch (org.hibernate.LazyInitializationException e) {
// ignore this exception
}
}
public String[] getCharacterizations() {
return characterizations;
}
public void setCharacterizations(String[] characterizations) {
this.characterizations = characterizations;
}
public String[] getFunctionTypes() {
return functionTypes;
}
public void setFunctionTypes(String[] functionTypes) {
this.functionTypes = functionTypes;
}
public String[] getKeywords() {
return keywords;
}
public void setKeywords(String[] keywords) {
this.keywords = keywords;
}
public String getParticleClassification() {
return particleClassification;
}
public void setParticleClassification(String particleClassification) {
this.particleClassification = particleClassification;
}
public String[] getVisibilityGroups() {
return visibilityGroups;
}
public void setVisibilityGroups(String[] visibilityGroups) {
this.visibilityGroups = visibilityGroups;
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.ui;
import gov.nih.nci.ncicb.cadsr.loader.*;
import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEvent;
import gov.nih.nci.ncicb.cadsr.loader.event.ReviewListener;
import gov.nih.nci.ncicb.cadsr.loader.parser.ElementWriter;
import gov.nih.nci.ncicb.cadsr.loader.ui.tree.*;
import gov.nih.nci.ncicb.cadsr.loader.ui.event.*;
import gov.nih.nci.ncicb.cadsr.loader.util.*;
import gov.nih.nci.ncicb.cadsr.loader.ui.util.*;
import gov.nih.nci.ncicb.cadsr.loader.validator.*;
import java.awt.Component;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.io.File;
import javax.swing.*;
import java.util.*;
import gov.nih.nci.ncicb.cadsr.domain.*;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* The main Frame containing other frames
*
* @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a>
*/
public class MainFrame extends JFrame
implements ViewChangeListener, CloseableTabbedPaneListener,
PropertyChangeListener
{
private JMenuBar mainMenuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem saveAsMenuItem = new JMenuItem("Save As");
private JMenuItem exportErrorsMenuItem = new JMenuItem("Export");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private JMenu editMenu = new JMenu("Edit");
private JMenuItem findMenuItem = new JMenuItem("Find");
private JMenuItem prefMenuItem = new JMenuItem("Preferences");
private JMenu elementMenu = new JMenu("Element");
private JMenuItem applyMenuItem = new JMenuItem("Apply");
private JMenuItem applyToAllMenuItem = new JMenuItem("Apply to All");
private JMenu runMenu = new JMenu("Run");
private JMenuItem validateMenuItem = new JMenuItem("Validate");
private JMenuItem uploadMenuItem = new JMenuItem("Upload");
private JMenuItem defaultsMenuItem = new JMenuItem("Defaults");
private JMenu helpMenu = new JMenu("Help");
private JMenuItem aboutMenuItem = new JMenuItem("About");
private JMenuItem indexMenuItem = new JMenuItem("Index");
private JMenuItem semanticConnectorMenuItem = new JMenuItem("Semantic Connector");
private JSplitPane jSplitPane1 = new JSplitPane();
private JSplitPane jSplitPane2 = new JSplitPane();
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private CloseableTabbedPane viewTabbedPane = new CloseableTabbedPane();
private JPanel jPanel1 = new JPanel();
private NavigationPanel navigationPanel = new NavigationPanel();
private ErrorPanel errorPanel = null;
private MainFrame _this = this;
private JLabel infoLabel = new JLabel(" ");
private Map<String, UMLElementViewPanel> viewPanels = new HashMap();
private AssociationViewPanel associationViewPanel = null;
private ReviewTracker reviewTracker = ReviewTracker.getInstance();
private RunMode runMode = null;
private String saveFilename = "";
public MainFrame()
{
try
{
UserSelections selections = UserSelections.getInstance();
runMode = (RunMode)(selections.getProperty("MODE"));
saveFilename = (String)selections.getProperty("FILENAME");
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void exit() {
System.exit(0);
}
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("APPLY")) {
applyMenuItem.setEnabled((Boolean)evt.getNewValue());
applyToAllMenuItem.setEnabled((Boolean)evt.getNewValue());
if((Boolean)evt.getNewValue() == true)
infoLabel.setText("Unsaved Changes");
else
infoLabel.setText("Changes Applied");
}
}
private void jbInit() throws Exception
{
this.getContentPane().setLayout(new BorderLayout());
this.setSize(new Dimension(830, 650));
this.setJMenuBar(mainMenuBar);
UserSelections selections = UserSelections.getInstance();
String fileName = new File((String)selections.getProperty("FILENAME")).getName();
this.setTitle("Semantic Integration Workbench - " + fileName);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane1.setDividerLocation(160);
jSplitPane2.setDividerLocation(400);
fileMenu.add(saveMenuItem);
fileMenu.add(saveAsMenuItem);
fileMenu.addSeparator();
fileMenu.add(findMenuItem);
fileMenu.add(exportErrorsMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
mainMenuBar.add(fileMenu);
editMenu.add(findMenuItem);
editMenu.add(prefMenuItem);
mainMenuBar.add(editMenu);
applyMenuItem.setEnabled(false);
applyToAllMenuItem.setEnabled(false);
elementMenu.add(applyMenuItem);
elementMenu.add(applyToAllMenuItem);
mainMenuBar.add(elementMenu);
// runMenu.add(validateMenuItem);
if(runMode.equals(RunMode.Reviewer)) {
runMenu.add(uploadMenuItem);
uploadMenuItem.setEnabled(false);
runMenu.addSeparator();
runMenu.add(defaultsMenuItem);
mainMenuBar.add(runMenu);
}
helpMenu.add(indexMenuItem);
helpMenu.addSeparator();
helpMenu.add(aboutMenuItem);
mainMenuBar.add(helpMenu);
errorPanel = new ErrorPanel(TreeBuilder.getInstance().getRootNode());
jTabbedPane1.addTab("Errors", errorPanel);
Icon closeIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("close-tab.gif"));
viewTabbedPane.setCloseIcons(closeIcon, closeIcon, closeIcon);
viewTabbedPane.addCloseableTabbedPaneListener(this);
jTabbedPane1.addTab("Log", new JPanel());
jSplitPane2.add(jTabbedPane1, JSplitPane.BOTTOM);
jSplitPane2.add(viewTabbedPane, JSplitPane.TOP);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane1.add(navigationPanel, JSplitPane.LEFT);
navigationPanel.addViewChangeListener(this);
this.getContentPane().add(jSplitPane1, BorderLayout.CENTER);
this.getContentPane().add(infoLabel, BorderLayout.SOUTH);
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
_this.exit();
}
});
defaultsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
UmlDefaultsPanel dp = new UmlDefaultsPanel(_this);
dp.show();
UIUtil.putToCenter(dp);
}
});
findMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
SearchDialog sd = new SearchDialog(_this);
UIUtil.putToCenter(sd);
sd.addSearchListener(navigationPanel);
sd.setVisible(true);
}
});
findMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
final PreferenceDialog pd = new PreferenceDialog(_this);
prefMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
UIUtil.putToCenter(pd);
pd.setVisible(true);
}
});
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if(runMode.equals(RunMode.Reviewer)) {
JOptionPane.showMessageDialog(_this, "Sorry, Not Implemented Yet", "Not Implemented", JOptionPane.INFORMATION_MESSAGE);
return;
}
ElementWriter writer = BeansAccessor.getWriter();
writer.setOutput(saveFilename);
writer.write(ElementsLists.getInstance());
infoLabel.setText("File Saved");
}
});
saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String saveDir = UserPreferences.getInstance().getRecentDir();
JFileChooser chooser = new JFileChooser(saveDir);
javax.swing.filechooser.FileFilter filter =
new javax.swing.filechooser.FileFilter() {
String fileExtension = null;
{
if(runMode.equals(RunMode.Curator))
fileExtension = "csv";
else if(runMode.equals(RunMode.Reviewer))
fileExtension = "xmi";
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
return f.getName().endsWith("." + fileExtension);
}
public String getDescription() {
return fileExtension.toUpperCase() + " Files";
}
};
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String filePath = chooser.getSelectedFile().getAbsolutePath();
UserPreferences.getInstance().setRecentDir(filePath);
ElementWriter writer = BeansAccessor.getWriter();
writer.setOutput(filePath);
saveFilename = filePath;
writer.write(ElementsLists.getInstance());
infoLabel.setText("File Saved");
}
}
});
exportErrorsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(_this, "Sorry, Not Implemented Yet", "Not Implemented", JOptionPane.INFORMATION_MESSAGE);
}
});
validateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
ValidationItems.getInstance().clear();
Validator validator = new UMLValidator();
validator.validate();
errorPanel.update(TreeBuilder.getInstance().getRootNode());
JOptionPane.showMessageDialog(_this, "Sorry, Not Implemented Yet", "Not Implemented", JOptionPane.INFORMATION_MESSAGE);
}
});
uploadMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(_this, "Sorry, Not Implemented Yet", "Not Implemented", JOptionPane.INFORMATION_MESSAGE);
}
});
applyMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UMLElementViewPanel viewPanel =
(UMLElementViewPanel)viewTabbedPane
.getSelectedComponent();
viewPanel.apply(false);
}
});
applyToAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UMLElementViewPanel viewPanel =
(UMLElementViewPanel)viewTabbedPane
.getSelectedComponent();
viewPanel.apply(true);
}
});
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
new AboutPanel();
}
});
}
public void viewChanged(ViewChangeEvent event) {
if(event.getType() == ViewChangeEvent.VIEW_CONCEPTS) {
UMLNode node = (UMLNode)event.getViewObject();
// If concept is already showing, just bring it up front
if(viewPanels.containsKey(node.getFullPath())) {
UMLElementViewPanel pa = viewPanels.get(node.getFullPath());
viewTabbedPane.setSelectedComponent(pa);
return;
}
if((event.getInNewTab() == true) || (viewPanels.size() == 0)) {
UMLElementViewPanel viewPanel = new UMLElementViewPanel(node);
viewPanel.addPropertyChangeListener(this);
viewPanel.addReviewListener(navigationPanel);
viewPanel.addReviewListener(reviewTracker);
viewPanel.addElementChangeListener(ChangeTracker.getInstance());
viewPanel.addNavigationListener(navigationPanel);
navigationPanel.addNavigationListener(viewPanel);
String tabTitle = node.getDisplay();;
if(node instanceof AttributeNode)
tabTitle = node.getParent().getDisplay()
+ "." + tabTitle;
viewTabbedPane.addTab(tabTitle, viewPanel);
viewTabbedPane.setSelectedComponent(viewPanel);
viewPanel.setName(node.getFullPath());
viewPanels.put(viewPanel.getName(), viewPanel);
infoLabel.setText(tabTitle);
} else {
UMLElementViewPanel viewPanel = (UMLElementViewPanel)
viewTabbedPane.getSelectedComponent();
viewPanels.remove(viewPanel.getName());
String tabTitle = node.getDisplay();;
if(node instanceof AttributeNode)
tabTitle = node.getParent().getDisplay()
+ "." + tabTitle;
viewTabbedPane.setTitleAt(viewTabbedPane.getSelectedIndex(), tabTitle);
infoLabel.setText(tabTitle);
viewPanel.setName(node.getFullPath());
viewPanel.updateNode(node);
viewPanels.put(viewPanel.getName(), viewPanel);
}
} else if(event.getType() == ViewChangeEvent.VIEW_ASSOCIATION) {
UMLNode node = (UMLNode)event.getViewObject();
if(associationViewPanel == null) {
associationViewPanel = new AssociationViewPanel((ObjectClassRelationship)node.getUserObject());
viewTabbedPane.addTab("Association", associationViewPanel);
associationViewPanel.setName("Association");
infoLabel.setText("Association");
} else
associationViewPanel.update((ObjectClassRelationship)node.getUserObject());
viewTabbedPane.setSelectedComponent(associationViewPanel);
}
}
public boolean closeTab(int index) {
Component c = viewTabbedPane.getComponentAt(index);
if(c.equals(associationViewPanel))
associationViewPanel = null;
viewPanels.remove(c.getName());
return true;
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.ui;
import gov.nih.nci.ncicb.cadsr.loader.*;
import gov.nih.nci.ncicb.cadsr.loader.parser.ElementWriter;
import gov.nih.nci.ncicb.cadsr.loader.parser.ParserException;
import gov.nih.nci.ncicb.cadsr.loader.ui.tree.*;
import gov.nih.nci.ncicb.cadsr.loader.ui.event.*;
import gov.nih.nci.ncicb.cadsr.loader.util.*;
import gov.nih.nci.ncicb.cadsr.loader.ui.util.*;
import gov.nih.nci.ncicb.cadsr.loader.validator.*;
import java.awt.Component;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.io.File;
import javax.swing.*;
import java.util.*;
import gov.nih.nci.ncicb.cadsr.domain.*;
import org.apache.log4j.Logger;
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
/**
* The main Frame containing other frames
*
* @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a>
*/
public class MainFrame extends JFrame
implements ViewChangeListener, CloseableTabbedPaneListener,
PropertyChangeListener
{
private JMenuBar mainMenuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem saveAsMenuItem = new JMenuItem("Save As");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private JMenu editMenu = new JMenu("Edit");
private JMenuItem findMenuItem = new JMenuItem("Find");
private JMenuItem prefMenuItem = new JMenuItem("Preferences");
private JMenu elementMenu = new JMenu("Element");
private JMenuItem applyMenuItem = new JMenuItem("Apply");
private JMenuItem applyToAllMenuItem = new JMenuItem("Apply to All");
private JMenuItem previewReuseMenuItem = new JMenuItem("Preview DE Reuse");
private JMenu runMenu = new JMenu("Run");
private JMenuItem validateMenuItem = new JMenuItem("Validate");
private JMenuItem defaultsMenuItem = new JMenuItem("Defaults");
private JMenuItem validateConceptsMenuItem = new JMenuItem("Validate Concepts");
private JMenu helpMenu = new JMenu("Help");
private JMenuItem aboutMenuItem = new JMenuItem("About");
private JMenuItem indexMenuItem = new JMenuItem("SIW on GForge");
private JSplitPane jSplitPane1 = new JSplitPane();
private JSplitPane jSplitPane2 = new JSplitPane();
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private CloseableTabbedPane viewTabbedPane = new CloseableTabbedPane();
private DEReuseDialog reuseDialog;
private NavigationPanel navigationPanel;
private ErrorPanel errorPanel = null;
private JPanel logPanel;
private MainFrame _this = this;
private JLabel infoLabel = new JLabel(" ");
// private Map<String, UMLElementViewPanel> viewPanels = new HashMap();
private Map<String, NodeViewPanel> viewPanels = new HashMap();
private AssociationViewPanel associationViewPanel = null;
private ValueDomainViewPanel vdViewPanel = null;
private ReviewTracker ownerTracker, curatorTracker;
private RunMode runMode = null;
private String saveFilename = "";
private ElementWriter xmiWriter = null;
private static Logger logger = Logger.getLogger(MainFrame.class);
public MainFrame()
{
}
public void init() {
UserSelections selections = UserSelections.getInstance();
runMode = (RunMode)(selections.getProperty("MODE"));
// if(runMode.equals(RunMode.Curator))
curatorTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator);
ownerTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner);
saveFilename = (String)selections.getProperty("FILENAME");
this.reuseDialog = BeansAccessor.getDEReuseDialog();
jbInit();
}
public void exit() {
if(!ChangeTracker.getInstance().isEmpty()) {
int result = JOptionPane.showConfirmDialog((JFrame) null, "Would you like to save your file before quitting?");
switch(result) {
case JOptionPane.YES_OPTION:
saveMenuItem.doClick();
break;
case JOptionPane.NO_OPTION:
break;
case JOptionPane.CANCEL_OPTION:
return;
}
System.exit(0);
}
else
System.exit(0);
}
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("APPLY")) {
applyMenuItem.setEnabled((Boolean)evt.getNewValue());
applyToAllMenuItem.setEnabled((Boolean)evt.getNewValue());
if((Boolean)evt.getNewValue() == true)
infoLabel.setText("Unsaved Changes");
else
infoLabel.setText("Changes Applied");
} else if(evt.getPropertyName().equals("EXPORT_ERRORS")) {
infoLabel.setText("Export Errors Complete");
} else if(evt.getPropertyName().equals("EXPORT_ERRORS_FAILED")) {
infoLabel.setText("Export Errors Failed !");
}
}
/**
* Set the working title on the frame window.
*
* @param file_ null to use the current file name or !null to change the current file name as with
* a "Save As"
*/
public void setWorkingTitle(String file_)
{
if (file_ != null && file_.length() > 0)
saveFilename = file_;
this.setTitle(PropertyAccessor.getProperty("siw.title") + " - " + saveFilename + " - " + runMode.getTitleName());
}
private void jbInit() {
this.getContentPane().setLayout(new BorderLayout());
this.setSize(new Dimension(830, 650));
this.setJMenuBar(mainMenuBar);
this.setIconImage(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("siw-logo3_2.gif")).getImage());
setWorkingTitle(null);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane1.setDividerLocation(160);
jSplitPane2.setDividerLocation(400);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane2.setOneTouchExpandable(true);
fileMenu.add(saveMenuItem);
fileMenu.add(saveAsMenuItem);
fileMenu.addSeparator();
fileMenu.add(findMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
mainMenuBar.add(fileMenu);
editMenu.add(findMenuItem);
editMenu.add(prefMenuItem);
mainMenuBar.add(editMenu);
applyMenuItem.setEnabled(false);
applyToAllMenuItem.setEnabled(false);
previewReuseMenuItem.setEnabled(false);
elementMenu.add(applyMenuItem);
elementMenu.add(applyToAllMenuItem);
// not in this release. re-add to get feature
// elementMenu.add(previewReuseMenuItem);
mainMenuBar.add(elementMenu);
if(runMode.equals(RunMode.Reviewer)) {
// runMenu.add(defaultsMenuItem);
runMenu.add(validateConceptsMenuItem);
mainMenuBar.add(runMenu);
}
if(runMode.equals(RunMode.Curator)) {
runMenu.add(validateConceptsMenuItem);
mainMenuBar.add(runMenu);
}
helpMenu.add(indexMenuItem);
helpMenu.addSeparator();
helpMenu.add(aboutMenuItem);
mainMenuBar.add(helpMenu);
errorPanel = new ErrorPanel(TreeBuilder.getInstance().getRootNode());
errorPanel.addPropertyChangeListener(this);
jTabbedPane1.addTab("Errors", errorPanel);
Icon closeIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("close-tab.gif"));
viewTabbedPane.setCloseIcons(closeIcon, closeIcon, closeIcon);
viewTabbedPane.addCloseableTabbedPaneListener(this);
jTabbedPane1.addTab("Log", logPanel);
jSplitPane2.add(jTabbedPane1, JSplitPane.BOTTOM);
jSplitPane2.add(viewTabbedPane, JSplitPane.TOP);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
navigationPanel = new NavigationPanel();
jSplitPane1.add(navigationPanel, JSplitPane.LEFT);
navigationPanel.addViewChangeListener(this);
this.getContentPane().add(jSplitPane1, BorderLayout.CENTER);
this.getContentPane().add(infoLabel, BorderLayout.SOUTH);
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
_this.exit();
}
});
defaultsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
UmlDefaultsPanel dp = new UmlDefaultsPanel(_this);
dp.show();
UIUtil.putToCenter(dp);
}
});
findMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
SearchDialog sd = new SearchDialog(_this);
UIUtil.putToCenter(sd);
sd.addSearchListener(navigationPanel);
sd.setVisible(true);
}
});
findMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
final PreferenceDialog pd = new PreferenceDialog(_this);
prefMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pd.updatePreferences();
UIUtil.putToCenter(pd);
pd.setVisible(true);
}
});
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
xmiWriter.setOutput(saveFilename);
try {
xmiWriter.write(ElementsLists.getInstance());
infoLabel.setText("File Saved");
} catch (Throwable e){
JOptionPane.showMessageDialog(_this, "There was an error saving your File. Please contact support.", "Error Saving File", JOptionPane.ERROR_MESSAGE);
infoLabel.setText("Save Failed!!");
logger.error(e);
e.printStackTrace();
} // end of try-catch
}
});
saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String saveDir = UserPreferences.getInstance().getRecentDir();
JFileChooser chooser = new JFileChooser(saveDir);
javax.swing.filechooser.FileFilter filter =
new javax.swing.filechooser.FileFilter() {
String fileExtension = "xmi";
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
return f.getName().endsWith("." + fileExtension);
}
public String getDescription() {
return fileExtension.toUpperCase() + " Files";
}
};
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String filePath = chooser.getSelectedFile().getAbsolutePath();
String fileExtension = "xmi";
if(!filePath.endsWith(fileExtension))
filePath = filePath + "." + fileExtension;
UserPreferences.getInstance().setRecentDir(filePath);
xmiWriter.setOutput(filePath);
setWorkingTitle(filePath);
try {
xmiWriter.write(ElementsLists.getInstance());
infoLabel.setText("File Saved");
} catch (Throwable e){
JOptionPane.showMessageDialog(_this, "There was an error saving your File. Please contact support.", "Error Saving File", JOptionPane.ERROR_MESSAGE);
infoLabel.setText("Save Failed!!");
} // end of try-catch
}
}
});
validateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
ValidationItems.getInstance().clear();
Validator validator = new UMLValidator();
validator.validate();
ElementsLists elements = ElementsLists.getInstance();
TreeBuilder tb = TreeBuilder.getInstance();
tb.init();
tb.buildTree(elements);
errorPanel.update(tb.getRootNode());
}
});
validateConceptsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int n = JOptionPane.showConfirmDialog(_this,
"This process may take some time. Would you like to continue? ",
"Validate Concepts", JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION) {
ValidateConceptsDialog vcd = new ValidateConceptsDialog(_this);
vcd.addSearchListener(navigationPanel);
vcd.setVisible(true);
}
}
});
applyMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UMLElementViewPanel viewPanel =
(UMLElementViewPanel)viewTabbedPane
.getSelectedComponent();
try {
viewPanel.apply(false);
} catch (ApplyException e){
infoLabel.setText("Changes were not applied!");
} // end of try-catch
}
});
applyToAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UMLElementViewPanel viewPanel =
(UMLElementViewPanel)viewTabbedPane
.getSelectedComponent();
try {
viewPanel.apply(true);
} catch (ApplyException e){
infoLabel.setText("Changes were not applied!");
} // end of try-catch
}
});
previewReuseMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UMLElementViewPanel viewPanel =
(UMLElementViewPanel)viewTabbedPane
.getSelectedComponent();
// update dialog with current node
reuseDialog.init(viewPanel.getConceptEditorPanel().getNode());
UIUtil.putToCenter(reuseDialog);
reuseDialog.setVisible(true);
}
});
previewReuseMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
new AboutPanel();
}
});
indexMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String errMsg = "Error attempting to launch web browser";
String osName = System.getProperty("os.name");
String url = "http://gforge.nci.nih.gov/projects/siw/";
try {
if (osName.startsWith("Mac OS")) {
Class fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class[] {String.class});
openURL.invoke(null, new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String[] browsers = {
"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(
new String[] {"which", browsers[count]}).waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception("Could not find web browser");
else
Runtime.getRuntime().exec(new String[] {browser, url});
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, errMsg + ":\n" + e.getLocalizedMessage());
}
}
});
}
public void viewChanged(ViewChangeEvent event) {
previewReuseMenuItem.setEnabled(false);
if(event.getType() == ViewChangeEvent.VIEW_CONCEPTS
|| event.getType() == ViewChangeEvent.VIEW_VALUE_MEANING
|| event.getType() == ViewChangeEvent.VIEW_INHERITED) {
UMLNode node = (UMLNode)event.getViewObject();
// If concept is already showing, just bring it up front
if(viewPanels.containsKey(node.getFullPath())) {
NodeViewPanel pa = viewPanels.get(node.getFullPath());
viewTabbedPane.setSelectedComponent((JPanel)pa);
return;
}
if (node instanceof AttributeNode) {
DataElement de = (DataElement)node.getUserObject();
if (StringUtil.isEmpty(de.getPublicId())) {
previewReuseMenuItem.setEnabled(true);
}
}
// if we ask for new tab, or no tab yet, or it's an assoc or a VD.
// then open a new tab.
if((event.getInNewTab() == true) || (viewPanels.size() == 0)
|| viewTabbedPane.getSelectedComponent() instanceof AssociationViewPanel
|| viewTabbedPane.getSelectedComponent() instanceof ValueDomainViewPanel) {
newTab(event, node);
} else { // if not, update current tab.
NodeViewPanel viewPanel = (NodeViewPanel)
viewTabbedPane.getSelectedComponent();
viewTabbedPane.remove(viewTabbedPane.getSelectedIndex());
viewPanels.remove(viewPanel.getName());
newTab(event, node);
}
} else if(event.getType() == ViewChangeEvent.VIEW_ASSOCIATION) {
UMLNode node = (UMLNode)event.getViewObject();
if(associationViewPanel == null) {
associationViewPanel = new AssociationViewPanel(node);
associationViewPanel.addPropertyChangeListener(this);
associationViewPanel.addReviewListener(navigationPanel);
associationViewPanel.addReviewListener(ownerTracker);
associationViewPanel.addReviewListener(curatorTracker);
associationViewPanel.addElementChangeListener(ChangeTracker.getInstance());
associationViewPanel.addNavigationListener(navigationPanel);
navigationPanel.addNavigationListener(associationViewPanel);
viewTabbedPane.addTab("Association", associationViewPanel);
associationViewPanel.setName("Association");
infoLabel.setText("Association");
associationViewPanel.addCustomPropertyChangeListener(this);
} else
associationViewPanel.update(node);
viewTabbedPane.setSelectedComponent(associationViewPanel);
}
else if(event.getType() == ViewChangeEvent.VIEW_VALUE_DOMAIN) {
UMLNode node = (UMLNode)event.getViewObject();
if(vdViewPanel == null) {
vdViewPanel = new ValueDomainViewPanel((ValueDomain)node.getUserObject());
viewTabbedPane.addTab("ValueDomain", vdViewPanel);
vdViewPanel.setName("ValueDomain");
infoLabel.setText("ValueDomain");
}
else
vdViewPanel.update((ValueDomain)node.getUserObject());
viewTabbedPane.setSelectedComponent(vdViewPanel);
}
}
private void newTab(ViewChangeEvent event, UMLNode node) {
String tabTitle = node.getDisplay();
if(node instanceof AttributeNode) {
if(event.getType() == ViewChangeEvent.VIEW_INHERITED)
tabTitle = node.getParent().getParent().getDisplay()
+ "." + tabTitle;
else
tabTitle = node.getParent().getDisplay()
+ "." + tabTitle;
}
NodeViewPanel viewPanel = null;
if(event.getType() == ViewChangeEvent.VIEW_INHERITED) {
viewPanel = new InheritedAttributeViewPanel(node);
} else {
viewPanel = new UMLElementViewPanel(node);
}
viewPanel.addPropertyChangeListener(this);
viewPanel.addReviewListener(navigationPanel);
viewPanel.addReviewListener(ownerTracker);
viewPanel.addReviewListener(curatorTracker);
viewPanel.addElementChangeListener(ChangeTracker.getInstance());
viewPanel.addNavigationListener(navigationPanel);
navigationPanel.addNavigationListener(viewPanel);
viewTabbedPane.addTab(tabTitle, (JPanel)viewPanel);
viewTabbedPane.setSelectedComponent((JPanel)viewPanel);
viewPanel.setName(node.getFullPath());
viewPanels.put(viewPanel.getName(), viewPanel);
infoLabel.setText(tabTitle);
}
public boolean closeTab(int index) {
Component c = viewTabbedPane.getComponentAt(index);
if(c.equals(associationViewPanel))
associationViewPanel = null;
if(c.equals(vdViewPanel))
vdViewPanel = null;
viewPanels.remove(c.getName());
return true;
}
public void setXmiWriter(ElementWriter writer) {
this.xmiWriter = writer;
}
public void setLogTab(JPanel panel) {
this.logPanel = panel;
}
}
|
// $Id: ResourceBundle.java,v 1.27 2004/06/19 08:09:33 mdb Exp $
package com.threerings.resource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import com.samskivert.io.NestableIOException;
import com.samskivert.io.StreamUtil;
import com.samskivert.util.FileUtil;
import com.samskivert.util.StringUtil;
import org.apache.commons.io.StreamUtils;
/**
* A resource bundle provides access to the resources in a jar file.
*/
public class ResourceBundle
{
/**
* Constructs a resource bundle with the supplied jar file.
*
* @param source a file object that references our source jar file.
*/
public ResourceBundle (File source)
{
this(source, false, false);
}
/**
* Constructs a resource bundle with the supplied jar file.
*
* @param source a file object that references our source jar file.
* @param delay if true, the bundle will wait until someone calls
* {@link #sourceIsReady} before allowing access to its resources.
* @param unpack if true the bundle will unpack itself into a
* temporary directory
*/
public ResourceBundle (File source, boolean delay, boolean unpack)
{
_source = source;
if (unpack) {
String root = ResourceManager.unversionPath(
source.getPath(), ".jar");
root = stripSuffix(root);
_unpacked = new File(root + ".stamp");
_cache = new File(root);
}
if (!delay) {
sourceIsReady();
}
}
/**
* Returns the {@link File} from which resources are fetched for this
* bundle.
*/
public File getSource ()
{
return _source;
}
/**
* @return true if the bundle is fully downloaded and successfully
* unpacked.
*/
public boolean isUnpacked ()
{
return (_source.exists() && _unpacked != null &&
_unpacked.lastModified() == _source.lastModified());
}
/**
* Called by the resource manager once it has ensured that our
* resource jar file is up to date and ready for reading.
*
* @return true if we successfully unpacked our resources, false if we
* encountered errors in doing so.
*/
public boolean sourceIsReady ()
{
// make a note of our source's last modification time
_sourceLastMod = _source.lastModified();
// if we are unpacking files, the time to do so is now
if (_unpacked != null && _unpacked.lastModified() != _sourceLastMod) {
try {
resolveJarFile();
} catch (IOException ioe) {
Log.warning("Failure resolving jar file '" + _source +
"': " + ioe + ".");
wipeBundle();
return false;
}
Log.info("Unpacking into " + _cache + "...");
if (!_cache.exists()) {
if (!_cache.mkdir()) {
Log.warning("Failed to create bundle cache directory '" +
_cache + "'.");
closeJar();
// we are hopelessly fucked
return false;
}
} else {
FileUtil.recursiveClean(_cache);
}
Enumeration entries = _jarSource.entries();
while (entries.hasMoreElements()) {
JarEntry entry = (JarEntry)entries.nextElement();
File efile = new File(_cache, entry.getName());
// if we're unpacking a normal jar file, it will have
// special path entries that allow us to create our
// directories first
if (entry.isDirectory()) {
if (!efile.exists() && !efile.mkdir()) {
Log.warning("Failed to create bundle entry path '" +
efile + "'.");
}
continue;
}
// but some do not, so we want to ensure that our
// directories exist prior to getting down and funky
File parent = new File(efile.getParent());
if (!parent.exists() && !parent.mkdirs()) {
Log.warning("Failed to create bundle entry parent '" +
parent + "'.");
continue;
}
boolean failure = false;
BufferedOutputStream fout = null;
InputStream jin = null;
try {
fout = new BufferedOutputStream(
new FileOutputStream(efile));
jin = _jarSource.getInputStream(entry);
StreamUtils.pipe(jin, fout);
} catch (Exception e) {
Log.warning("Failure unpacking " + efile + ": " + e);
failure = true;
} finally {
StreamUtil.close(jin);
StreamUtil.close(fout);
}
// if something went awry, delete everything in the hopes
// that next time things will work
if (failure) {
wipeBundle();
return false;
}
}
// close the jar file now that it's all unpacked
closeJar();
// if everything unpacked smoothly, create our unpack stamp
try {
_unpacked.createNewFile();
if (!_unpacked.setLastModified(_sourceLastMod)) {
Log.warning("Failed to set last mod on stamp file '" +
_unpacked + "'.");
}
} catch (IOException ioe) {
Log.warning("Failure creating stamp file '" + _unpacked +
"': " + ioe + ".");
// no need to stick a fork in things at this point
}
}
return true;
}
/**
* Closes our (possibly opened) jar file.
*/
protected void closeJar ()
{
try {
if (_jarSource != null) {
_jarSource.close();
}
} catch (Exception ioe) {
Log.warning("Failed to close jar file [path=" + _source +
", error=" + ioe + "].");
}
}
/**
* Clears out everything associated with this resource bundle in the
* hopes that we can download it afresh and everything will work the
* next time around.
*/
protected void wipeBundle ()
{
// clear out our cache directory
if (_cache != null) {
FileUtil.recursiveClean(_cache);
}
// delete our unpack stamp file
if (_unpacked != null) {
_unpacked.delete();
}
// close and delete our source jar file
if (_source != null) {
closeJar();
_source.delete();
}
// also clear out any .vers file that the downloader might be
// maintaining if this is a versioned resource bundle
File vfile = new File(FileUtil.resuffix(_source, ".jar", ".vers"));
vfile.delete();
}
/**
* Fetches the named resource from this bundle. The path should be
* specified as a relative, platform independent path (forward
* slashes). For example <code>sounds/scream.au</code>.
*
* @param path the path to the resource in this jar file.
*
* @return an input stream from which the resource can be loaded or
* null if no such resource exists.
*
* @exception IOException thrown if an error occurs locating the
* resource in the jar file.
*/
public InputStream getResource (String path)
throws IOException
{
// unpack our resources into a temp directory so that we can load
// them quickly and the file system can cache them sensibly
File rfile = getResourceFile(path);
return (rfile == null) ? null : new FileInputStream(rfile);
}
/**
* Returns a file from which the specified resource can be loaded.
* This method will unpack the resource into a temporary directory and
* return a reference to that file.
*
* @param path the path to the resource in this jar file.
*
* @return a file from which the resource can be loaded or null if no
* such resource exists.
*/
public File getResourceFile (String path)
throws IOException
{
if (resolveJarFile()) {
return null;
}
// if we have been unpacked, return our unpacked file
if (_cache != null) {
File cfile = new File(_cache, path);
if (cfile.exists()) {
return cfile;
} else {
return null;
}
}
// otherwise, we unpack resources as needed into a temp directory
String tpath = StringUtil.md5hex(_source.getPath() + "%" + path);
File tfile = new File(getCacheDir(), tpath);
if (tfile.exists() && (tfile.lastModified() > _sourceLastMod)) {
return tfile;
}
JarEntry entry = _jarSource.getJarEntry(path);
if (entry == null) {
// Log.info("Couldn't locate " + path + " in " + _jarSource + ".");
return null;
}
// copy the resource into the temporary file
BufferedOutputStream fout =
new BufferedOutputStream(new FileOutputStream(tfile));
InputStream jin = _jarSource.getInputStream(entry);
StreamUtils.pipe(jin, fout);
jin.close();
fout.close();
return tfile;
}
/**
* Returns true if this resource bundle contains the resource with the
* specified path. This avoids actually loading the resource, in the
* event that the caller only cares to know that the resource exists.
*/
public boolean containsResource (String path)
{
try {
if (resolveJarFile()) {
return false;
}
return (_jarSource.getJarEntry(path) != null);
} catch (IOException ioe) {
return false;
}
}
/**
* Returns a string representation of this resource bundle.
*/
public String toString ()
{
try {
resolveJarFile();
return (_jarSource == null) ? "[file=" + _source + "]" :
"[path=" + _jarSource.getName() + "]";
} catch (IOException ioe) {
return "[file=" + _source + ", ioe=" + ioe + "]";
}
}
/**
* Creates the internal jar file reference if we've not already got
* it; we do this lazily so as to avoid any jar- or zip-file-related
* antics until and unless doing so is required, and because the
* resource manager would like to be able to create bundles before the
* associated files have been fully downloaded.
*
* @return true if the jar file could not yet be resolved because we
* haven't yet heard from the resource manager that it is ready for us
* to access, false if all is cool.
*/
protected boolean resolveJarFile ()
throws IOException
{
// if we don't yet have our resource bundle's last mod time, we
// have not yet been notified that it is ready
if (_sourceLastMod == -1) {
return true;
}
if (!_source.exists()) {
throw new IOException("Missing jar file for resource bundle: " +
_source + ".");
}
try {
if (_jarSource == null) {
_jarSource = new JarFile(_source);
}
return false;
} catch (IOException ioe) {
Log.warning("Failure reading jar file '" + _source + "'.");
Log.logStackTrace(ioe);
throw new NestableIOException(
"Failed to resolve resource bundle jar file '" +
_source + "'", ioe);
}
}
/**
* Returns the cache directory used for unpacked resources.
*/
public static File getCacheDir ()
{
if (_tmpdir == null) {
String tmpdir = System.getProperty("java.io.tmpdir");
if (tmpdir == null) {
Log.info("No system defined temp directory. Faking it.");
tmpdir = System.getProperty("user.home");
}
setCacheDir(new File(tmpdir, ".narcache"));
}
return _tmpdir;
}
/**
* Specifies the directory in which our temporary resource files
* should be stored.
*/
public static void setCacheDir (File tmpdir)
{
String rando = Long.toHexString((long)(Math.random() * Long.MAX_VALUE));
_tmpdir = new File(tmpdir, rando);
if (!_tmpdir.exists()) {
Log.info("Creating narya temp cache directory '" + _tmpdir + "'.");
_tmpdir.mkdirs();
}
// add a hook to blow away the temp directory when we exit
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run () {
Log.info("Clearing narya temp cache '" + _tmpdir + "'.");
FileUtil.recursiveDelete(_tmpdir);
}
});
}
/** Strips the .jar off of jar file paths. */
protected static String stripSuffix (String path)
{
if (path.endsWith(".jar")) {
return path.substring(0, path.length()-4);
} else {
// we have to change the path somehow
return path + "-cache";
}
}
/** The file from which we construct our jar file. */
protected File _source;
/** The last modified time of our source jar file. */
protected long _sourceLastMod = -1;
/** A file whose timestamp indicates whether or not our existing jar
* file has been unpacked. */
protected File _unpacked;
/** A directory into which we unpack files from our bundle. */
protected File _cache;
/** The jar file from which we load resources. */
protected JarFile _jarSource;
/** A directory in which we temporarily unpack our resource files. */
protected static File _tmpdir;
}
|
package org.jaxen.function;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
import org.jaxen.UnsupportedAxisException;
import org.jaxen.JaxenRuntimeException;
import java.util.List;
import java.util.Iterator;
/**
* <p><b>4.2</b> <code><i>string</i> string(<i>object</i>)</code>
*
* @author bob mcwhirter (bob @ werken.com)
*/
public class StringFunction implements Function
{
public Object call(Context context,
List args) throws FunctionCallException
{
int size = args.size();
if ( size == 0 )
{
return evaluate( context.getNodeSet(),
context.getNavigator() );
}
else if ( size == 1 )
{
return evaluate( args.get(0),
context.getNavigator() );
}
throw new FunctionCallException( "string() requires one argument." );
}
public static String evaluate(Object obj,
Navigator nav)
{
try
{
String retval = "";
if (obj == null) {
return "";
}
if (obj instanceof List)
{
List list = (List) obj;
if (list.isEmpty())
{
return "";
}
// do not recurse: only first list should unwrap
obj = list.get(0);
}
if (nav.isElement(obj) || nav.isDocument(obj))
{
Iterator descendantAxisIterator = nav.getDescendantAxisIterator(obj);
StringBuffer sb = new StringBuffer();
while (descendantAxisIterator.hasNext())
{
Object descendant = descendantAxisIterator.next();
if (nav.isText(descendant))
{
sb.append(nav.getTextStringValue(descendant));
}
}
retval = sb.toString();
}
else if (nav.isAttribute(obj))
{
retval = nav.getAttributeStringValue(obj);
}
else if (nav.isText(obj))
{
retval = nav.getTextStringValue(obj);
}
else if (nav.isProcessingInstruction(obj))
{
retval = nav.getProcessingInstructionData(obj);
}
else if (nav.isComment(obj))
{
retval = nav.getCommentStringValue(obj);
}
else if (nav.isNamespace(obj))
{
retval = nav.getNamespaceStringValue(obj);
}
else if (obj instanceof String)
{
retval = (String) obj;
}
else if (obj instanceof Boolean)
{
retval = stringValue(((Boolean) obj).booleanValue());
}
else if (obj instanceof Number)
{
retval = stringValue(((Number) obj).doubleValue());
}
retval = retval == null ? "" : retval;
return retval;
}
catch (UnsupportedAxisException e)
{
throw new JaxenRuntimeException(e);
}
}
public static String stringValue(double value)
{
if (Double.isNaN(value))
{
return "NaN";
}
if (-0.0 == value || 0.0 == value)
{
return "0";
}
if (Double.isInfinite(value) && value < 0)
{
return "-Infinity";
}
if (Double.isInfinite(value) && value > 0)
{
return "Infinity";
}
if (((long) value) == value)
{
return Long.toString((long) value);
}
return Double.toString(value);
}
public static String stringValue(boolean bool)
{
return bool ? "true" : "false";
}
}
|
package org.jdesktop.swingx.plaf;
import javax.swing.JComponent;
import javax.swing.plaf.PanelUI;
/**
*
* @author rbair
*/
public abstract class TitledPanelUI extends PanelUI {
/**
* Adds the given JComponent as a decoration on the right of the title
* @param decoration
*/
public abstract void addRightDecoration(JComponent decoration);
/**
* Adds the given JComponent as a decoration on the left of the title
* @param decoration
*/
public abstract void addLeftDecoration(JComponent decoration);
}
|
package org.jivesoftware.wildfire.net;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParser;
import java.io.IOException;
import java.io.Reader;
/**
* MXParser that returns an IGNORABLE_WHITESPACE event when a whitespace character or a
* line feed is received. This parser is useful when not validating documents.
*
* @author Gaston Dombiak
*/
public class MXParser extends org.xmlpull.mxp1.MXParser {
/**
* Last time a heartbeat was received. Hearbeats are represented as whitespaces
* or \n characters received when an XmlPullParser.END_TAG was parsed. Note that we
* can falsely detect heartbeats when parsing XHTML content but that is fine.
*/
private long lastHeartbeat = 0;
protected int nextImpl()
throws XmlPullParserException, IOException
{
text = null;
pcEnd = pcStart = 0;
usePC = false;
bufStart = posEnd;
if(pastEndTag) {
pastEndTag = false;
--depth;
namespaceEnd = elNamespaceCount[ depth ]; // less namespaces available
}
if(emptyElementTag) {
emptyElementTag = false;
pastEndTag = true;
return eventType = END_TAG;
}
// [1] document ::= prolog element Misc*
if(depth > 0) {
if(seenStartTag) {
seenStartTag = false;
return eventType = parseStartTag();
}
if(seenEndTag) {
seenEndTag = false;
return eventType = parseEndTag();
}
// ASSUMPTION: we are _on_ first character of content or markup!!!!
// [43] content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*
char ch;
if(seenMarkup) { // we have read ahead ...
seenMarkup = false;
ch = '<';
} else if(seenAmpersand) {
seenAmpersand = false;
ch = '&';
} else {
ch = more();
}
posStart = pos - 1; // VERY IMPORTANT: this is correct start of event!!!
// when true there is some potential event TEXT to return - keep gathering
boolean hadCharData = false;
// when true TEXT data is not continous (like <![CDATA[text]]>) and requires PC merging
boolean needsMerging = false;
MAIN_LOOP:
while(true) {
// work on MARKUP
if(ch == '<') {
if(hadCharData) {
//posEnd = pos - 1;
if(tokenize) {
seenMarkup = true;
return eventType = TEXT;
}
}
ch = more();
if(ch == '/') {
if(!tokenize && hadCharData) {
seenEndTag = true;
//posEnd = pos - 2;
return eventType = TEXT;
}
return eventType = parseEndTag();
} else if(ch == '!') {
ch = more();
if(ch == '-') {
// note: if(tokenize == false) posStart/End is NOT changed!!!!
parseComment();
if(tokenize) return eventType = COMMENT;
if( !usePC && hadCharData ) {
needsMerging = true;
} else {
posStart = pos; //completely ignore comment
}
} else if(ch == '[') {
//posEnd = pos - 3;
// must remeber previous posStart/End as it merges with content of CDATA
//int oldStart = posStart + bufAbsoluteStart;
//int oldEnd = posEnd + bufAbsoluteStart;
parseCDSect(hadCharData);
if(tokenize) return eventType = CDSECT;
final int cdStart = posStart;
final int cdEnd = posEnd;
final int cdLen = cdEnd - cdStart;
if(cdLen > 0) { // was there anything inside CDATA section?
hadCharData = true;
if(!usePC) {
needsMerging = true;
}
}
// posStart = oldStart;
// posEnd = oldEnd;
// if(cdLen > 0) { // was there anything inside CDATA section?
// if(hadCharData) {
// // do merging if there was anything in CDSect!!!!
// // if(!usePC) {
// // // posEnd is correct already!!!
// // if(posEnd > posStart) {
// // joinPC();
// // } else {
// // usePC = true;
// // pcStart = pcEnd = 0;
// // if(pcEnd + cdLen >= pc.length) ensurePC(pcEnd + cdLen);
// // // copy [cdStart..cdEnd) into PC
// // System.arraycopy(buf, cdStart, pc, pcEnd, cdLen);
// // pcEnd += cdLen;
// if(!usePC) {
// needsMerging = true;
// posStart = cdStart;
// posEnd = cdEnd;
// } else {
// if(!usePC) {
// needsMerging = true;
// posStart = cdStart;
// posEnd = cdEnd;
// hadCharData = true;
// //hadCharData = true;
// } else {
// if( !usePC && hadCharData ) {
// needsMerging = true;
} else {
throw new XmlPullParserException(
"unexpected character in markup "+printable(ch), this, null);
}
} else if(ch == '?') {
parsePI();
if(tokenize) return eventType = PROCESSING_INSTRUCTION;
if( !usePC && hadCharData ) {
needsMerging = true;
} else {
posStart = pos; //completely ignore PI
}
} else if( isNameStartChar(ch) ) {
if(!tokenize && hadCharData) {
seenStartTag = true;
//posEnd = pos - 2;
return eventType = TEXT;
}
return eventType = parseStartTag();
} else {
throw new XmlPullParserException(
"unexpected character in markup "+printable(ch), this, null);
}
// do content comapctation if it makes sense!!!!
} else if(ch == '&') {
// work on ENTITTY
//posEnd = pos - 1;
if(tokenize && hadCharData) {
seenAmpersand = true;
return eventType = TEXT;
}
final int oldStart = posStart + bufAbsoluteStart;
final int oldEnd = posEnd + bufAbsoluteStart;
final char[] resolvedEntity = parseEntityRef();
if(tokenize) return eventType = ENTITY_REF;
// check if replacement text can be resolved !!!
if(resolvedEntity == null) {
if(entityRefName == null) {
entityRefName = newString(buf, posStart, posEnd - posStart);
}
throw new XmlPullParserException(
"could not resolve entity named '"+printable(entityRefName)+"'",
this, null);
}
//int entStart = posStart;
//int entEnd = posEnd;
posStart = oldStart - bufAbsoluteStart;
posEnd = oldEnd - bufAbsoluteStart;
if(!usePC) {
if(hadCharData) {
joinPC(); // posEnd is already set correctly!!!
needsMerging = false;
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
// write into PC replacement text - do merge for replacement text!!!!
for (int i = 0; i < resolvedEntity.length; i++)
{
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = resolvedEntity[ i ];
}
hadCharData = true;
//assert needsMerging == false;
} else {
if(needsMerging) {
//assert usePC == false;
joinPC(); // posEnd is already set correctly!!!
//posStart = pos - 1;
needsMerging = false;
}
//no MARKUP not ENTITIES so work on character data ...
// [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
hadCharData = true;
boolean normalizedCR = false;
final boolean normalizeInput = tokenize == false || roundtripSupported == false;
// use loop locality here!!!!
boolean seenBracket = false;
boolean seenBracketBracket = false;
do {
// check that ]]> does not show in
if (eventType == XmlPullParser.END_TAG &&
(ch == ' ' || ch == '\n' || ch == '\t')) {
// ** ADDED CODE (INCLUDING IF STATEMENT)
lastHeartbeat = System.currentTimeMillis();;
}
if(ch == ']') {
if(seenBracket) {
seenBracketBracket = true;
} else {
seenBracket = true;
}
} else if(seenBracketBracket && ch == '>') {
throw new XmlPullParserException(
"characters ]]> are not allowed in content", this, null);
} else {
if(seenBracket) {
seenBracketBracket = seenBracket = false;
}
// assert seenTwoBrackets == seenBracket == false;
}
if(normalizeInput) {
// deal with normalization issues ...
if(ch == '\r') {
normalizedCR = true;
posEnd = pos -1;
// posEnd is alreadys set
if(!usePC) {
if(posEnd > posStart) {
joinPC();
} else {
usePC = true;
pcStart = pcEnd = 0;
}
}
//assert usePC == true;
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
} else if(ch == '\n') {
// if(!usePC) { joinPC(); } else { if(pcEnd >= pc.length) ensurePC(); }
if(!normalizedCR && usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = '\n';
}
normalizedCR = false;
} else {
if(usePC) {
if(pcEnd >= pc.length) ensurePC(pcEnd);
pc[pcEnd++] = ch;
}
normalizedCR = false;
}
}
ch = more();
} while(ch != '<' && ch != '&');
posEnd = pos - 1;
continue MAIN_LOOP; // skip ch = more() from below - we are alreayd ahead ...
}
ch = more();
} // endless while(true)
} else {
if(seenRoot) {
return parseEpilog();
} else {
return parseProlog();
}
}
}
/**
* Returns the last time a heartbeat was received. Hearbeats are represented as whitespaces
* or \n characters received when an XmlPullParser.END_TAG was parsed. Note that we
* can falsely detect heartbeats when parsing XHTML content but that is fine.
*
* @return the time in milliseconds when a heartbeat was received.
*/
public long getLastHeartbeat() {
return lastHeartbeat;
}
public void resetInput() {
Reader oldReader = reader;
String oldEncoding = inputEncoding;
reset();
reader = oldReader;
inputEncoding = oldEncoding;
}
}
|
package winstone.classLoader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import winstone.Logger;
import winstone.WinstoneResourceBundle;
/**
* Implements the servlet spec model (v2.3 section 9.7.2) for classloading, which
* is different to the standard JDK model in that it delegates *after* checking
* local repositories. This has the effect of isolating copies of classes that exist
* in 2 webapps from each other.
*
* Thanks to James Berry for the changes to use the system classloader to prevent
* loading servlet spec or system classpath classes again.
*
* @author <a href="mailto:rick_knowles@hotmail.com">Rick Knowles</a>
* @version $Id$
*/
public class WebappClassLoader extends URLClassLoader {
private static final WinstoneResourceBundle CL_RESOURCES = new WinstoneResourceBundle("winstone.classLoader.LocalStrings");
protected ClassLoader system = getSystemClassLoader();
public WebappClassLoader(URL[] urls) {
super(urls);
}
public WebappClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
public WebappClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(urls, parent, factory);
}
protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
// First, check if the class has already been loaded
Class c = findLoadedClass(name);
// Try the system loader first, to ensure that system classes are not
// overridden by webapps. Note that this includes any classes in winstone,
// including the javax.servlet classes
if (c == null) {
try {
c = system.loadClass(name);
if (c != null) {
Logger.log(Logger.MAX, CL_RESOURCES, "WebappClassLoader.LoadedBySystemCL", name);
}
} catch (ClassNotFoundException e) {
c = null;
}
}
// If an allowed class, load it locally first
if (c == null) {
try {
// If still not found, then invoke findClass in order to find the class.
c = findClass(name);
if (c != null) {
Logger.log(Logger.MAX, CL_RESOURCES, "WebappClassLoader.LoadedByThisCL", name);
}
} catch (ClassNotFoundException e) {
c = null;
}
}
// otherwise, and only if we have a parent, delegate to our parent
// Note that within winstone, the only difference between this and the system
// class loader we've already tried is that our parent might include the common/shared lib.
if (c == null) {
ClassLoader parent = getParent();
if (parent != null) {
c = parent.loadClass(name);
if (c != null) {
Logger.log(Logger.MAX, CL_RESOURCES, "WebappClassLoader.LoadedByParentCL", name);
}
} else {
// We have no other hope for loading the class, so throw the class not found exception
throw new ClassNotFoundException(name);
}
}
if (resolve && (c != null)) {
resolveClass(c);
}
return c;
}
public InputStream getResourceAsStream(String name) {
if ((name != null) && name.startsWith("/")) {
name = name.substring(1);
}
return super.getResourceAsStream(name);
}
}
|
package de.fzi.cjunit.runners;
import java.util.ArrayList;
import java.util.List;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import de.fzi.cjunit.ConcurrentTest;
import de.fzi.cjunit.runners.model.ConcurrentFrameworkMethod;
public class ConcurrentRunner extends BlockJUnit4ClassRunner {
List<FrameworkMethod> testMethods;
public ConcurrentRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected void collectInitializationErrors(List<Throwable> errors) {
super.collectInitializationErrors(errors);
validateConcurrentTestMethods(errors);
}
@Override
protected List<FrameworkMethod> computeTestMethods() {
if (testMethods == null) {
testMethods = new ArrayList<FrameworkMethod>(
super.computeTestMethods());
testMethods.addAll(computeConcurrentTestMethods());
}
return testMethods;
}
protected List<FrameworkMethod> computeConcurrentTestMethods() {
List<FrameworkMethod> methods
= getTestClass().getAnnotatedMethods(
ConcurrentTest.class);
List<FrameworkMethod> concurrentMethods
= new ArrayList<FrameworkMethod>();
for (FrameworkMethod eachMethod : methods) {
concurrentMethods.add(new ConcurrentFrameworkMethod(
eachMethod.getMethod()));
}
return concurrentMethods;
}
protected void validateConcurrentTestMethods(List<Throwable> errors) {
validatePublicVoidNoArgMethods(ConcurrentTest.class, false,
errors);
}
}
|
package br.uff.ic.provviewer.Input;
import br.uff.ic.utility.IO.BasePath;
import br.uff.ic.provviewer.EdgeType;
import br.uff.ic.provviewer.GraphFrame;
import br.uff.ic.provviewer.VariableNames;
import br.uff.ic.provviewer.Variables;
import br.uff.ic.provviewer.Vertex.ColorScheme.ColorScheme;
import br.uff.ic.provviewer.Vertex.ColorScheme.VertexColorScheme;
import br.uff.ic.provviewer.Vertex.ColorScheme.DefaultVertexColorScheme;
import br.uff.ic.provviewer.Vertex.ColorScheme.GraphVisualizationScheme;
import br.uff.ic.provviewer.Vertex.ColorScheme.ProvScheme;
import br.uff.ic.provviewer.Vertex.ColorScheme.VertexGraphGrayScaleScheme;
import br.uff.ic.utility.AttValueColor;
import br.uff.ic.utility.Utils;
import br.uff.ic.utility.graph.Edge;
import br.uff.ic.utility.graph.Vertex;
import java.awt.Color;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Class responsible for configuring the tool to a specific domain
*
* @author Kohwalter
*/
public class Config {
public int vertexSize = 40;
//Filter List
public List<EdgeType> edgetype = new ArrayList<>();
public List<String> vertexLabelFilter = new ArrayList<>();
//Modes
public Map<String, ColorScheme> vertexModes = new HashMap<>();
//Temporal Layout
public String layoutSpecialVertexType;
// Default Layout
public String defaultLayout = "Spatial";
// Coordinates Layout
public String layoutAxis_X;
public String layoutAxis_Y;
//BackGround for Coordinates Layout
public String imageLocation;
public double imageOffsetX;
public double imageOffsetY;
public boolean orthogonal = true;
public double googleZoomLevel;
public double spatialLayoutPosition;
public double coordinatesScale;
public double scale;
// public boolean showEntityDate;
// public boolean showEntityLabel;
public double width;
public double height;
public String timeScale = "";
public boolean considerEdgeLabelForMerge = false;
//Vertex Stroke variables
public List<String> vertexStrokevariables = new ArrayList<>();
//ActivityVertex
//All 3 arrays must have the same size
public List<AttValueColor> activityVC = new ArrayList<>();
public List<AttValueColor> entityVC = new ArrayList<>();
public List<AttValueColor> agentVC = new ArrayList<>();
/**
* Method to configure the tool for the first time using the default graph
* and configuration
*
* @param variables
*/
public void Initialize(Variables variables) {
System.out.println("Config: " + BasePath.getBasePathForClass(Config.class) + variables.configDemo);
File fXmlFile = new File(BasePath.getBasePathForClass(Config.class) + variables.configDemo);
Initialize(fXmlFile);
}
public void resetVertexModeInitializations() {
for (ColorScheme vm : vertexModes.values()) {
vm.resetInitialization();
}
}
/**
* Method to compute the graph scale for the Spatial Layout
*/
public void ComputeCoordScale() {
final ImageIcon icon = new ImageIcon(BasePath.getBasePathForClass(Config.class) + imageLocation);
width = icon.getIconWidth();
height = icon.getIconHeight();
if (width > 0) {
coordinatesScale = (width * 0.5);
coordinatesScale = coordinatesScale * 100;
if (spatialLayoutPosition != 0) {
coordinatesScale = coordinatesScale / spatialLayoutPosition;
}
coordinatesScale = coordinatesScale / 100;
} else {
coordinatesScale = -50;
}
}
public void DetectEdges(Collection<Edge> edges) {
Map<String, EdgeType> newEdges = new HashMap<>();
int colorCount = 0;
for (Edge edge : edges) {
boolean isNewType = true;
boolean isNewLabel = true;
for (EdgeType e : edgetype) {
if (edge.getType().equalsIgnoreCase(e.type)) {
isNewType = false;
}
if (edge.getLabel().equalsIgnoreCase(e.type)) {
isNewLabel = false;
}
}
if (isNewType) {
EdgeType newEdge = new EdgeType();
newEdge.type = edge.getType();
newEdge.stroke = "MAX";
newEdge.collapse = "SUM";
newEdge.edgeColor = Utils.getColor(colorCount);
colorCount++;
newEdges.put(newEdge.type, newEdge);
}
if (isNewLabel) {
EdgeType newEdge = new EdgeType();
newEdge.type = edge.getLabel();
newEdge.stroke = "MAX";
newEdge.collapse = "SUM";
newEdge.edgeColor = Utils.getColor(colorCount);
colorCount++;
newEdges.put(newEdge.type, newEdge);
}
}
edgetype.addAll(newEdges.values());
InterfaceEdgeFilters();
GraphFrame.edgeFilterList.setSelectedIndex(0);
}
public void detectGraphVisualizationModes(Collection<String> graphs) {
Map<String, ColorScheme> newGraphModes = new HashMap<>();
for(String g : graphs) {
if(!vertexModes.containsKey(g)) {
GraphVisualizationScheme graphMode = new GraphVisualizationScheme(g);
newGraphModes.put(g, graphMode);
}
}
vertexModes.putAll(newGraphModes);
InterfaceStatusFilters();
}
public void DetectVertexModes(Collection<Object> vertices) {
Map<String, String> attributeList = new HashMap<>();
Map<String, ColorScheme> newAttributes = new HashMap<>();
for (Object v : vertices) {
attributeList.putAll(((Vertex) v).attributeList());
}
for (String att : attributeList.values()) {
// boolean isNew = true;
if(!vertexModes.containsKey(att)) {
DefaultVertexColorScheme attMode = new DefaultVertexColorScheme(att);
newAttributes.put(att, attMode);
}
// for (ColorScheme color : vertexModes.values()) {
// if (att.equalsIgnoreCase(color.attribute) && color.restrictedAttribute == null) {
// isNew = false;
// if (isNew) {
// DefaultVertexColorScheme attMode = new DefaultVertexColorScheme(att);
// newAttributes.put(att, attMode);
}
vertexModes.putAll(newAttributes);//.addAll(newAttributes.values());
InterfaceStatusFilters();
}
// public void DetectVertexAttributeFilterValues(Collection<Object> vertices) {
// Map<String, String> valueList = new HashMap<>();
// Map<String, ColorScheme> newAttributes = new HashMap<>();
// for (Object v : vertices) {
// valueList.put(((Vertex) v).getAttributeValue(vertexAttributeFilter), ((Vertex) v).getAttributeValue(vertexAttributeFilter));
// vertexLabelFilter.addAll(valueList.values());
// InterfaceVertexFilters();
// GraphFrame.vertexFilterList.setSelectedIndex(0);
/**
* Method to configure the tool
*
* @param fXmlFile is the xml file that contains the configuration for the
* tool
*/
public void Initialize(File fXmlFile) {
try {
edgetype = new ArrayList<>();
vertexLabelFilter = new ArrayList<>();
vertexModes = new HashMap<>();
layoutSpecialVertexType = "";
scale = 1.0;
vertexStrokevariables = new ArrayList<>();
activityVC = new ArrayList<>();
entityVC = new ArrayList<>();
agentVC = new ArrayList<>();
EdgeType allEdges = new EdgeType();
allEdges.type = VariableNames.FilterAllEdges;
allEdges.stroke = "MAX";
allEdges.collapse = "SUM";
edgetype.add(allEdges);
EdgeType chronological = new EdgeType();
chronological.type = VariableNames.ChronologicalEdge;
chronological.stroke = "MAX";
chronological.collapse = "SUM";
edgetype.add(chronological);
String allvertices = VariableNames.FilterAllVertices;
vertexLabelFilter.add(allvertices);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("vertexSize");
if (nList != null && nList.getLength() > 0 && !nList.item(0).getTextContent().equalsIgnoreCase("")) {
vertexSize = Integer.parseInt(nList.item(0).getTextContent());
}
nList = doc.getElementsByTagName("timeScale");
if (nList != null && nList.getLength() > 0) {
timeScale = nList.item(0).getTextContent().toLowerCase();
}
nList = doc.getElementsByTagName("default_layout");
if (nList.item(0) != null) {
defaultLayout = nList.item(0).getTextContent();
}
nList = doc.getElementsByTagName("considerEdgeLabelForMerge");
if (nList.item(0) != null) {
considerEdgeLabelForMerge = Boolean.parseBoolean(nList.item(0).getTextContent());
}
// Temporal Layout parameters
nList = doc.getElementsByTagName("temporalLayoutbackbone");
layoutSpecialVertexType = nList.item(0).getTextContent();
nList = doc.getElementsByTagName("temporalLayoutscale");
if (nList.item(0).getTextContent().equals("")) {
scale = 1;
} else {
scale = Double.parseDouble(nList.item(0).getTextContent());
}
// To avoid empty backbone
if (layoutSpecialVertexType.equalsIgnoreCase("")) {
layoutSpecialVertexType = "Default";
}
// Spatial Layout parameters
nList = doc.getElementsByTagName("layoutAxis_X");
layoutAxis_X = nList.item(0).getTextContent();
nList = doc.getElementsByTagName("layoutAxis_Y");
layoutAxis_Y = nList.item(0).getTextContent();
nList = doc.getElementsByTagName("imageLocation");
imageLocation = nList.item(0).getTextContent();
nList = doc.getElementsByTagName("imageOffset_X");
if (nList.item(0).getTextContent().equals("")) {
imageOffsetX = 0;
} else {
imageOffsetX = Double.parseDouble(nList.item(0).getTextContent());
}
nList = doc.getElementsByTagName("imageOffset_Y");
if (nList.item(0).getTextContent().equals("")) {
imageOffsetY = 0;
} else {
imageOffsetY = Double.parseDouble(nList.item(0).getTextContent());
}
nList = doc.getElementsByTagName("spatialLayoutPosition");
if (nList.item(0).getTextContent().equals("")) {
spatialLayoutPosition = 0;
} else {
spatialLayoutPosition = Double.parseDouble(nList.item(0).getTextContent());
}
nList = doc.getElementsByTagName("zoomLevel");
if (nList.item(0).getTextContent().equals("")) {
googleZoomLevel = 0;
} else {
googleZoomLevel = Double.parseDouble(nList.item(0).getTextContent());
}
if (googleZoomLevel != 0) {
orthogonal = false;
}
ComputeCoordScale();
//Edge Types
nList = doc.getElementsByTagName("edgetype");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
EdgeType etype = new EdgeType();
etype.type = eElement.getElementsByTagName("edge").item(0).getTextContent();
etype.stroke = eElement.getElementsByTagName("edgestroke").item(0).getTextContent();
etype.collapse = eElement.getElementsByTagName("collapsefunction").item(0).getTextContent();
if (eElement.getElementsByTagName("isInverted") != null && eElement.getElementsByTagName("isInverted").getLength() > 0) {
if (!eElement.getElementsByTagName("isInverted").item(0).getTextContent().isEmpty()) {
etype.isInverted = Boolean.parseBoolean(eElement.getElementsByTagName("isInverted").item(0).getTextContent());
}
}
Color color;
if (eElement.getElementsByTagName("r").item(0) != null) {
int r = Integer.parseInt(eElement.getElementsByTagName("r").item(0).getTextContent());
int g = Integer.parseInt(eElement.getElementsByTagName("g").item(0).getTextContent());
int b = Integer.parseInt(eElement.getElementsByTagName("b").item(0).getTextContent());
color = new Color(r, g, b);
} else {
color = new Color(0, 0, 0);
}
etype.edgeColor = color;
edgetype.add(etype);
}
}
//Vertex Label Filters
nList = doc.getElementsByTagName("vertexAttributeFilter");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String vertexFilter = new String();
if(eElement.getElementsByTagName("logic").item(0) != null) {
if("".equals(eElement.getElementsByTagName("logic").item(0).getTextContent()) && !"".equals(eElement.getElementsByTagName("value").item(0).getTextContent()))
vertexFilter = "(EQ";
else if("".equals(eElement.getElementsByTagName("logic").item(0).getTextContent()))
vertexFilter = "(C";
else
vertexFilter = "(" + eElement.getElementsByTagName("logic").item(0).getTextContent();
} else
vertexFilter = "(EQ";
vertexFilter += ") ";
vertexFilter += eElement.getElementsByTagName("name").item(0).getTextContent();
vertexFilter += ": ";
vertexFilter += eElement.getElementsByTagName("value").item(0).getTextContent();
vertexLabelFilter.add(vertexFilter);
}
}
//Vertex Stroke Types
nList = doc.getElementsByTagName("vertexstroke");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String list = "";
if (!eElement.getElementsByTagName("attribute").item(0).getTextContent().isEmpty()) {
list = eElement.getElementsByTagName("attribute").item(0).getTextContent();
list += " " + eElement.getElementsByTagName("values").item(0).getTextContent();
}
vertexStrokevariables.add(list);
}
}
//Vertex Color Schemes
//Default mode is always set, no matter the config.xml
ProvScheme provScheme = new ProvScheme("Prov");
vertexModes.put("Prov", provScheme);
VertexGraphGrayScaleScheme graphScheme = new VertexGraphGrayScaleScheme(VariableNames.GraphFile);
vertexModes.put(VariableNames.GraphFile, graphScheme);
nList = doc.getElementsByTagName("colorscheme");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String attribute = eElement.getElementsByTagName("attribute").item(0).getTextContent();
boolean isInverted = false;
boolean isZeroWhite = false;
String values = "empty";
String maxvalue = null;
String minvalue = null;
String restrictedAttribute = null;
String restrictedValue = null;
boolean limited = false;
boolean restricted = false;
if (eElement.getElementsByTagName("trafficLightType") != null && eElement.getElementsByTagName("trafficLightType").getLength() > 0) {
if (!eElement.getElementsByTagName("trafficLightType").item(0).getTextContent().isEmpty()) {
if (eElement.getElementsByTagName("trafficLightType").item(0).getTextContent().equalsIgnoreCase("type2")) {
isZeroWhite = true;
}
}
}
if (eElement.getElementsByTagName("isInverted") != null && eElement.getElementsByTagName("isInverted").getLength() > 0) {
if (!eElement.getElementsByTagName("isInverted").item(0).getTextContent().isEmpty()) {
isInverted = Boolean.parseBoolean(eElement.getElementsByTagName("isInverted").item(0).getTextContent());
}
}
if (eElement.getElementsByTagName("values") != null && eElement.getElementsByTagName("values").getLength() > 0) {
if (!eElement.getElementsByTagName("values").item(0).getTextContent().isEmpty()) {
values = eElement.getElementsByTagName("values").item(0).getTextContent();
}
}
NodeList goodattribute = eElement.getElementsByTagName("goodvalue");
if (goodattribute != null && goodattribute.getLength() > 0) {
if (!eElement.getElementsByTagName("goodvalue").item(0).getTextContent().isEmpty()) {
maxvalue = eElement.getElementsByTagName("goodvalue").item(0).getTextContent();
limited = true;
}
}
NodeList badattribute = eElement.getElementsByTagName("badvalue");
if (badattribute != null && badattribute.getLength() > 0) {
if (!eElement.getElementsByTagName("badvalue").item(0).getTextContent().isEmpty()) {
minvalue = eElement.getElementsByTagName("badvalue").item(0).getTextContent();
limited = true;
}
}
NodeList restrictedAtt = eElement.getElementsByTagName("restrictedAttribute");
if (restrictedAtt != null && restrictedAtt.getLength() > 0) {
if (!eElement.getElementsByTagName("restrictedAttribute").item(0).getTextContent().isEmpty()) {
restrictedAttribute = eElement.getElementsByTagName("restrictedAttribute").item(0).getTextContent();
restricted = true;
}
}
NodeList restrictedVal = eElement.getElementsByTagName("restrictedValue");
if (restrictedVal != null && restrictedVal.getLength() > 0) {
if (!eElement.getElementsByTagName("restrictedValue").item(0).getTextContent().isEmpty()) {
restrictedValue = eElement.getElementsByTagName("restrictedValue").item(0).getTextContent();
restricted = true;
}
}
Class cl = Class.forName("br.uff.ic.provviewer.Vertex.ColorScheme." + eElement.getElementsByTagName("class").item(0).getTextContent());
if (restricted) {
Constructor con = cl.getConstructor(boolean.class, boolean.class, String.class, String.class, String.class, String.class, boolean.class, String.class, String.class);
ColorScheme attMode = (ColorScheme) con.newInstance(isZeroWhite, isInverted, attribute, values, maxvalue, minvalue, limited, restrictedAttribute, restrictedValue);
vertexModes.put(attribute + "(" + restrictedValue + ")", attMode);
} else {
Constructor con = cl.getConstructor(boolean.class, boolean.class, String.class, String.class, String.class, String.class, boolean.class);
ColorScheme attMode = (ColorScheme) con.newInstance(isZeroWhite, isInverted, attribute, values, maxvalue, minvalue, limited);
vertexModes.put(attribute, attMode);
}
}
}
VertexColorScheme vertexColorScheme;
nList = doc.getElementsByTagName("vertexcolor");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
activityVC = new ArrayList<>();
entityVC = new ArrayList<>();
agentVC = new ArrayList<>();
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) nNode;
NodeList innerList;
String generalname = e.getElementsByTagName("generalname").item(0).getTextContent();
String isAutomatic = e.getElementsByTagName("isAutomatic").item(0).getTextContent();
//Activity Variables
innerList = e.getElementsByTagName("activitycolor");
for (int j = 0; j < innerList.getLength(); j++) {
Node innerNode = innerList.item(j);
if (innerNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) innerNode;
AttValueColor avc = new AttValueColor();
avc.name = eElement.getElementsByTagName("attribute").item(0).getTextContent();
if(eElement.getElementsByTagName("value").getLength() > 0 && eElement.getElementsByTagName("value").item(0).getTextContent() != "") {
avc.value = eElement.getElementsByTagName("value").item(0).getTextContent();
int r = Integer.parseInt(eElement.getElementsByTagName("r").item(0).getTextContent());
int g = Integer.parseInt(eElement.getElementsByTagName("g").item(0).getTextContent());
int b = Integer.parseInt(eElement.getElementsByTagName("b").item(0).getTextContent());
avc.color = new Color(r, g, b);
}
activityVC.add(avc);
}
}
//Entity Variables
innerList = e.getElementsByTagName("entitycolor");
for (int j = 0; j < innerList.getLength(); j++) {
Node innerNode = innerList.item(j);
if (innerNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) innerNode;
AttValueColor avc = new AttValueColor();
avc.name = eElement.getElementsByTagName("attribute").item(0).getTextContent();
if(eElement.getElementsByTagName("value").getLength() > 0 && eElement.getElementsByTagName("value").item(0).getTextContent() != "") {
avc.value = eElement.getElementsByTagName("value").item(0).getTextContent();
int r = Integer.parseInt(eElement.getElementsByTagName("r").item(0).getTextContent());
int g = Integer.parseInt(eElement.getElementsByTagName("g").item(0).getTextContent());
int b = Integer.parseInt(eElement.getElementsByTagName("b").item(0).getTextContent());
avc.color = new Color(r, g, b);
}
entityVC.add(avc);
}
}
//Agent Variables
innerList = e.getElementsByTagName("agentcolor");
for (int j = 0; j < innerList.getLength(); j++) {
Node innerNode = innerList.item(j);
if (innerNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) innerNode;
AttValueColor avc = new AttValueColor();
avc.name = eElement.getElementsByTagName("attribute").item(0).getTextContent();
if(eElement.getElementsByTagName("value").getLength() > 0 && eElement.getElementsByTagName("value").item(0).getTextContent() != "") {
avc.value = eElement.getElementsByTagName("value").item(0).getTextContent();
int r = Integer.parseInt(eElement.getElementsByTagName("r").item(0).getTextContent());
int g = Integer.parseInt(eElement.getElementsByTagName("g").item(0).getTextContent());
int b = Integer.parseInt(eElement.getElementsByTagName("b").item(0).getTextContent());
avc.color = new Color(r, g, b);
}
agentVC.add(avc);
}
}
vertexColorScheme = new VertexColorScheme(generalname,activityVC ,entityVC, agentVC, Boolean.parseBoolean(isAutomatic));
vertexModes.put(generalname, vertexColorScheme);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//Initialize Interface Filters
InterfaceEdgeFilters();
InterfaceVertexFilters();
InterfaceStatusFilters();
}
/**
* Function to update the edge list in the GraphFrame interface
*/
private void InterfaceEdgeFilters() {
//Initialize Interface Filters
String[] types = new String[edgetype.size()];
for (int x = 0; x < types.length; x++) {
types[x] = edgetype.get(x).type;
}
GraphFrame.edgeFilterList.setListData(types);
}
/**
* Function to update the vertex filter list in the GraphFrame interface
*/
private void InterfaceVertexFilters() {
//Initialize Interface Filters
String[] types = new String[vertexLabelFilter.size()];
for (int i = 0; i < types.length; i++) {
types[i] = vertexLabelFilter.get(i);
}
GraphFrame.vertexFilterList.setListData(types);
}
/**
* Function to update the status filter list in the GraphFrame interface
*/
private void InterfaceStatusFilters() {
String[] items = new String[vertexModes.size()];
int j = 0;
for (ColorScheme mode : vertexModes.values()) {
items[j] = mode.GetName();
j++;
}
GraphFrame.StatusFilterBox.setModel(
new DefaultComboBoxModel(items));
}
/**
* Method to automatically add the GraphFile filter in the Vertex Filters menu
* @param graphNames is the list of GraphFile names
*/
public void addGraphFileVertexFilter(Collection<String> graphNames) {
String[] types = new String[vertexLabelFilter.size() + (graphNames.size() * 4)];
for (int i = 0; i < vertexLabelFilter.size(); i++) {
types[i] = vertexLabelFilter.get(i);
}
int i = vertexLabelFilter.size();
for (String s : graphNames) {
types[i] = "(EQ) "+ VariableNames.GraphFile + ": " + s;
i++;
types[i] = "(NE) "+ VariableNames.GraphFile + ": " + s;
i++;
types[i] = "(C) "+ VariableNames.GraphFile + ": " + s;
i++;
types[i] = "(NC) "+ VariableNames.GraphFile + ": " + s;
i++;
}
GraphFrame.vertexFilterList.setListData(types);
}
}
|
package ch.tkuhn.memetools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.supercsv.io.CsvListReader;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
public class PrepareApsData {
@Parameter(names = "-v", description = "Write detailed log")
private boolean verbose = false;
@Parameter(names = "-t", description = "File with terms")
private File termsFile;
@Parameter(names = "-tcol", description = "Index or name of column to read terms (if term file is in CSV format)")
private String termCol = "TERM";
@Parameter(names = "-c", description = "Only use first c terms")
private int termCount = -1;
@Parameter(names = "-sg", description = "Skip GML file generation")
private boolean skipGml = false;
@Parameter(names = "-sd", description = "Skip data file generation")
private boolean skipData = false;
@Parameter(names = "-sdt", description = "Skip generation of title-only data file")
private boolean skipDataT = false;
@Parameter(names = "-sdta", description = "Skip generation of title+abstract data file")
private boolean skipDataTA = false;
@Parameter(names = "-r", description = "Randomize graph (for baseline analysis)")
private boolean randomize = false;
@Parameter(names = "-rw", description = "Randomize graph within time window (keeping time structure mostly intact)")
private int randomizeTimeWindow = 0;
@Parameter(names = "-rs", description = "Seed for randomization")
private Long randomSeed;
private File logFile;
public static final void main(String[] args) {
PrepareApsData obj = new PrepareApsData();
JCommander jc = new JCommander(obj);
try {
jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
obj.run();
}
private static String metadataFolder = "aps-dataset-metadata";
private static String abstractFolder = "aps-abstracts";
private static String citationFile = "aps-dataset-citations/citing_cited.csv";
private Map<String,String> titles;
private Map<String,String> dates;
private Map<String,String> abstracts;
private Map<String,List<String>> references;
private Map<String,String> randomizedDois;
private Random random;
private List<String> terms;
private Set<FileVisitOption> walkFileTreeOptions;
public PrepareApsData() {
}
public void run() {
init();
try {
processMetadataDir();
processAbstractDir();
processCitationFile();
readTerms();
writeDataFiles();
writeGmlFile();
} catch (Throwable th) {
log(th);
System.exit(1);
}
log("Finished");
}
private void init() {
logFile = new File(MemeUtils.getLogDir(), "prepare-aps.log");
log("==========");
log("Starting...");
titles = new HashMap<String,String>();
dates = new HashMap<String,String>();
abstracts = new HashMap<String,String>();
references = new HashMap<String,List<String>>();
terms = null;
walkFileTreeOptions = new HashSet<FileVisitOption>();
walkFileTreeOptions.add(FileVisitOption.FOLLOW_LINKS);
if (randomizeTimeWindow > 0) {
randomize = true;
}
if (randomize) {
randomizedDois = new HashMap<String,String>();
if (randomSeed == null) {
random = new Random();
} else {
random = new Random(randomSeed);
}
}
}
private void processMetadataDir() throws IOException {
log("Reading metadata...");
File metadataDir = new File(MemeUtils.getRawDataDir(), metadataFolder);
Files.walkFileTree(metadataDir.toPath(), walkFileTreeOptions, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (path.toString().endsWith(".xml")) {
processMetadataFile(path);
}
return FileVisitResult.CONTINUE;
}
});
log("Number of documents: " + titles.size());
}
private void processMetadataFile(Path path) {
log("Reading metadata file: " + path);
try {
BufferedReader r = new BufferedReader(new FileReader(path.toFile()));
int errors = 0;
String doi = null;
String date = null;
String line;
while ((line = r.readLine()) != null) {
line = line.trim();
if (line.matches(".*doi=\".*\".*")) {
String newDoi = line.replaceFirst("^.*doi=\"([^\"]*)\".*$", "$1");
if (doi != null && !doi.equals(newDoi)) {
logDetail("ERROR. Two DOI values found for same entry");
errors++;
}
doi = newDoi;
}
if (line.matches(".*<issue printdate=\"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\".*")) {
String newDate = line.replaceFirst("^.*<issue printdate=\"([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9])\".*$", "$1");
if (date != null && !date.equals(newDate)) {
logDetail("ERROR. Two year values found for same entry");
errors++;
}
date = newDate;
}
if (line.matches(".*<title>.*</title>.*")) {
String title = line.replaceFirst("^.*<title>(.*)</title>.*$", "$1");
if (doi == null) {
logDetail("ERROR. No DOI found for title: " + title);
errors++;
continue;
}
if (date == null) {
logDetail("ERROR. No publishing date found for title: " + title);
errors++;
continue;
}
title = MemeUtils.normalize(title);
if (!titles.containsKey(doi)) {
titles.put(doi, title);
dates.put(doi, date);
// initialize also references table:
references.put(doi, new ArrayList<String>());
} else {
logDetail("ERROR. Duplicate DOI: " + doi);
errors++;
}
doi = null;
date = null;
}
}
r.close();
log("Number of errors: " + errors);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void processAbstractDir() throws IOException {
log("Reading abstracts...");
File abstractDir = new File(MemeUtils.getRawDataDir(), abstractFolder);
Files.walkFileTree(abstractDir.toPath(), walkFileTreeOptions, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (path.toString().endsWith(".txt")) {
processAbstractFile(path);
}
return FileVisitResult.CONTINUE;
}
});
}
private void processAbstractFile(Path path) {
try {
BufferedReader br = new BufferedReader(new FileReader(path.toFile()));
String doi = "10.1103/" + path.getFileName().toString().replaceFirst(".txt$", "");
String text = "";
String line;
while ((line = br.readLine()) != null) {
text += line.trim() + " ";
}
abstracts.put(doi, MemeUtils.normalize(text));
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void processCitationFile() throws IOException {
log("Reading citations...");
File file = new File(MemeUtils.getRawDataDir(), citationFile);
BufferedReader r = new BufferedReader(new FileReader(file));
String line;
int invalid = 0;
int missing = 0;
int linecount = 0;
while ((line = r.readLine()) != null) {
linecount++;
if (linecount == 1) continue; // skip header line
line = line.trim();
if (line.matches(".*,.*")) {
String doi1 = line.replaceFirst("^(.*),.*$", "$1");
String doi2 = line.replaceFirst("^.*,(.*)$", "$1");
if (!titles.containsKey(doi1)) {
logDetail("ERROR. Missing publication: " + doi1);
missing++;
continue;
}
if (!titles.containsKey(doi2)) {
logDetail("ERROR. Missing publication: " + doi2);
missing++;
continue;
}
references.get(doi1).add(doi2);
} else {
log("ERROR. Invalid line: " + line);
invalid++;
}
}
r.close();
log("Invalid lines: " + invalid);
log("Missing publications: " + missing);
}
private void readTerms() throws IOException {
if (termsFile == null) return;
log("Reading terms from " + termsFile + " ...");
terms = new ArrayList<String>();
if (termsFile.toString().endsWith(".csv")) {
readTermsCsv();
} else {
readTermsTxt();
}
log("Number of terms: " + terms.size());
}
private void readTermsTxt() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(termsFile));
String line;
while ((line = reader.readLine()) != null) {
String term = MemeUtils.normalize(line);
terms.add(term);
if (termCount >= 0 && terms.size() >= termCount) {
break;
}
}
reader.close();
}
private void readTermsCsv() throws IOException {
BufferedReader r = new BufferedReader(new FileReader(termsFile));
CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference());
List<String> header = csvReader.read();
int col;
if (termCol.matches("[0-9]+")) {
col = Integer.parseInt(termCol);
} else {
col = header.indexOf(termCol);
}
List<String> line;
while ((line = csvReader.read()) != null) {
String term = MemeUtils.normalize(line.get(col));
terms.add(term);
if (termCount >= 0 && terms.size() >= termCount) {
break;
}
}
csvReader.close();
}
private void writeDataFiles() throws IOException {
if (skipData) return;
if (randomize) {
randomizeDois();
}
log("Writing data files...");
String fileSuffix = "";
if (randomizeTimeWindow > 0) {
fileSuffix = "-randomized" + randomizeTimeWindow;
} else if (randomize) {
fileSuffix = "-randomized";
}
if (randomize && randomSeed != null) {
fileSuffix += "-s" + randomSeed;
}
fileSuffix += ".txt";
File fileT = new File(MemeUtils.getPreparedDataDir(), "aps-T" + fileSuffix);
File fileTA = new File(MemeUtils.getPreparedDataDir(), "aps-TA" + fileSuffix);
int noAbstracts = 0;
BufferedWriter wT = null;
BufferedWriter wTA = null;
if (!skipDataT) wT = new BufferedWriter(new FileWriter(fileT));
if (!skipDataTA) wTA = new BufferedWriter(new FileWriter(fileTA));
for (String doi1 : titles.keySet()) {
List<String> refs = references.get(doi1);
if (randomize) doi1 = randomizedDois.get(doi1);
String text = titles.get(doi1);
String date = dates.get(doi1);
DataEntry eT = new DataEntry(doi1, date, text);
if (abstracts.containsKey(doi1)) text += " " + abstracts.get(doi1);
DataEntry eTA = new DataEntry(doi1, date, text);
for (String doi2 : refs) {
if (randomize) doi2 = randomizedDois.get(doi2);
text = titles.get(doi2);
eT.addCitedText(text);
if (abstracts.containsKey(doi2)) text += " " + abstracts.get(doi2);
eTA.addCitedText(text);
}
if (!skipDataT) wT.write(eT.getLine() + "\n");
if (!skipDataTA) wTA.write(eTA.getLine() + "\n");
}
if (!skipDataT) wT.close();
if (!skipDataTA) wTA.close();
log("No abstracts: " + noAbstracts);
}
private void randomizeDois() {
log("Randomizing DOIs...");
if (randomizeTimeWindow > 0) {
List<String> dateDoiList = new ArrayList<String>(titles.size());
for (String doi : titles.keySet()) {
String date = dates.get(doi);
if (date == null) date = "";
dateDoiList.add(date + " " + doi);
}
Collections.sort(dateDoiList);
List<String> dois = new ArrayList<String>(randomizeTimeWindow);
for (String dateDoi : dateDoiList) {
dois.add(dateDoi.split(" ", -1)[1]);
if (dois.size() >= randomizeTimeWindow) {
randomizeDois(dois);
}
}
randomizeDois(dois);
} else {
List<String> doisOut = new ArrayList<String>(titles.keySet());
Collections.shuffle(doisOut, random);
int i = 0;
for (String doiIn : titles.keySet()) {
randomizedDois.put(doiIn, doisOut.get(i));
i++;
}
}
}
private void randomizeDois(List<String> dois) {
List<String> doisShuffled = new ArrayList<String>(dois);
Collections.shuffle(doisShuffled, random);
int i = 0;
for (String doiIn : dois) {
randomizedDois.put(doiIn, doisShuffled.get(i));
i++;
}
dois.clear();
}
private void writeGmlFile() throws IOException {
if (skipGml || randomize) return;
log("Writing GML file...");
File file = new File(MemeUtils.getPreparedDataDir(), "aps.gml");
BufferedWriter w = new BufferedWriter(new FileWriter(file));
w.write("graph [\n");
w.write("directed 1\n");
if (terms != null) {
for (int i = 0; i < terms.size(); i++) {
w.write("comment \"meme" + i + ": " + terms.get(i).replace("\"", "") + "\"\n");
}
}
for (String doi : titles.keySet()) {
String year = dates.get(doi).substring(0, 4);
w.write("node [\n");
w.write("id \"" + doi + "\"\n");
w.write("journal \"" + getJournalFromDoi(doi) + "\"\n");
w.write("year \"" + year + "\"\n");
if (terms != null) {
String text = titles.get(doi);
if (abstracts.containsKey(doi)) text += " " + abstracts.get(doi);
text = " " + text + " ";
for (int i = 0; i < terms.size(); i++) {
if (text.contains(" " + terms.get(i) + " ")) {
w.write("meme" + i + " 1\n");
}
}
}
w.write("]\n");
}
for (String doi1 : references.keySet()) {
for (String doi2 : references.get(doi1)) {
w.write("edge [\n");
w.write("source \"" + doi1 + "\"\n");
w.write("target \"" + doi2 + "\"\n");
w.write("]\n");
}
}
w.write("]\n");
w.close();
}
public static String getJournalFromDoi(String doi) {
return doi.replaceFirst("^10\\.[0-9]+/([^.]+).*$", "$1");
}
private void log(Object obj) {
MemeUtils.log(logFile, obj);
}
private void logDetail(Object obj) {
if (verbose) log(obj);
}
}
|
package cloud.swiftnode.kspam.util;
import cloud.swiftnode.kspam.KSpam;
import cloud.swiftnode.kspam.abstraction.SpamExecutor;
import cloud.swiftnode.kspam.abstraction.executor.DebugSpamExecutor;
import cloud.swiftnode.kspam.abstraction.executor.PunishSpamExecutor;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
public class Static {
public static void runTaskAsync(Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously(KSpam.INSTANCE, runnable);
}
public static void runTaskLaterAsync(Runnable runnable, long delay) {
Bukkit.getScheduler().runTaskLaterAsynchronously(KSpam.INSTANCE, runnable, delay);
}
public static void runTaskTimerAsync(Runnable runnable, long delay, long period) {
Bukkit.getScheduler().runTaskTimerAsynchronously(KSpam.INSTANCE, runnable, delay, period);
}
public static void runTask(Runnable runnable) {
Bukkit.getScheduler().runTask(KSpam.INSTANCE, runnable);
}
public static void consoleMsg(String... msgs) {
for (String msg : msgs) {
Bukkit.getConsoleSender().sendMessage(msg);
}
}
public static void consoleMsg(Lang.MessageBuilder... builders) {
for (Lang.MessageBuilder builder : builders) {
consoleMsg(builder.build());
}
}
public static void consoleMsg(Exception ex) {
if (!Config.isAlert()) {
return;
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(stream));
consoleMsg(Lang.EXCEPTION.builder().single(Lang.Key.EXCEPTION_MESSAGE, new String(stream.toByteArray())).prefix());
}
public static long time() {
return System.currentTimeMillis();
}
public static String readAllText(URL url, String userContentOption) throws IOException {
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", userContentOption);
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String all = null;
String line;
while ((line = reader.readLine()) != null) {
if (all != null) {
all += line;
} else {
all = line;
}
}
reader.close();
return all;
}
public static String readAllText(URL url) throws IOException {
return readAllText(url, "K-SPAM v" + StaticStorage.getCurrVer());
}
public static String substring(String target, String a, String b) {
String parse = target.substring(target.indexOf(a) + a.length());
return parse.substring(0, parse.indexOf(b));
}
public static String getVersion() {
return KSpam.INSTANCE.getDescription().getVersion();
}
public static FileConfiguration getConfig() {
return KSpam.INSTANCE.getConfig();
}
public static SpamExecutor getDefaultExecutor() {
if (Config.isDebugMode()) {
return new DebugSpamExecutor(new PunishSpamExecutor());
}
return new PunishSpamExecutor();
}
@SuppressWarnings("unchecked")
public static Player[] getOnlinePlayers() {
Player[] players = new Player[0];
try {
Method method = Bukkit.class.getMethod("getOnlinePlayers");
Object ret = method.invoke(null);
if (ret instanceof Collection) {
players = ((Collection<? extends Player>) ret).toArray(new Player[0]);
} else if (ret instanceof Player[]) {
players = (Player[]) ret;
} else {
throw new IllegalArgumentException("Illegal return type");
}
} catch (Exception ex) {
Static.consoleMsg(ex);
}
return players;
}
public static boolean isRunning() {
try {
Field consoleField = Bukkit.getServer().getClass().getDeclaredField("console");
consoleField.setAccessible(true);
Object console = consoleField.get(Bukkit.getServer());
Method runningMethod = console.getClass().getMethod("isRunning");
return (boolean) runningMethod.invoke(console);
} catch (Exception ex) {
Static.consoleMsg(ex);
return true;
}
}
}
|
package com.almasb.fxgl.entity;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.binding.NumberBinding;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.shape.Circle;
/**
* Represents the visual aspect of entity.
*
* @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
*/
public class EntityView extends Parent {
private Entity entity;
/**
* Scene view ctor
*
* @param entity the entity creating the view
* @param graphics the view for that entity
*/
EntityView(Entity entity, Node graphics) {
this.entity = entity;
addNode(graphics);
initAsSceneView();
}
/**
* Constructs new view for given entity
*
* @param entity the entity
*/
public EntityView(Entity entity) {
this.entity = entity;
}
/**
* @return source entity of this view
*/
public final Entity getEntity() {
return entity;
}
/**
* Binds X Y and rotation of the view to entity's properties.
*/
private void initAsSceneView() {
this.translateXProperty().bind(entity.xProperty());
this.translateYProperty().bind(entity.yProperty());
this.rotateProperty().bind(entity.rotationProperty());
NumberBinding xFlipped = Bindings.when(entity.xFlippedProperty()).then(-1).otherwise(1);
this.scaleXProperty().bind(xFlipped);
}
/**
* Add a child node.
*
* @param node graphics
*/
public final void addNode(Node node) {
if (node instanceof Circle) {
Circle c = (Circle) node;
c.setCenterX(c.getRadius());
c.setCenterY(c.getRadius());
}
getChildren().add(node);
}
/**
* Removes all children nodes attached to view.
*/
public final void removeChildren() {
getChildren().clear();
}
private RenderLayer renderLayer = RenderLayer.TOP;
public final void setRenderLayer(RenderLayer layer) {
if (entity.isActive())
throw new IllegalStateException(
"Can't set render layer to active view.");
this.renderLayer = layer;
}
/**
* @return render layer for entity
*/
public final RenderLayer getRenderLayer() {
return renderLayer;
}
}
|
package com.annimon.ownlang.parser;
import com.annimon.ownlang.exceptions.ParseException;
import com.annimon.ownlang.lib.NumberValue;
import com.annimon.ownlang.lib.StringValue;
import com.annimon.ownlang.lib.UserDefinedFunction;
import com.annimon.ownlang.parser.ast.*;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author aNNiMON
*/
public final class Parser {
public static Statement parse(List<Token> tokens) {
final Parser parser = new Parser(tokens);
final Statement program = parser.parse();
if (parser.getParseErrors().hasErrors()) {
throw new ParseException();
}
return program;
}
private static final Token EOF = new Token(TokenType.EOF, "", -1, -1);
private static final EnumMap<TokenType, BinaryExpression.Operator> ASSIGN_OPERATORS;
static {
ASSIGN_OPERATORS = new EnumMap(TokenType.class);
ASSIGN_OPERATORS.put(TokenType.EQ, null);
ASSIGN_OPERATORS.put(TokenType.PLUSEQ, BinaryExpression.Operator.ADD);
ASSIGN_OPERATORS.put(TokenType.MINUSEQ, BinaryExpression.Operator.SUBTRACT);
ASSIGN_OPERATORS.put(TokenType.STAREQ, BinaryExpression.Operator.MULTIPLY);
ASSIGN_OPERATORS.put(TokenType.SLASHEQ, BinaryExpression.Operator.DIVIDE);
ASSIGN_OPERATORS.put(TokenType.PERCENTEQ, BinaryExpression.Operator.REMAINDER);
ASSIGN_OPERATORS.put(TokenType.AMPEQ, BinaryExpression.Operator.AND);
ASSIGN_OPERATORS.put(TokenType.CARETEQ, BinaryExpression.Operator.XOR);
ASSIGN_OPERATORS.put(TokenType.BAREQ, BinaryExpression.Operator.OR);
ASSIGN_OPERATORS.put(TokenType.COLONCOLONEQ, BinaryExpression.Operator.PUSH);
ASSIGN_OPERATORS.put(TokenType.LTLTEQ, BinaryExpression.Operator.LSHIFT);
ASSIGN_OPERATORS.put(TokenType.GTGTEQ, BinaryExpression.Operator.RSHIFT);
ASSIGN_OPERATORS.put(TokenType.GTGTGTEQ, BinaryExpression.Operator.URSHIFT);
ASSIGN_OPERATORS.put(TokenType.ATEQ, BinaryExpression.Operator.AT);
}
private final List<Token> tokens;
private final int size;
private final ParseErrors parseErrors;
private Statement parsedStatement;
private int pos;
public Parser(List<Token> tokens) {
this.tokens = tokens;
size = tokens.size();
parseErrors = new ParseErrors();
}
public Statement getParsedStatement() {
return parsedStatement;
}
public ParseErrors getParseErrors() {
return parseErrors;
}
public Statement parse() {
parseErrors.clear();
final BlockStatement result = new BlockStatement();
while (!match(TokenType.EOF)) {
try {
result.add(statement());
} catch (Exception ex) {
parseErrors.add(ex, getErrorLine());
recover();
}
}
parsedStatement = result;
return result;
}
private int getErrorLine() {
if (size == 0) return 0;
if (pos >= size) return tokens.get(size - 1).getRow();
return tokens.get(pos).getRow();
}
private void recover() {
int preRecoverPosition = pos;
for (int i = preRecoverPosition; i <= size; i++) {
pos = i;
try {
statement();
// successfully parsed,
pos = i; // restore position
return;
} catch (Exception ex) {
// fail
}
}
}
private Statement block() {
final BlockStatement block = new BlockStatement();
consume(TokenType.LBRACE);
while (!match(TokenType.RBRACE)) {
block.add(statement());
}
return block;
}
private Statement statementOrBlock() {
if (lookMatch(0, TokenType.LBRACE)) return block();
return statement();
}
private Statement statement() {
if (match(TokenType.PRINT)) {
return new PrintStatement(expression());
}
if (match(TokenType.PRINTLN)) {
return new PrintlnStatement(expression());
}
if (match(TokenType.IF)) {
return ifElse();
}
if (match(TokenType.WHILE)) {
return whileStatement();
}
if (match(TokenType.DO)) {
return doWhileStatement();
}
if (match(TokenType.BREAK)) {
return new BreakStatement();
}
if (match(TokenType.CONTINUE)) {
return new ContinueStatement();
}
if (match(TokenType.RETURN)) {
return new ReturnStatement(expression());
}
if (match(TokenType.USE)) {
return new UseStatement(expression());
}
if (match(TokenType.INCLUDE)) {
return new IncludeStatement(expression());
}
if (match(TokenType.FOR)) {
return forStatement();
}
if (match(TokenType.DEF)) {
return functionDefine();
}
if (match(TokenType.MATCH)) {
return new ExprStatement(match());
}
if (lookMatch(0, TokenType.WORD) && lookMatch(1, TokenType.LPAREN)) {
return new ExprStatement(functionChain(qualifiedName()));
}
return assignmentStatement();
}
private Statement assignmentStatement() {
if (match(TokenType.EXTRACT)) {
return destructuringAssignment();
}
final Expression expression = expression();
if (expression instanceof Statement) {
return (Statement) expression;
}
throw new ParseException("Unknown statement: " + get(0));
}
private DestructuringAssignmentStatement destructuringAssignment() {
// extract(var1, var2, ...) = ...
consume(TokenType.LPAREN);
final List<String> variables = new ArrayList<>();
while (!match(TokenType.RPAREN)) {
if (lookMatch(0, TokenType.WORD)) {
variables.add(consume(TokenType.WORD).getText());
} else {
variables.add(null);
}
consume(TokenType.COMMA);
}
consume(TokenType.EQ);
return new DestructuringAssignmentStatement(variables, expression());
}
private Statement ifElse() {
final Expression condition = expression();
final Statement ifStatement = statementOrBlock();
final Statement elseStatement;
if (match(TokenType.ELSE)) {
elseStatement = statementOrBlock();
} else {
elseStatement = null;
}
return new IfStatement(condition, ifStatement, elseStatement);
}
private Statement whileStatement() {
final Expression condition = expression();
final Statement statement = statementOrBlock();
return new WhileStatement(condition, statement);
}
private Statement doWhileStatement() {
final Statement statement = statementOrBlock();
consume(TokenType.WHILE);
final Expression condition = expression();
return new DoWhileStatement(condition, statement);
}
private Statement forStatement() {
int foreachIndex = lookMatch(0, TokenType.LPAREN) ? 1 : 0;
if (lookMatch(foreachIndex, TokenType.WORD) && lookMatch(foreachIndex + 1, TokenType.COLON)) {
// for v : arr || for (v : arr)
return foreachArrayStatement();
}
if (lookMatch(foreachIndex, TokenType.WORD) && lookMatch(foreachIndex + 1, TokenType.COMMA)
&& lookMatch(foreachIndex + 2, TokenType.WORD) && lookMatch(foreachIndex + 3, TokenType.COLON)) {
// for key, value : arr || for (key, value : arr)
return foreachMapStatement();
}
// for (init, condition, increment) body
boolean optParentheses = match(TokenType.LPAREN);
final Statement initialization = assignmentStatement();
consume(TokenType.COMMA);
final Expression termination = expression();
consume(TokenType.COMMA);
final Statement increment = assignmentStatement();
if (optParentheses) consume(TokenType.RPAREN); // close opt parentheses
final Statement statement = statementOrBlock();
return new ForStatement(initialization, termination, increment, statement);
}
private ForeachArrayStatement foreachArrayStatement() {
boolean optParentheses = match(TokenType.LPAREN);
final String variable = consume(TokenType.WORD).getText();
consume(TokenType.COLON);
final Expression container = expression();
if (optParentheses) consume(TokenType.RPAREN); // close opt parentheses
final Statement statement = statementOrBlock();
return new ForeachArrayStatement(variable, container, statement);
}
private ForeachMapStatement foreachMapStatement() {
boolean optParentheses = match(TokenType.LPAREN);
final String key = consume(TokenType.WORD).getText();
consume(TokenType.COMMA);
final String value = consume(TokenType.WORD).getText();
consume(TokenType.COLON);
final Expression container = expression();
if (optParentheses) consume(TokenType.RPAREN); // close opt parentheses
final Statement statement = statementOrBlock();
return new ForeachMapStatement(key, value, container, statement);
}
private FunctionDefineStatement functionDefine() {
// def name(arg1, arg2 = value) { ... } || def name(args) = expr
final String name = consume(TokenType.WORD).getText();
final Arguments arguments = arguments();
final Statement body = statementBody();
return new FunctionDefineStatement(name, arguments, body);
}
private Arguments arguments() {
// (arg1, arg2, arg3 = expr1, arg4 = expr2)
final Arguments arguments = new Arguments();
boolean startsOptionalArgs = false;
consume(TokenType.LPAREN);
while (!match(TokenType.RPAREN)) {
final String name = consume(TokenType.WORD).getText();
if (match(TokenType.EQ)) {
startsOptionalArgs = true;
arguments.addOptional(name, variable());
} else if (!startsOptionalArgs) {
arguments.addRequired(name);
} else {
throw new ParseException("Required argument cannot be after optional");
}
match(TokenType.COMMA);
}
return arguments;
}
private Statement statementBody() {
if (match(TokenType.EQ)) {
return new ReturnStatement(expression());
}
return statementOrBlock();
}
private Expression functionChain(Expression qualifiedNameExpr) {
// f1()()() || f1().f2().f3() || f1().key
final Expression expr = function(qualifiedNameExpr);
if (lookMatch(0, TokenType.LPAREN)) {
return functionChain(expr);
}
if (lookMatch(0, TokenType.DOT)) {
final List<Expression> indices = variableSuffix();
if (indices == null | indices.isEmpty()) return expr;
if (lookMatch(0, TokenType.LPAREN)) {
// next function call
return functionChain(new ContainerAccessExpression(expr, indices));
}
// container access
return new ContainerAccessExpression(expr, indices);
}
return expr;
}
private FunctionalExpression function(Expression qualifiedNameExpr) {
// function(arg1, arg2, ...)
consume(TokenType.LPAREN);
final FunctionalExpression function = new FunctionalExpression(qualifiedNameExpr);
while (!match(TokenType.RPAREN)) {
function.addArgument(expression());
match(TokenType.COMMA);
}
return function;
}
private Expression array() {
// [value1, value2, ...]
consume(TokenType.LBRACKET);
final List<Expression> elements = new ArrayList<>();
while (!match(TokenType.RBRACKET)) {
elements.add(expression());
match(TokenType.COMMA);
}
return new ArrayExpression(elements);
}
private Expression map() {
// {key1 : value1, key2 : value2, ...}
consume(TokenType.LBRACE);
final Map<Expression, Expression> elements = new HashMap<>();
while (!match(TokenType.RBRACE)) {
final Expression key = primary();
consume(TokenType.COLON);
final Expression value = expression();
elements.put(key, value);
match(TokenType.COMMA);
}
return new MapExpression(elements);
}
private MatchExpression match() {
// match expression {
// case pattern1: result1
// case pattern2 if extr: result2
final Expression expression = expression();
consume(TokenType.LBRACE);
final List<MatchExpression.Pattern> patterns = new ArrayList<>();
do {
consume(TokenType.CASE);
MatchExpression.Pattern pattern = null;
final Token current = get(0);
if (match(TokenType.NUMBER)) {
// case 0.5:
pattern = new MatchExpression.ConstantPattern(
NumberValue.of(createNumber(current.getText(), 10))
);
} else if (match(TokenType.HEX_NUMBER)) {
// case
pattern = new MatchExpression.ConstantPattern(
NumberValue.of(createNumber(current.getText(), 16))
);
} else if (match(TokenType.TEXT)) {
// case "text":
pattern = new MatchExpression.ConstantPattern(
new StringValue(current.getText())
);
} else if (match(TokenType.WORD)) {
// case value:
pattern = new MatchExpression.VariablePattern(current.getText());
} else if (match(TokenType.LBRACKET)) {
// case [x :: xs]:
final MatchExpression.ListPattern listPattern = new MatchExpression.ListPattern();
while (!match(TokenType.RBRACKET)) {
listPattern.add(consume(TokenType.WORD).getText());
match(TokenType.COLONCOLON);
}
pattern = listPattern;
} else if (match(TokenType.LPAREN)) {
// case (1, 2):
final MatchExpression.TuplePattern tuplePattern = new MatchExpression.TuplePattern();
while (!match(TokenType.RPAREN)) {
if ("_".equals(get(0).getText())) {
tuplePattern.addAny();
consume(TokenType.WORD);
} else {
tuplePattern.add(expression());
}
match(TokenType.COMMA);
}
pattern = tuplePattern;
}
if (pattern == null) {
throw new ParseException("Wrong pattern in match expression: " + current);
}
if (match(TokenType.IF)) {
// case e if e > 0:
pattern.optCondition = expression();
}
consume(TokenType.COLON);
if (lookMatch(0, TokenType.LBRACE)) {
pattern.result = block();
} else {
pattern.result = new ReturnStatement(expression());
}
patterns.add(pattern);
} while (!match(TokenType.RBRACE));
return new MatchExpression(expression, patterns);
}
private Expression expression() {
return assignment();
}
private Expression assignment() {
final Expression assignment = assignmentStrict();
if (assignment != null) {
return assignment;
}
return ternary();
}
private Expression assignmentStrict() {
final int position = pos;
final Expression targetExpr = qualifiedName();
if ((targetExpr == null) || !(targetExpr instanceof Accessible)) {
pos = position;
return null;
}
final TokenType currentType = get(0).getType();
if (!ASSIGN_OPERATORS.containsKey(currentType)) {
pos = position;
return null;
}
match(currentType);
final BinaryExpression.Operator op = ASSIGN_OPERATORS.get(currentType);
final Expression expression = expression();
return new AssignmentExpression(op, (Accessible) targetExpr, expression);
}
private Expression ternary() {
Expression result = logicalOr();
if (match(TokenType.QUESTION)) {
final Expression trueExpr = expression();
consume(TokenType.COLON);
final Expression falseExpr = expression();
return new TernaryExpression(result, trueExpr, falseExpr);
}
if (match(TokenType.QUESTIONCOLON)) {
return new BinaryExpression(BinaryExpression.Operator.ELVIS, result, expression());
}
return result;
}
private Expression logicalOr() {
Expression result = logicalAnd();
while (true) {
if (match(TokenType.BARBAR)) {
result = new ConditionalExpression(ConditionalExpression.Operator.OR, result, logicalAnd());
continue;
}
break;
}
return result;
}
private Expression logicalAnd() {
Expression result = bitwiseOr();
while (true) {
if (match(TokenType.AMPAMP)) {
result = new ConditionalExpression(ConditionalExpression.Operator.AND, result, bitwiseOr());
continue;
}
break;
}
return result;
}
private Expression bitwiseOr() {
Expression expression = bitwiseXor();
while (true) {
if (match(TokenType.BAR)) {
expression = new BinaryExpression(BinaryExpression.Operator.OR, expression, bitwiseXor());
continue;
}
break;
}
return expression;
}
private Expression bitwiseXor() {
Expression expression = bitwiseAnd();
while (true) {
if (match(TokenType.CARET)) {
expression = new BinaryExpression(BinaryExpression.Operator.XOR, expression, bitwiseAnd());
continue;
}
break;
}
return expression;
}
private Expression bitwiseAnd() {
Expression expression = equality();
while (true) {
if (match(TokenType.AMP)) {
expression = new BinaryExpression(BinaryExpression.Operator.AND, expression, equality());
continue;
}
break;
}
return expression;
}
private Expression equality() {
Expression result = conditional();
if (match(TokenType.EQEQ)) {
return new ConditionalExpression(ConditionalExpression.Operator.EQUALS, result, conditional());
}
if (match(TokenType.EXCLEQ)) {
return new ConditionalExpression(ConditionalExpression.Operator.NOT_EQUALS, result, conditional());
}
return result;
}
private Expression conditional() {
Expression result = shift();
while (true) {
if (match(TokenType.LT)) {
result = new ConditionalExpression(ConditionalExpression.Operator.LT, result, shift());
continue;
}
if (match(TokenType.LTEQ)) {
result = new ConditionalExpression(ConditionalExpression.Operator.LTEQ, result, shift());
continue;
}
if (match(TokenType.GT)) {
result = new ConditionalExpression(ConditionalExpression.Operator.GT, result, shift());
continue;
}
if (match(TokenType.GTEQ)) {
result = new ConditionalExpression(ConditionalExpression.Operator.GTEQ, result, shift());
continue;
}
break;
}
return result;
}
private Expression shift() {
Expression expression = additive();
while (true) {
if (match(TokenType.LTLT)) {
expression = new BinaryExpression(BinaryExpression.Operator.LSHIFT, expression, additive());
continue;
}
if (match(TokenType.GTGT)) {
expression = new BinaryExpression(BinaryExpression.Operator.RSHIFT, expression, additive());
continue;
}
if (match(TokenType.GTGTGT)) {
expression = new BinaryExpression(BinaryExpression.Operator.URSHIFT, expression, additive());
continue;
}
if (match(TokenType.DOTDOT)) {
expression = new BinaryExpression(BinaryExpression.Operator.RANGE, expression, additive());
continue;
}
break;
}
return expression;
}
private Expression additive() {
Expression result = multiplicative();
while (true) {
if (match(TokenType.PLUS)) {
result = new BinaryExpression(BinaryExpression.Operator.ADD, result, multiplicative());
continue;
}
if (match(TokenType.MINUS)) {
result = new BinaryExpression(BinaryExpression.Operator.SUBTRACT, result, multiplicative());
continue;
}
if (match(TokenType.COLONCOLON)) {
result = new BinaryExpression(BinaryExpression.Operator.PUSH, result, multiplicative());
continue;
}
if (match(TokenType.AT)) {
result = new BinaryExpression(BinaryExpression.Operator.AT, result, multiplicative());
continue;
}
break;
}
return result;
}
private Expression multiplicative() {
Expression result = unary();
while (true) {
if (match(TokenType.STAR)) {
result = new BinaryExpression(BinaryExpression.Operator.MULTIPLY, result, unary());
continue;
}
if (match(TokenType.SLASH)) {
result = new BinaryExpression(BinaryExpression.Operator.DIVIDE, result, unary());
continue;
}
if (match(TokenType.PERCENT)) {
result = new BinaryExpression(BinaryExpression.Operator.REMAINDER, result, unary());
continue;
}
if (match(TokenType.STARSTAR)) {
result = new BinaryExpression(BinaryExpression.Operator.POWER, result, unary());
continue;
}
break;
}
return result;
}
private Expression unary() {
if (match(TokenType.PLUSPLUS)) {
return new UnaryExpression(UnaryExpression.Operator.INCREMENT_PREFIX, primary());
}
if (match(TokenType.MINUSMINUS)) {
return new UnaryExpression(UnaryExpression.Operator.DECREMENT_PREFIX, primary());
}
if (match(TokenType.MINUS)) {
return new UnaryExpression(UnaryExpression.Operator.NEGATE, primary());
}
if (match(TokenType.EXCL)) {
return new UnaryExpression(UnaryExpression.Operator.NOT, primary());
}
if (match(TokenType.TILDE)) {
return new UnaryExpression(UnaryExpression.Operator.COMPLEMENT, primary());
}
if (match(TokenType.PLUS)) {
return primary();
}
return primary();
}
private Expression primary() {
if (match(TokenType.LPAREN)) {
Expression result = expression();
match(TokenType.RPAREN);
return result;
}
if (match(TokenType.COLONCOLON)) {
final String functionName = consume(TokenType.WORD).getText();
return new FunctionReferenceExpression(functionName);
}
if (match(TokenType.MATCH)) {
return match();
}
if (match(TokenType.DEF)) {
final Arguments arguments = arguments();
final Statement statement = statementBody();
return new ValueExpression(new UserDefinedFunction(arguments, statement));
}
return variable();
}
private Expression variable() {
// function(...
if (lookMatch(0, TokenType.WORD) && lookMatch(1, TokenType.LPAREN)) {
return functionChain(new ValueExpression(consume(TokenType.WORD).getText()));
}
final Expression qualifiedNameExpr = qualifiedName();
if (qualifiedNameExpr != null) {
// variable(args) || arr["key"](args) || obj.key(args)
if (lookMatch(0, TokenType.LPAREN)) {
return functionChain(qualifiedNameExpr);
}
// postfix increment/decrement
if (match(TokenType.PLUSPLUS)) {
return new UnaryExpression(UnaryExpression.Operator.INCREMENT_POSTFIX, qualifiedNameExpr);
}
if (match(TokenType.MINUSMINUS)) {
return new UnaryExpression(UnaryExpression.Operator.DECREMENT_POSTFIX, qualifiedNameExpr);
}
return qualifiedNameExpr;
}
if (lookMatch(0, TokenType.LBRACKET)) {
return array();
}
if (lookMatch(0, TokenType.LBRACE)) {
return map();
}
return value();
}
private Expression qualifiedName() {
// var || var.key[index].key2
final Token current = get(0);
if (!match(TokenType.WORD)) return null;
final List<Expression> indices = variableSuffix();
if ((indices == null) || indices.isEmpty()) {
return new VariableExpression(current.getText());
}
return new ContainerAccessExpression(current.getText(), indices);
}
private List<Expression> variableSuffix() {
// .key1.arr1[expr1][expr2].key2
if (!lookMatch(0, TokenType.DOT) && !lookMatch(0, TokenType.LBRACKET)) {
return null;
}
final List<Expression> indices = new ArrayList<>();
while (lookMatch(0, TokenType.DOT) || lookMatch(0, TokenType.LBRACKET)) {
if (match(TokenType.DOT)) {
final String fieldName = consume(TokenType.WORD).getText();
final Expression key = new ValueExpression(fieldName);
indices.add(key);
}
if (match(TokenType.LBRACKET)) {
indices.add(expression());
consume(TokenType.RBRACKET);
}
}
return indices;
}
private Expression value() {
final Token current = get(0);
if (match(TokenType.NUMBER)) {
return new ValueExpression(createNumber(current.getText(), 10));
}
if (match(TokenType.HEX_NUMBER)) {
return new ValueExpression(createNumber(current.getText(), 16));
}
if (match(TokenType.TEXT)) {
return new ValueExpression(current.getText());
}
throw new ParseException("Unknown expression: " + current);
}
private Number createNumber(String text, int radix) {
// Double
if (text.contains(".")) {
return Double.parseDouble(text);
}
// Integer
try {
return Integer.parseInt(text, radix);
} catch (NumberFormatException nfe) {
return Long.parseLong(text, radix);
}
}
private Token consume(TokenType type) {
final Token current = get(0);
if (type != current.getType()) throw new ParseException("Token " + current + " doesn't match " + type);
pos++;
return current;
}
private boolean match(TokenType type) {
final Token current = get(0);
if (type != current.getType()) return false;
pos++;
return true;
}
private boolean lookMatch(int pos, TokenType type) {
return get(pos).getType() == type;
}
private Token get(int relativePosition) {
final int position = pos + relativePosition;
if (position >= size) return EOF;
return tokens.get(position);
}
}
|
package com.communeup.service;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.communeup.crol.dao.NoticeDao;
import com.communeup.crol.dao.NoticeDaoImpl;
import com.communeup.crol.domain.Notice;
import com.communeup.crol.to.CrolInput;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@Service
public class CrolService {
private NoticeDao noticeDao = new NoticeDaoImpl();
private ParserService parserService = new ParserService();
public Notice fetch( String noticeId ) {
return noticeDao.getNotice(noticeId);
}
public void parseAndSave(CrolInput noticeInput) {
String parserOutput = parserService.parseInput(noticeInput.getNoticeType(), noticeInput);
String output = createFreemarkerOutputFromInput(noticeInput, parserOutput);
if (isJSONValid(output)) {
noticeDao.saveNotice(createNotice(noticeInput, output), noticeInput);
} else {
System.out.println("Json doesn't validate ... \n" + output);
}
}
/**
*
* @param jsonPayload
*/
private String createFreemarkerOutputFromInput(CrolInput input, String parserOutput) {
try {
String ftlPath = new java.io.File("/").getCanonicalPath();
ftlPath += "/template.ftl";
Configuration config = new Configuration();
config.setClassForTemplateLoading(CrolService.class, "");
Template template = config.getTemplate(ftlPath);
Map<String, Object> data = new HashMap<String, Object>();
data.put("PIN", checkNullString(input.getPin()));
data.put("Email", checkNullString(input.getEmail()));
data.put("EndDate", checkNullString(input.getEndDate()));
data.put("DueDate", checkNullString(input.getDueDate()));
data.put("Printout", checkNullString(input.getPrintout()));
data.put("StartDate", checkNullString(input.getStartDate()));
data.put("OtherInfo", checkNullString(input.getOtherInfo()));
data.put("RequestID", checkNullString(input.getRequestId()));
data.put("SectionID", checkNullString(input.getSectionId()));
data.put("OtherInfo", checkNullString(input.getOtherInfo()));
data.put("ContactFax", checkNullString(input.getContactFax()));
data.put("ShortTitle", checkNullString(input.getShortTitle()));
data.put("AgencyName", checkNullString(input.getAgencyName()));
data.put("AgencyCode", checkNullString(input.getAgencyCode()));
data.put("VendorName", checkNullString(input.getVendorName()));
data.put("SectionName", checkNullString(input.getSectionName()));
data.put("ContactName", checkNullString(input.getContactName()));
data.put("ContactPhone", checkNullString(input.getContactPhone()));
data.put("VendorAddress", checkNullString(input.getVendorAddress()));
data.put("ContractAmount", checkNullString(input.getContractAmount()));
data.put("AddressToSubmit", checkNullString(input.getAddressToSubmit()));
data.put("TypeOfNoticeCode", checkNullString(input.getTypeOfNoticeCode()));
data.put("CategoryDescription", checkNullString(input.getCategoryDescription()));
data.put("SelectionMethodCode", checkNullString(input.getSelectionMethodCode()));
data.put("AdditionalDescription", checkNullString(input.getAdditionalDescription()));
data.put("SpecialCaseReasonCode", checkNullString(input.getSpecialCaseReasonCode()));
data.put("SelectionMethodDescription", checkNullString(input.getSelectionMethodDescription()));
data.put("SpecialCaseReasonDescription", checkNullString(input.getSpecialCaseReasonDescription()));
data.put("ParserOutput", parserOutput);
StringWriter writer = new StringWriter();
template.process(data, writer);
writer.flush();
return writer.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return null;
}
private Object checkNullString(String string) {
return (string == null) ? "" : string;
}
private Notice createNotice(CrolInput noticeInput, String output) {
Notice notice = new Notice();
notice.setNoticeId(noticeInput.getRequestId());
notice.setNoticeText(output);
return notice;
}
public void parseAndUpdate(CrolInput noticeInput) {
String parserOutput = parserService.parseInput(noticeInput.getNoticeType(), noticeInput);
String output = createFreemarkerOutputFromInput(noticeInput, parserOutput);
System.out.println(output);
noticeDao.deleteNotice(createNotice(noticeInput, output));
}
public void delete(String noticeId) {
noticeDao.deleteNotice(noticeId);
}
public List<Notice> fetchAfter(String timestamp) {
return noticeDao.getNoticeAfter(timestamp);
}
public static boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
}
|
package com.datasift.client.cli;
import com.datasift.client.BaseDataSiftResult;
import com.datasift.client.DataSiftClient;
import com.datasift.client.DataSiftConfig;
import com.datasift.client.DataSiftResult;
import com.datasift.client.pylon.PylonQueryParameters;
import com.datasift.client.pylon.PylonQuery;
import com.datasift.client.core.Stream;
import com.datasift.client.core.Usage;
import com.datasift.client.push.OutputType;
import com.datasift.client.push.PushSubscription;
import com.datasift.client.push.connectors.BaseConnector;
import com.datasift.client.push.connectors.PushConnector;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.higgs.http.client.HttpRequestBuilder;
import org.joda.time.DateTime;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.datasift.client.cli.Parser.CliArguments;
import static com.datasift.client.cli.Parser.CliSwitch;
public class Interface {
private static final ObjectMapper mapper = new ObjectMapper();
private Interface() {
}
private static String getOrDefault(Map<String, String> map, String key, String defaultValue) {
if (map.containsKey(key)) {
return map.get(key);
} else {
return defaultValue;
}
}
public static void main(String[] args) throws JsonProcessingException {
try {
List<CliSwitch> switches = new ArrayList<>();
switches.add(new CliSwitch("a", "auth", true, "Auth is required in the form username:api_key"));
switches.add(new CliSwitch("c", "command", true));
CliSwitch endpoint = new CliSwitch("e", "endpoint");
endpoint.setDefault("core");
switches.add(endpoint);
switches.add(new CliSwitch("p", "param"));
switches.add(new CliSwitch("u", "url"));
CliArguments parsedArgs = Parser.parse(args, switches);
Map<String, String> auth = parsedArgs.map("a");
if (auth == null || auth.size() == 0) {
System.out.println("Auth must be provided in the form '-a[uth] username api_key'");
System.exit(0);
}
Map.Entry<String, String> authVals = auth.entrySet().iterator().next();
DataSiftConfig config = new DataSiftConfig(authVals.getKey(), authVals.getValue());
String u = parsedArgs.get("u");
if (u != null) {
URI url = new URI(!u.startsWith("http") && !u.startsWith("https") ? "http://" + u : u);
config.host(url.getHost());
config.setSslEnabled(url.getScheme() != null && url.getScheme().equals("https"));
config.port(url.getPort() > -1 ? url.getPort() : config.isSslEnabled() ? 443 : 80);
}
DataSiftClient dataSift = new DataSiftClient(config);
HashMap<String, String> params = parsedArgs.map("p");
if (params == null) {
params = new HashMap<String, String>();
}
switch (parsedArgs.get("e")) {
case "core":
executeCore(dataSift, parsedArgs.get("c"), params);
break;
case "push":
executePush(dataSift, parsedArgs.get("c"), params);
break;
case "historics":
executeHistorics(dataSift, parsedArgs.get("c"), params);
break;
case "preview":
executePreview(dataSift, parsedArgs.get("c"), params);
break;
case "sources":
executeSources(dataSift, parsedArgs.get("c"), params);
break;
case "pylon":
executeAnalysis(dataSift, parsedArgs.get("c"), params);
break;
case "identity":
executeIdentity(dataSift, parsedArgs.get("c"), params);
break;
case "token":
executeToken(dataSift, parsedArgs.get("c"), params);
break;
case "limit":
executeLimit(dataSift, parsedArgs.get("c"), params);
break;
}
} catch (Exception ex) {
BaseDataSiftResult res = new BaseDataSiftResult();
res.failed(ex);
printResponse(res);
} finally {
HttpRequestBuilder.group().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS);
}
}
private static void require(String[] args, Map<String, String> params) {
List<String> missing = new ArrayList<>();
for (String arg : args) {
if (!params.containsKey(arg)) {
missing.add(arg);
}
}
if (missing.size() > 0) {
System.out.println("The following arguments are required : " + Arrays.toString(missing.toArray()));
System.exit(0);
}
}
private static void executeCore(DataSiftClient dataSift, String endpoint, Map<String, String> params)
throws JsonProcessingException {
switch (endpoint) {
case "validate":
require(new String[]{"csdl"}, params);
printResponse(dataSift.validate(params.get("csdl")).sync());
break;
case "compile":
require(new String[]{"csdl"}, params);
printResponse(dataSift.compile(params.get("csdl")).sync());
break;
case "usage":
String period = params.get("period");
if (period == null) {
printResponse(dataSift.usage().sync());
} else {
printResponse(dataSift.usage(Usage.Period.fromStr(period)).sync());
}
break;
case "dpu":
require(new String[]{"hash"}, params);
printResponse(dataSift.dpu(Stream.fromString(params.get("hash"))).sync());
break;
case "balance":
printResponse(dataSift.balance().sync());
break;
}
}
private static void printResponse(DataSiftResult result) throws JsonProcessingException {
try {
Map<String, Object> response = new HashMap<>();
Map<String, String> headers = new HashMap<>();
if (result.getResponse() != null) {
for (Map.Entry<String, List<String>> h : result.getResponse().headers().entrySet()) {
headers.put(h.getKey(), h.getValue() == null || h.getValue().size() == 0 ?
null : h.getValue().get(0));
}
int status = result.getResponse().status();
response.put("status", status);
} else {
response.put("error", "Invalid response, null");
}
response.put("body", result);
response.put("headers", headers);
System.out.println(mapper.writeValueAsString(response));
System.exit(0);
} catch (Exception ex) {
BaseDataSiftResult res = new BaseDataSiftResult();
res.failed(ex);
System.out.println(mapper.writeValueAsString(res));
System.exit(0);
} finally {
HttpRequestBuilder.group().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS);
}
}
private static void executePush(DataSiftClient dataSift, String endpoint, HashMap<String, String> params)
throws IOException {
PushConnector connector;
Map<String, Object> args = mapper.readValue(params.get("output_type"),
new TypeReference<HashMap<String, Object>>() {
});
connector = BaseConnector.fromMap(new OutputType<>(params.get("output_type")), args);
switch (endpoint) {
case "validate":
printResponse(dataSift.push().validate(connector).sync());
break;
case "create":
printResponse(dataSift.push().create(connector, Stream.fromString(params.get("hash")),
params.get("name")).sync());
break;
case "pause":
printResponse(dataSift.push().pause(params.get("id")).sync());
break;
case "resume":
printResponse(dataSift.push().resume(params.get("id")).sync());
break;
case "update":
printResponse(dataSift.push().update(params.get("id"), connector).sync());
break;
case "stop":
printResponse(dataSift.push().stop(params.get("id")).sync());
break;
case "delete":
printResponse(dataSift.push().delete(params.get("id")).sync());
break;
case "log":
printResponse(dataSift.push().log(params.get("id"), Integer.parseInt(params.get("page"))).sync());
break;
case "get":
printResponse(dataSift.push().get(params.get("id")).sync());
break;
case "pull":
printResponse(dataSift.push().pull(PushSubscription.fromString(params.get("id")),
Integer.parseInt(params.get("size")),
params.get("page")).sync());
break;
}
}
private static void executeHistorics(DataSiftClient dataSift, String endpoint, HashMap<String, String> params)
throws JsonProcessingException {
switch (endpoint) {
case "prepare":
printResponse(dataSift.historics().prepare(params.get("hash"), DateTime.parse(params.get("start")),
DateTime.parse(params.get("end")), params.get("name")).sync());
break;
case "start":
printResponse(dataSift.historics().start(params.get("id")).sync());
break;
case "stop":
printResponse(dataSift.historics().stop(params.get("id"), params.get("reason")).sync());
break;
case "status":
printResponse(dataSift.historics().status(new DateTime(Long.parseLong(params.get("start"))),
new DateTime(Long.parseLong(params.get("end")))).sync());
break;
case "update":
printResponse(dataSift.historics().update(params.get("id"), params.get("name")).sync());
break;
case "delete":
printResponse(dataSift.historics().delete(params.get("id")).sync());
break;
case "get":
printResponse(dataSift.historics().get(params.get("id")).sync());
break;
}
}
private static void executeAnalysis(DataSiftClient dataSift, String endpoint, HashMap<String, String> params)
throws IOException {
switch (endpoint) {
case "analyze":
PylonQueryParameters map = null;
String p = params.get("parameters");
if (p != null && !p.isEmpty()) {
map = mapper.readValue(p, PylonQueryParameters.class);
}
PylonQuery analysis = new PylonQuery(params.get("hash"), map, params.get("filter"),
params.get("start") == null ? null : Integer.parseInt(params.get("start")),
params.get("end") == null ? null : Integer.parseInt(params.get("end")));
printResponse(dataSift.pylon().analyze(analysis).sync());
break;
case "compile":
printResponse(dataSift.pylon().compile(params.get("csdl")).sync());
break;
case "get":
String hash = params == null ? null : params.get("hash");
printResponse(hash == null ? dataSift.pylon().get().sync() : dataSift.pylon().get(hash).sync());
break;
case "start":
printResponse(dataSift.pylon().start(params.get("hash")).sync());
break;
case "stop":
printResponse(dataSift.pylon().stop(params.get("hash")).sync());
break;
case "tags":
printResponse(dataSift.pylon().tags(params.get("hash")).sync());
break;
case "validate":
printResponse(dataSift.pylon().validate(params.get("csdl")).sync());
break;
}
}
private static void executePreview(DataSiftClient dataSift, String endpoint, HashMap<String, String> params)
throws JsonProcessingException {
switch (endpoint) {
case "create":
printResponse(dataSift.preview().create(new DateTime(Long.parseLong(params.get("start"))),
Stream.fromString(params.get("hash")), params.get("params").split(",")).sync());
break;
case "get":
printResponse(dataSift.preview().get(params.get("id")).sync());
break;
}
}
private static void executeSources(DataSiftClient dataSift, String endpoint, HashMap<String, String> params)
throws JsonProcessingException {
switch (endpoint) {
case "create":
//DataSource
//new DateTime(Long.parseLong(params.get("start")))
//printResponse(dataSift.managedSource().create(params.get("name"), ).sync());
break;
case "update":
//printResponse(dataSift.managedSource().update(params.get("name"), ).sync());
break;
case "delete":
printResponse(dataSift.managedSource().delete(params.get("id")).sync());
break;
case "log":
printResponse(dataSift.managedSource().log(params.get("id")).sync());
break;
case "get":
printResponse(dataSift.managedSource().get(params.get("id")).sync());
break;
case "stop":
printResponse(dataSift.managedSource().stop(params.get("id")).sync());
break;
case "start":
printResponse(dataSift.managedSource().start(params.get("id")).sync());
break;
}
}
private static void executeIdentity(DataSiftClient dataSift, String endpoint, HashMap<String, String> params)
throws IOException {
switch (endpoint) {
case "list":
String label = getOrDefault(params, "label", null);
int page = Integer.parseInt(getOrDefault(params, "page", "0"));
int perpage = Integer.parseInt(getOrDefault(params, "per_page", "0"));
printResponse(dataSift.account().list(label, page, perpage).sync());
break;
case "get":
printResponse(dataSift.account().get(params.get("id")).sync());
break;
case "create":
String createlabel = params.get("label");
Boolean active = getOrDefault(params, "status", "inactive").equals("active");
Boolean master = getOrDefault(params, "master", "false").equals("true");
printResponse(dataSift.account().create(createlabel, active, master).sync());
break;
case "update":
String targetid = params.get("id");
String updatelabel = getOrDefault(params, "label", null);
String updateactivitystring = getOrDefault(params, "status", null);
Boolean updateactivity = null;
if (updateactivitystring.equals("active")) {
updateactivity = true;
} else if (updateactivitystring.equals("inactive")) {
updateactivity = false;
}
String updatemasterstring = getOrDefault(params, "master", null);
Boolean updatemaster = null;
if (updatemasterstring.equals("true")) {
updatemaster = true;
} else if (updatemasterstring.equals("false")) {
updatemaster = false;
}
printResponse(dataSift.account().update(targetid, updatelabel, updateactivity, updatemaster).sync());
break;
case "delete":
printResponse(dataSift.account().delete(params.get("id")).sync());
break;
}
}
private static void executeToken(DataSiftClient dataSift, String endpoint, HashMap<String, String> params)
throws IOException {
switch (endpoint) {
case "list":
String identityid = getOrDefault(params, "identity_id", null);
int page = Integer.parseInt(getOrDefault(params, "page", "0"));
int perpage = Integer.parseInt(getOrDefault(params, "per_page", "0"));
printResponse(dataSift.account().listTokens(identityid, page, perpage).sync());
break;
case "get":
printResponse(dataSift.account().getToken(params.get("identity_id"), params.get("service")).sync());
break;
case "create":
String createidentity = params.get("identity_id");
String createservice = params.get("service");
String createtoken = params.get("token");
printResponse(dataSift.account().createToken(createidentity, createservice, createtoken).sync());
break;
case "update":
String targetid = params.get("identity_id");
String targetservice = params.get("service");
String newtoken = params.get("token");
printResponse(dataSift.account().updateToken(targetid, targetservice, newtoken).sync());
break;
case "delete":
printResponse(dataSift.account().deleteToken(params.get("identity_id"), params.get("service")).sync());
break;
}
}
private static void executeLimit(DataSiftClient dataSift, String endpoint, HashMap<String, String> params)
throws IOException {
switch (endpoint) {
case "list":
String service = params.get("service");
int page = Integer.parseInt(getOrDefault(params, "page", "0"));
int perpage = Integer.parseInt(getOrDefault(params, "per_page", "0"));
printResponse(dataSift.account().listLimits(service, page, perpage).sync());
break;
case "get":
printResponse(dataSift.account().getLimit(params.get("identity_id"), params.get("service")).sync());
break;
case "create":
String createidentity = params.get("identity_id");
String createservice = params.get("service");
Long createallowance = Long.parseLong(params.get("total_allowance"));
printResponse(dataSift.account().createLimit(createidentity, createservice, createallowance).sync());
break;
case "update":
String updateidentity = params.get("identity_id");
String updateservice = params.get("service");
Long updateallowance = Long.parseLong(params.get("total_allowance"));
printResponse(dataSift.account().updateLimit(updateidentity, updateservice, updateallowance).sync());
break;
case "delete":
printResponse(dataSift.account().deleteLimit(params.get("identity_id"), params.get("service")).sync());
break;
}
}
}
|
package com.digium.respokesdk;
import android.content.Context;
import android.media.AudioManager;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.DataChannel;
import org.webrtc.IceCandidate;
import org.webrtc.MediaConstraints;
import org.webrtc.MediaStream;
import org.webrtc.MediaStreamTrack;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;
import org.webrtc.VideoCapturer;
import org.webrtc.VideoRenderer;
import org.webrtc.VideoRendererGui;
import org.webrtc.VideoSource;
import org.webrtc.VideoTrack;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RespokeCall {
private final static String TAG = "RespokeCall";
public RespokeCallDelegate delegate;
private RespokeSignalingChannel signalingChannel;
private ArrayList<PeerConnection.IceServer> iceServers;
private PeerConnectionFactory peerConnectionFactory;
private PeerConnection peerConnection;
private VideoSource videoSource;
private ArrayList<IceCandidate> queuedRemoteCandidates;
private ArrayList<IceCandidate> queuedLocalCandidates;
private org.webrtc.VideoRenderer.Callbacks localRender;
private org.webrtc.VideoRenderer.Callbacks remoteRender;
private boolean caller;
private boolean waitingForAnswer;
private JSONObject incomingSDP;
private String sessionID;
private String toConnection;
public RespokeEndpoint endpoint;
public boolean audioOnly;
private final PCObserver pcObserver = new PCObserver();
private final SDPObserver sdpObserver = new SDPObserver();
private boolean videoSourceStopped;
private MediaStream localStream;
public RespokeCall(RespokeSignalingChannel channel) {
commonConstructor(channel);
}
public RespokeCall(RespokeSignalingChannel channel, RespokeEndpoint newEndpoint) {
commonConstructor(channel);
endpoint = newEndpoint;
}
public RespokeCall(RespokeSignalingChannel channel, JSONObject sdp, String newSessionID, String newConnectionID, RespokeEndpoint newEndpoint) {
commonConstructor(channel);
incomingSDP = sdp;
sessionID = newSessionID;
endpoint = newEndpoint;
toConnection = newConnectionID;
}
public void commonConstructor(RespokeSignalingChannel channel) {
signalingChannel = channel;
iceServers = new ArrayList<PeerConnection.IceServer>();
queuedLocalCandidates = new ArrayList<IceCandidate>();
sessionID = Respoke.makeGUID();
peerConnectionFactory = new PeerConnectionFactory();
signalingChannel.delegate.callCreated(this);
//TODO resign active handler?
}
public String getSessionID() {
return sessionID;
}
public void disconnect() {
if (peerConnection != null) {
peerConnection.dispose();
peerConnection = null;
}
if (videoSource != null) {
videoSource.dispose();
videoSource = null;
}
if (peerConnectionFactory != null) {
peerConnectionFactory.dispose();
peerConnectionFactory = null;
}
signalingChannel.delegate.callTerminated(this);
delegate = null;
}
public void startCall(final Context context, GLSurfaceView glView, boolean isAudioOnly) {
caller = true;
waitingForAnswer = true;
audioOnly = isAudioOnly;
if (null != glView) {
VideoRendererGui.setView(glView);
remoteRender = VideoRendererGui.create(0, 0, 100, 100);
localRender = VideoRendererGui.create(70, 5, 25, 25);
}
getTurnServerCredentials(new RespokeTaskCompletionDelegate() {
@Override
public void onSuccess() {
Log.d(TAG, "Got TURN credentials");
addLocalStreams(context);
createOffer();
}
@Override
public void onError(String errorMessage) {
delegate.onError(errorMessage, RespokeCall.this);
}
});
}
public void answer(final Context context, RespokeCallDelegate newDelegate, GLSurfaceView glView) {
if (!caller) {
delegate = newDelegate;
if (null != glView) {
VideoRendererGui.setView(glView);
remoteRender = VideoRendererGui.create(0, 0, 100, 100);
localRender = VideoRendererGui.create(70, 5, 25, 25);
}
getTurnServerCredentials(new RespokeTaskCompletionDelegate() {
@Override
public void onSuccess() {
addLocalStreams(context);
processRemoteSDP();
}
@Override
public void onError(String errorMessage) {
delegate.onError(errorMessage, RespokeCall.this);
}
});
}
}
public void hangup(boolean shouldSendHangupSignal) {
if (shouldSendHangupSignal) {
JSONObject data = null;
try {
data = new JSONObject("{'signalType':'bye','target':'call','version':'1.0'}");
data.put("to", endpoint.getEndpointID());
data.put("sessionId", sessionID);
data.put("signalId", Respoke.makeGUID());
signalingChannel.sendSignal(data, endpoint.getEndpointID(), new RespokeTaskCompletionDelegate() {
@Override
public void onSuccess() {
// Do nothing
}
@Override
public void onError(String errorMessage) {
delegate.onError(errorMessage, RespokeCall.this);
}
});
} catch (JSONException e) {
delegate.onError("Error encoding signal to json", RespokeCall.this);
}
}
disconnect();
}
public void muteVideo(boolean mute) {
if (!audioOnly) {
for (MediaStreamTrack eachTrack : localStream.videoTracks) {
eachTrack.setEnabled(!mute);
}
}
}
public void muteAudio(boolean mute) {
for (MediaStreamTrack eachTrack : localStream.audioTracks) {
eachTrack.setEnabled(!mute);
}
}
public void pause() {
if (videoSource != null) {
videoSource.stop();
videoSourceStopped = true;
}
}
public void resume() {
if (videoSource != null && videoSourceStopped) {
videoSource.restart();
}
}
public void hangupReceived() {
disconnect();
delegate.onHangup(this);
}
public void answerReceived(JSONObject remoteSDP, String remoteConnection) {
incomingSDP = remoteSDP;
toConnection = remoteConnection;
try {
JSONObject signalData = new JSONObject("{'signalType':'connected','target':'call','version':'1.0'}");
signalData.put("to", endpoint.getEndpointID());
signalData.put("toConnection", toConnection);
signalData.put("sessionId", sessionID);
signalData.put("signalId", Respoke.makeGUID());
signalingChannel.sendSignal(signalData, endpoint.getEndpointID(), new RespokeTaskCompletionDelegate() {
@Override
public void onSuccess() {
processRemoteSDP();
delegate.onConnected(RespokeCall.this);
}
@Override
public void onError(String errorMessage) {
delegate.onError(errorMessage, RespokeCall.this);
}
});
} catch (JSONException e) {
delegate.onError("Error encoding answer signal", this);
}
}
public void connectedReceived() {
delegate.onConnected(this);
}
public void iceCandidatesReceived(JSONArray candidates) {
for (int ii = 0; ii < candidates.length(); ii++) {
try {
JSONObject eachCandidate = (JSONObject) candidates.get(ii);
String mid = eachCandidate.getString("sdpMid");
int sdpLineIndex = eachCandidate.getInt("sdpMLineIndex");
String sdp = eachCandidate.getString("candidate");
IceCandidate rtcCandidate = new IceCandidate(mid, sdpLineIndex, sdp);
if (null != queuedRemoteCandidates) {
queuedRemoteCandidates.add(rtcCandidate);
} else {
peerConnection.addIceCandidate(rtcCandidate);
}
} catch (JSONException e) {
Log.d(TAG, "Error processing remote ice candidate data");
}
}
}
private void processRemoteSDP() {
try {
String type = incomingSDP.getString("type");
String sdpString = incomingSDP.getString("sdp");
SessionDescription sdp = new SessionDescription(SessionDescription.Type.fromCanonicalForm(type), preferISAC(sdpString));
peerConnection.setRemoteDescription(this.sdpObserver, sdp);
} catch (JSONException e) {
delegate.onError("Error processing remote SDP.", this);
}
}
private void getTurnServerCredentials(final RespokeTaskCompletionDelegate completionDelegate) {
// get TURN server credentials
signalingChannel.sendRESTMessage("get", "/v1/turn", null, new RespokeSignalingChannelRESTDelegate() {
@Override
public void onSuccess(Object response) {
JSONObject jsonResponse = (JSONObject) response;
try {
String username = jsonResponse.getString("username");
String password = jsonResponse.getString("password");
JSONArray uris = (JSONArray) jsonResponse.get("uris");
for (int ii = 0; ii < uris.length(); ii++) {
String eachUri = uris.getString(ii);
PeerConnection.IceServer server = new PeerConnection.IceServer(eachUri, username, password);
iceServers.add(server);
}
if (iceServers.size() > 0) {
completionDelegate.onSuccess();
} else {
completionDelegate.onError("No ICE servers were found");
}
} catch (JSONException e) {
completionDelegate.onError("Unexpected response from server");
}
}
@Override
public void onError(String errorMessage) {
completionDelegate.onError(errorMessage);
}
});
}
private void addLocalStreams(Context context) {
queuedRemoteCandidates = new ArrayList<IceCandidate>();
//TODO not sure about these - Jason
MediaConstraints sdpMediaConstraints = new MediaConstraints();
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", audioOnly ? "false" : "true"));
sdpMediaConstraints.optional.add(new MediaConstraints.KeyValuePair("internalSctpDataChannels", "true"));
sdpMediaConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
//sdpMediaConstraints.optional.add(new MediaConstraints.KeyValuePair("RtpDataChannels", "true"));
peerConnection = peerConnectionFactory.createPeerConnection(iceServers, sdpMediaConstraints, pcObserver);
AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));
// TODO(fischman): figure out how to do this Right(tm) and remove the suppression.
@SuppressWarnings("deprecation")
boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn();
audioManager.setMode(isWiredHeadsetOn ? AudioManager.MODE_IN_CALL : AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(!isWiredHeadsetOn);
localStream = peerConnectionFactory.createLocalMediaStream("ARDAMS");
if (!audioOnly) {
VideoCapturer capturer = getVideoCapturer();
videoSource = peerConnectionFactory.createVideoSource(capturer, sdpMediaConstraints);
VideoTrack videoTrack = peerConnectionFactory.createVideoTrack("ARDAMSv0", videoSource);
videoTrack.addRenderer(new VideoRenderer(localRender));
localStream.addTrack(videoTrack);
}
localStream.addTrack(peerConnectionFactory.createAudioTrack("ARDAMSa0", peerConnectionFactory.createAudioSource(sdpMediaConstraints)));
peerConnection.addStream(localStream, new MediaConstraints());
}
// Cycle through likely device names for the camera and return the first
// capturer that works, or crash if none do.
private VideoCapturer getVideoCapturer() {
String[] cameraFacing = { "front", "back" };
int[] cameraIndex = { 0, 1 };
int[] cameraOrientation = { 0, 90, 180, 270 };
for (String facing : cameraFacing) {
for (int index : cameraIndex) {
for (int orientation : cameraOrientation) {
String name = "Camera " + index + ", Facing " + facing +
", Orientation " + orientation;
VideoCapturer capturer = VideoCapturer.create(name);
if (capturer != null) {
//logAndToast("Using camera: " + name);
Log.d(TAG, "Using camera: " + name);
return capturer;
}
}
}
}
throw new RuntimeException("Failed to open capturer");
}
private void createOffer() {
MediaConstraints sdpMediaConstraints = new MediaConstraints();
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
"OfferToReceiveAudio", "true"));
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
"OfferToReceiveVideo", audioOnly ? "false" : "true"));
peerConnection.createOffer(sdpObserver, sdpMediaConstraints);
}
private void updateVideoViewLayout() {
//TODO
}
// Implementation detail: observe ICE & stream changes and react accordingly.
private class PCObserver implements PeerConnection.Observer {
@Override public void onIceCandidate(final IceCandidate candidate){
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
Log.d(TAG, "onIceCandidate");
if (caller && waitingForAnswer) {
queuedLocalCandidates.add(candidate);
} else {
sendLocalCandidate(candidate);
}
}
});
}
@Override public void onError(){
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
delegate.onError("PeerConnection failed", RespokeCall.this);
}
});
}
@Override public void onSignalingChange(
PeerConnection.SignalingState newState) {
}
@Override public void onIceConnectionChange(
PeerConnection.IceConnectionState newState) {
if (newState == PeerConnection.IceConnectionState.CONNECTED) {
Log.d(TAG, "ICE Connection connected");
} else if (newState == PeerConnection.IceConnectionState.FAILED) {
Log.d(TAG, "ICE Connection FAILED");
delegate.onError("Ice Connection failed!", RespokeCall.this);
disconnect();
delegate.onHangup(RespokeCall.this);
delegate = null;
} else {
Log.d(TAG, "ICE Connection state: " + newState.toString());
}
}
@Override public void onIceGatheringChange(
PeerConnection.IceGatheringState newState) {
}
@Override public void onAddStream(final MediaStream stream){
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
if (stream.audioTracks.size() <= 1 && stream.videoTracks.size() <= 1) {
if (stream.videoTracks.size() == 1) {
stream.videoTracks.get(0).addRenderer(
new VideoRenderer(remoteRender));
}
} else {
delegate.onError("An invalid stream was added", RespokeCall.this);
}
}
});
}
@Override public void onRemoveStream(final MediaStream stream){
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
stream.videoTracks.get(0).dispose();
}
});
}
@Override public void onDataChannel(final DataChannel dc) {
/*new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
throw new RuntimeException(
"AppRTC doesn't use data channels, but got: " + dc.label() +
" anyway!");
}
});*/
}
@Override public void onRenegotiationNeeded() {
// No need to do anything; AppRTC follows a pre-agreed-upon
// signaling/negotiation protocol.
}
}
// Implementation detail: handle offer creation/signaling and answer setting,
// as well as adding remote ICE candidates once the answer SDP is set.
private class SDPObserver implements SdpObserver {
@Override public void onCreateSuccess(final SessionDescription origSdp) {
//abortUnless(localSdp == null, "multiple SDP create?!?");
final SessionDescription sdp = new SessionDescription(
origSdp.type, preferISAC(origSdp.description));
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
Log.d(TAG, "onSuccess(Create SDP)");
peerConnection.setLocalDescription(sdpObserver, sdp);
try {
JSONObject data = new JSONObject("{'target':'call','version':'1.0'}");
String type = sdp.type.toString().toLowerCase();
data.put("signalType", type);
data.put("to", endpoint.getEndpointID());
data.put("sessionId", sessionID);
data.put("signalId", Respoke.makeGUID());
JSONObject sdpJSON = new JSONObject();
sdpJSON.put("sdp", sdp.description);
sdpJSON.put("type", type);
data.put("sessionDescription", sdpJSON);
signalingChannel.sendSignal(data, endpoint.getEndpointID(), new RespokeTaskCompletionDelegate() {
@Override
public void onSuccess() {
// Do nothing
}
@Override
public void onError(String errorMessage) {
delegate.onError(errorMessage, RespokeCall.this);
}
});
} catch (JSONException e) {
delegate.onError("Error encoding sdp", RespokeCall.this);
}
}
});
}
@Override public void onSetSuccess() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
Log.d(TAG, "onSuccess(Set SDP)");
if (caller) {
if (peerConnection.getRemoteDescription() != null) {
// We've set our local offer and received & set the remote
// answer, so drain candidates.
waitingForAnswer = false;
drainRemoteCandidates();
drainLocalCandidates();
}
} else {
if (peerConnection.getLocalDescription() == null) {
// We just set the remote offer, time to create our answer.
MediaConstraints sdpMediaConstraints = new MediaConstraints();
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
"OfferToReceiveAudio", "true"));
sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
"OfferToReceiveVideo", "true"));
peerConnection.createAnswer(SDPObserver.this, sdpMediaConstraints);
} else {
drainRemoteCandidates();
}
}
}
});
}
@Override public void onCreateFailure(final String error) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
delegate.onError("createSDP error: " + error, RespokeCall.this);
}
});
}
@Override public void onSetFailure(final String error) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
delegate.onError("setSDP error: " + error, RespokeCall.this);
}
});
}
private void drainRemoteCandidates() {
for (IceCandidate candidate : queuedRemoteCandidates) {
peerConnection.addIceCandidate(candidate);
}
queuedRemoteCandidates = null;
}
private void drainLocalCandidates() {
for (IceCandidate candidate : queuedLocalCandidates) {
sendLocalCandidate(candidate);
}
}
}
private void sendLocalCandidate(IceCandidate candidate) {
JSONObject candidateDict = new JSONObject();
try {
candidateDict.put("sdpMLineIndex", candidate.sdpMLineIndex);
candidateDict.put("sdpMid", candidate.sdpMid);
candidateDict.put("candidate", candidate.sdp);
JSONArray candidateArray = new JSONArray();
candidateArray.put(candidateDict);
JSONObject signalData = new JSONObject("{'signalType':'iceCandidates','target':'call','version':'1.0'}");
signalData.put("to", endpoint.getEndpointID());
signalData.put("toConnection", toConnection);
signalData.put("sessionId", sessionID);
signalData.put("signalId", Respoke.makeGUID());
signalData.put("iceCandidates", candidateArray);
signalingChannel.sendSignal(signalData, endpoint.getEndpointID(), new RespokeTaskCompletionDelegate() {
@Override
public void onSuccess() {
// Do nothing
}
@Override
public void onError(String errorMessage) {
delegate.onError(errorMessage, RespokeCall.this);
}
});
} catch (JSONException e) {
delegate.onError("Unable to encode local candidate", this);
}
}
// Mangle SDP to prefer ISAC/16000 over any other audio codec.
private static String preferISAC(String sdpDescription) {
String[] lines = sdpDescription.split("\r\n");
int mLineIndex = -1;
String isac16kRtpMap = null;
Pattern isac16kPattern =
Pattern.compile("^a=rtpmap:(\\d+) ISAC/16000[\r]?$");
for (int i = 0;
(i < lines.length) && (mLineIndex == -1 || isac16kRtpMap == null);
++i) {
if (lines[i].startsWith("m=audio ")) {
mLineIndex = i;
continue;
}
Matcher isac16kMatcher = isac16kPattern.matcher(lines[i]);
if (isac16kMatcher.matches()) {
isac16kRtpMap = isac16kMatcher.group(1);
continue;
}
}
if (mLineIndex == -1) {
//Log.d(TAG, "No m=audio line, so can't prefer iSAC");
return sdpDescription;
}
if (isac16kRtpMap == null) {
//Log.d(TAG, "No ISAC/16000 line, so can't prefer iSAC");
return sdpDescription;
}
String[] origMLineParts = lines[mLineIndex].split(" ");
StringBuilder newMLine = new StringBuilder();
int origPartIndex = 0;
// Format is: m=<media> <port> <proto> <fmt> ...
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(origMLineParts[origPartIndex++]).append(" ");
newMLine.append(isac16kRtpMap);
for (; origPartIndex < origMLineParts.length; ++origPartIndex) {
if (!origMLineParts[origPartIndex].equals(isac16kRtpMap)) {
newMLine.append(" ").append(origMLineParts[origPartIndex]);
}
}
lines[mLineIndex] = newMLine.toString();
StringBuilder newSdpDescription = new StringBuilder();
for (String line : lines) {
newSdpDescription.append(line).append("\r\n");
}
return newSdpDescription.toString();
}
}
|
package com.distelli.europa.db;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import com.distelli.europa.models.EuropaSetting;
import com.distelli.europa.models.EuropaSettingType;
import com.distelli.jackson.transform.TransformModule;
import com.distelli.persistence.AttrDescription;
import com.distelli.persistence.AttrType;
import com.distelli.persistence.ConvertMarker;
import com.distelli.persistence.Index;
import com.distelli.persistence.IndexDescription;
import com.distelli.persistence.IndexType;
import com.distelli.persistence.PageIterator;
import com.distelli.persistence.TableDescription;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Singleton;
import com.distelli.europa.Constants;
import com.distelli.europa.db.BaseDb;
import lombok.extern.log4j.Log4j;
@Log4j
@Singleton
public class SettingsDb extends BaseDb
{
private Index<EuropaSetting> _main;
private final ObjectMapper _om = new ObjectMapper();
public static TableDescription getTableDescription() {
return TableDescription.builder()
.tableName("settings")
.indexes(Arrays.asList(IndexDescription.builder()
.hashKey(attr("dom", AttrType.STR))
.rangeKey(attr("rk", AttrType.STR))
.indexType(IndexType.MAIN_INDEX)
.readCapacity(1L)
.writeCapacity(1L)
.build()))
.build();
}
private TransformModule createTransforms(TransformModule module) {
module.createTransform(EuropaSetting.class)
.put("dom", String.class,
(setting) -> setting.getDomain().toLowerCase(),
(setting, dom) -> setting.setDomain(dom))
.put("rk", String.class,
(setting) -> toRK(setting))
.put("key", String.class, "key")
.put("val", String.class, "value")
.put("type", EuropaSettingType.class, "type");
return module;
}
private static String toRK(EuropaSetting setting) {
return toRK(setting.getType(), setting.getKey());
}
private static String toRK(EuropaSettingType type, String key) {
return String.format("%s:%s",type, key);
}
@Inject
public SettingsDb(Index.Factory indexFactory,
ConvertMarker.Factory convertMarkerFactory)
{
_om.registerModule(createTransforms(new TransformModule()));
_main = indexFactory.create(EuropaSetting.class)
.withTableDescription(getTableDescription())
.withConvertValue(_om::convertValue)
.build();
}
public void save(EuropaSetting europaSetting) {
if ( null == europaSetting.getDomain() || europaSetting.getDomain().trim().isEmpty()) {
throw new IllegalArgumentException("domain must be non-null and non-empty");
}
if ( null == europaSetting.getType() ) {
throw new IllegalArgumentException("type must be non-null");
}
if ( null == europaSetting.getKey() || europaSetting.getKey().trim().isEmpty()) {
throw new IllegalArgumentException("key must be non-null and non-empty");
}
_main.putItem(europaSetting);
}
public void delete(String domain, EuropaSettingType type, String key) {
_main.deleteItem(domain, toRK(type, key));
}
public List<EuropaSetting> listRootSettingsByType(EuropaSettingType type) {
return listSettingsByType(Constants.DOMAIN_ZERO, type);
}
public List<EuropaSetting> listSettingsByType(String domain, EuropaSettingType type) {
return _main.queryItems(domain.toLowerCase(), new PageIterator().pageSize(1000))
.beginsWith(toRK(type, null))
.list();
}
}
|
package team353;
import battlecode.common.*;
import java.util.*;
public class RobotPlayer {
public static class smuConstants {
public static int roundToLaunchAttack = 1600;
public static int roundToDefendTowers = 500;
public static int roundToFormSupplyConvoy = 1200; // roundToBuildSOLDIERS;
public static int RADIUS_FOR_SUPPLY_CONVOY = 2;
public static int numTowersRemainingToAttackHQ = 2;
public static double weightExponentMagic = 0.3;
public static double weightScaleMagic = 0.8;
public static int currentOreGoal = 100;
public static double percentBeaversToGoToSecondBase = 0.4;
// Defence
public static int NUM_TOWER_PROTECTORS = 4;
public static int NUM_HOLE_PROTECTORS = 3;
public static int PROTECT_OTHERS_RANGE = 15;
public static int DISTANCE_TO_START_PROTECTING_SQUARED = 200;
// Idle States
public static MapLocation defenseRallyPoint;
public static int PROTECT_HOLE = 1;
public static int PROTECT_TOWER = 2;
// Supply
public static int NUM_ROUNDS_TO_KEEP_SUPPLIED = 20;
// Contain
public static int CLOCKWISE = 0;
public static int COUNTERCLOCKWISE = 1;
public static int CURRENTLY_BEING_CONTAINED = 1;
public static int NOT_CURRENTLY_BEING_CONTAINED = 2;
// Strategies
/*
* NOTE: If changing these values, alter smuTeamMemoryIndices accordingly
*/
public static int STRATEGY_DRONE_CONTAIN = 1;
public static int STRATEGY_TANKS_AND_SOLDIERS = 2;
}
public static class smuIndices {
public static int RALLY_POINT_X = 0;
public static int RALLY_POINT_Y = 1;
public static int TOWER_SOS_X = 2;
public static int TOWER_SOS_Y = 3;
public static int TOWER_SOS_ROUND_SENT = 4;
//Economy
public static int freqQueue = 11;
public static int STRATEGY = 19;
public static int HQ_BEING_CONTAINED = 20;
public static int HQ_BEING_CONTAINED_BY = 21;
//Strategy broadcasts use frequencies 1000 through 3200!
//TODO
public static final int channelAEROSPACELAB = 1100;
public static final int channelBARRACKS = 1200;
public static final int channelBASHER = 1300;
public static final int channelBEAVER = 1400;
public static final int channelCOMMANDER = 1500;
public static final int channelCOMPUTER = 1600;
public static final int channelDRONE = 1700;
public static final int channelHANDWASHSTATION = 1800;
public static final int channelHELIPAD = 1900;
public static final int channelHQ = 2000;
public static final int channelLAUNCHER = 2100;
public static final int channelMINER = 2200;
public static final int channelMINERFACTORY = 2300;
public static final int channelMISSILE = 2400;
public static final int channelSOLDIER = 2500;
public static final int channelSUPPLYDEPOT = 2600;
public static final int channelTANK = 2700;
public static final int channelTANKFACTORY = 2800;
public static final int channelTECHNOLOGYINSTITUTE = 2900;
public static final int channelTOWER = 3000;
public static final int channelTRAININGFIELD = 3100;
public static final int[] channel = new int[] {0, channelAEROSPACELAB, channelBARRACKS, channelBASHER, channelBEAVER, channelCOMMANDER,
channelCOMPUTER, channelDRONE, channelHANDWASHSTATION, channelHELIPAD, channelHQ, channelLAUNCHER, channelMINER,
channelMINERFACTORY, channelMISSILE, channelSOLDIER, channelSUPPLYDEPOT, channelTANK, channelTANKFACTORY,
channelTECHNOLOGYINSTITUTE, channelTOWER, channelTRAININGFIELD};
public static int TOWER_HOLES_BEGIN = 4000;
}
public static class smuTeamMemoryIndices {
public static int PREV_MAP_TOWER_THREAT = 0;
public static int PREV_MAP_VOID_TYPE_PERCENT = 1;
public static int NUM_ROUNDS_USING_STRATEGY_BASE = 1;
// Strategies from smuConstants take values 2-7
public static int ROUND_OUR_HQ_ATTACKED = 8;
// Round their HQ attacked?
public static int ROUND_OUR_TOWER_DESTROYED_BASE = 10;
// Base will expand to values 10-16
public static int ROUND_THEIR_TOWER_DESTROYED_BASE = 17;
// Base will expand to values 17-23
// public static int ROUND_STARTED_USING_STRATEGY_BASE = 23;
// // Base will expand to values 23-29
}
public static void run(RobotController rc) throws GameActionException {
BaseBot myself;
if (rc.getType() == RobotType.HQ) {
myself = new HQ(rc);
} else if (rc.getType() == RobotType.MINER) {
myself = new Miner(rc);
} else if (rc.getType() == RobotType.MINERFACTORY) {
myself = new Minerfactory(rc);
} else if (rc.getType() == RobotType.BEAVER) {
myself = new Beaver(rc);
} else if (rc.getType() == RobotType.BARRACKS) {
myself = new Barracks(rc);
} else if (rc.getType() == RobotType.SOLDIER) {
myself = new Soldier(rc);
} else if (rc.getType() == RobotType.BASHER) {
myself = new Basher(rc);
} else if (rc.getType() == RobotType.HELIPAD) {
myself = new Helipad(rc);
} else if (rc.getType() == RobotType.DRONE) {
myself = new Drone(rc);
} else if (rc.getType() == RobotType.TOWER) {
myself = new Tower(rc);
} else if (rc.getType() == RobotType.SUPPLYDEPOT) {
myself = new Supplydepot(rc);
} else if (rc.getType() == RobotType.HANDWASHSTATION) {
myself = new Handwashstation(rc);
} else if (rc.getType() == RobotType.TANKFACTORY) {
myself = new Tankfactory(rc);
} else if (rc.getType() == RobotType.TANK) {
myself = new Tank(rc);
} else if (rc.getType() == RobotType.AEROSPACELAB) {
myself = new Aerospacelab(rc);
} else if (rc.getType() == RobotType.LAUNCHER) {
myself = new Launcher(rc);
} else if (rc.getType() == RobotType.MISSILE) {
myself = new Missile(rc);
} else {
myself = new BaseBot(rc);
}
while (true) {
try {
myself.go();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static class BaseBot {
protected RobotController rc;
protected MapLocation myHQ, theirHQ;
protected Team myTeam, theirTeam;
protected int myRange;
protected RobotType myType;
static Random rand;
protected double shouldProtectTower;
public BaseBot(RobotController rc) {
this.rc = rc;
this.myHQ = rc.senseHQLocation();
this.theirHQ = rc.senseEnemyHQLocation();
this.myTeam = rc.getTeam();
this.theirTeam = this.myTeam.opponent();
this.myType = rc.getType();
this.myRange = myType.attackRadiusSquared;
rand = new Random(rc.getID());
shouldProtectTower = rand.nextDouble();
}
public void defendTowerSOS() throws GameActionException {
if (shouldProtectTower > 0.5) return;
int towerX = rc.readBroadcast(smuIndices.TOWER_SOS_X);
int towerY = rc.readBroadcast(smuIndices.TOWER_SOS_Y);
if (towerX != 0 && towerY != 0) {
goToLocation(new MapLocation(towerX, towerY));
}
}
public int getDistanceSquared(MapLocation A, MapLocation B){
return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
}
public int getDistanceSquared(MapLocation A){
MapLocation B = rc.getLocation();
return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
}
public Direction[] getDirectionsToward(MapLocation dest) {
Direction toDest = rc.getLocation().directionTo(dest);
Direction[] dirs = new Direction[5];
dirs[0] = toDest;
if (rand.nextDouble() < 0.5){
dirs[1] = toDest.rotateLeft();
dirs[2] = toDest.rotateRight();
} else {
dirs[2] = toDest.rotateLeft();
dirs[1] = toDest.rotateRight();
}
if (rand.nextDouble() < 0.5){
dirs[3] = toDest.rotateLeft().rotateLeft();
dirs[4] = toDest.rotateRight().rotateRight();
} else {
dirs[4] = toDest.rotateLeft().rotateLeft();
dirs[3] = toDest.rotateRight().rotateRight();
}
return dirs;
}
public Direction[] getDirectionsAway(MapLocation dest) {
Direction toDest = rc.getLocation().directionTo(dest).opposite();
Direction[] dirs = new Direction[5];
dirs[0] = toDest;
if (rand.nextDouble() < 0.5){
dirs[1] = toDest.rotateLeft();
dirs[2] = toDest.rotateRight();
} else {
dirs[2] = toDest.rotateLeft();
dirs[1] = toDest.rotateRight();
}
if (rand.nextDouble() < 0.5){
dirs[3] = toDest.rotateLeft().rotateLeft();
dirs[4] = toDest.rotateRight().rotateRight();
} else {
dirs[4] = toDest.rotateLeft().rotateLeft();
dirs[3] = toDest.rotateRight().rotateRight();
}
return dirs;
}
public Direction getMoveDir(MapLocation dest) {
Direction[] dirs = getDirectionsToward(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
public Direction getMoveDirAway(MapLocation dest) {
Direction[] dirs = getDirectionsAway(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
//Will return a single direction for spawning. (Uses getDirectionsToward())
public Direction getSpawnDir(RobotType type) {
Direction[] arrayOfDirections = new Direction[]{Direction.EAST, Direction.NORTH, Direction.NORTH_EAST, Direction.NORTH_WEST,
Direction.SOUTH, Direction.SOUTH_EAST, Direction.SOUTH_WEST, Direction.WEST};
// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(arrayOfDirections));
for (Direction d : arrayOfDirections) {
if (rc.canSpawn(d, type)) {
return d;
}
}
return null;
}
//Will return a single direction for building. (Uses getDirectionsToward())
public Direction getBuildDir(RobotType type) {
Direction[] dirs = getDirectionsToward(this.theirHQ);
for (Direction d : dirs) {
if (rc.canBuild(d, type)) {
return d;
}
}
dirs = getDirectionsToward(this.myHQ);
for (Direction d : dirs) {
if (rc.canBuild(d, type)) {
return d;
} else {
// //System.out.println("Could not find valid build location!");
}
}
return null;
}
public RobotInfo[] getAllies() {
RobotInfo[] allies = rc.senseNearbyRobots(Integer.MAX_VALUE, myTeam);
return allies;
}
public RobotInfo[] getEnemiesInAttackingRange() {
RobotInfo[] enemies = rc.senseNearbyRobots(myRange, theirTeam);
return enemies;
}
public Direction getDirOfLauncherTarget() {
int startingByteCode = Clock.getBytecodeNum();
MapLocation myLocation = rc.getLocation();
Direction[] targetDirections = getDirectionsToward(theirHQ);
MapLocation[] targets = new MapLocation[5];
for (int i=0; i<targetDirections.length; i++){
targets[i] = myLocation.add(targetDirections[i], 3);
}
for (int j = 0; j < targets.length; j++) {
if (Clock.getBytecodesLeft() > 500) {
int teammates = 0;
MapLocation targetCenter = targets[j];
RobotInfo[] allRobotsInTargetArea = rc.senseNearbyRobots(
targetCenter, 15, null);
for (RobotInfo robot : allRobotsInTargetArea) {
if (robot.team == myTeam)
teammates++;
}
if (allRobotsInTargetArea.length >= 2 * teammates) {
// //System.out.println("getPositionOfLauncherTarget [bytecode]:" + (Clock.getBytecodeNum()-startingByteCode));
return myLocation.directionTo(targetCenter);
}
}
}
// System.out.println("FAILED getPositionOfLauncherTarget [bytecode]:" + (Clock.getBytecodeNum()-startingByteCode));
return null;
}
public void attackLeastHealthEnemy(RobotInfo[] enemies) throws GameActionException {
if (enemies.length == 0) {
return;
}
double minEnergon = Double.MAX_VALUE;
MapLocation toAttack = null;
for (RobotInfo info : enemies) {
if (info.health < minEnergon) {
toAttack = info.location;
minEnergon = info.health;
}
}
if (toAttack != null) {
rc.attackLocation(toAttack);
}
}
public void attackLeastHealthEnemyInRange() throws GameActionException {
RobotInfo[] enemies = getEnemiesInAttackingRange();
if (enemies.length > 0) {
if (rc.isWeaponReady()) {
attackLeastHealthEnemy(enemies);
}
}
}
public void fleeMissile() throws GameActionException {
RobotInfo[] enemies = rc.senseNearbyRobots(myType.sensorRadiusSquared, theirTeam);
for (RobotInfo enemy : enemies) {
if (enemy.type == RobotType.MISSILE) {
Direction enemyDir = rc.getLocation().directionTo(enemy.location);
Direction moveDir = enemyDir.opposite();
for(int i = 0; i<8; i++) {
if (rc.canMove(moveDir) && !moveDir.equals(enemyDir)) {
rc.move(moveDir);
break;
}
moveDir = moveDir.rotateLeft();
}
}
}
}
public void moveToRallyPoint() throws GameActionException {
if (rc.isCoreReady()) {
int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X);
int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y);
MapLocation rallyPoint = new MapLocation(rallyX, rallyY);
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack &&
rc.getLocation().distanceSquaredTo(rallyPoint) > 8 + Clock.getRoundNum() / 100) {
moveOptimally(getDirectionsToward(rallyPoint));
} else {
if (rc.getLocation().distanceSquaredTo(rallyPoint) > 40){
moveOptimally(getDirectionsToward(rallyPoint));
} else {
Direction newDir = getMoveDir(rallyPoint);
if (newDir != null && rc.canMove(newDir)) {
rc.move(newDir);
}
}
}
}
}
//Returns the current rally point MapLocation
public MapLocation getRallyPoint() throws GameActionException {
int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X);
int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y);
MapLocation rallyPoint = new MapLocation(rallyX, rallyY);
return rallyPoint;
}
public void moveOptimally(Direction currentDirection) throws GameActionException {
//TODO check safety
if (currentDirection != null) {
MapLocation tileInFront = rc.getLocation().add(currentDirection);
//check that we are not facing off the edge of the map
TerrainTile terrainTileInFront = rc.senseTerrainTile(tileInFront);
if(!isLocationSafe(tileInFront) ||
!rc.isPathable(myType, tileInFront) ||
terrainTileInFront == TerrainTile.OFF_MAP ||
(myType != RobotType.DRONE && terrainTileInFront!=TerrainTile.NORMAL)){
return;
}else{
//try to move in the currentDirection direction
if(currentDirection != null && rc.isCoreReady() && rc.canMove(currentDirection)){
rc.move(currentDirection);
return;
}
}
}
}
//Moves a random safe direction from input array
public void moveOptimally(Direction[] optimalDirections) throws GameActionException {
//TODO check safety
if (optimalDirections != null) {
boolean lookingForDirection = true;
int attemptForDirection = 0;
while(lookingForDirection){
Direction currentDirection = optimalDirections[attemptForDirection];
//Direction currentDirection = optimalDirections[(int) (rand.nextDouble()*optimalDirections.length)];
MapLocation tileInFront = rc.getLocation().add(currentDirection);
//check that we are not facing off the edge of the map
TerrainTile terrainTileInFront = rc.senseTerrainTile(tileInFront);
if(!isLocationSafe(tileInFront) ||
!rc.isPathable(myType, tileInFront) ||
terrainTileInFront == TerrainTile.OFF_MAP ||
(myType != RobotType.DRONE && terrainTileInFront!=TerrainTile.NORMAL)){
//currentDirection = currentDirection.rotateLeft();
attemptForDirection++;
if (attemptForDirection == optimalDirections.length) {
// //System.out.println("No suitable direction found!");
return;
}
}else{
//try to move in the currentDirection direction
if(currentDirection != null && rc.isCoreReady() && rc.canMove(currentDirection)){
rc.move(currentDirection);
lookingForDirection = false;
return;
}
}
}
}
}
//Gets optimal directions and then calls moveOptimally() with those directions.
public void moveOptimally() throws GameActionException {
Direction[] optimalDirections = getOptimalDirections();
if (optimalDirections != null) {
moveOptimally(optimalDirections);
}
}
//TODO Finish
public Direction[] getOptimalDirections() throws GameActionException {
// The switch statement should result in an array of directions that make sense
//for the RobotType. Safety is considered in moveOptimally()
RobotType currentRobotType = rc.getType();
Direction[] optimalDirections = Direction.values();
Collections.shuffle(Arrays.asList(optimalDirections));
switch(currentRobotType){
case BASHER:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case BEAVER:
if (getDistanceSquared(this.myHQ) < 50){
optimalDirections = getDirectionsAway(this.myHQ);
}
break;
case COMMANDER:
break;
case COMPUTER:
break;
case DRONE:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case LAUNCHER:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case MINER:
if (getDistanceSquared(this.myHQ) < 50){
optimalDirections = getDirectionsAway(this.myHQ);
}
break;
case MISSILE:
break;
case SOLDIER:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case TANK:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
default:
} //Done RobotType specific actions.
return optimalDirections;
}
//Spawns or Queues the unit if it is needed
public boolean tryToSpawn(RobotType spawnType) throws GameActionException{
int round = Clock.getRoundNum();
double ore = rc.getTeamOre();
int spawnTypeInt = RobotTypeToInt(spawnType);
int spawnQueue = rc.readBroadcast(smuIndices.freqQueue);
int strategy = rc.readBroadcast(smuIndices.STRATEGY);
int currentAmount = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+0);
int desiredAmount = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+1);
int roundToBeginSpawning = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+2);
//Check if we actually need anymore spawnType units
if (round > roundToBeginSpawning){
if (currentAmount < desiredAmount ||
(strategy == smuConstants.STRATEGY_DRONE_CONTAIN && spawnType == RobotType.DRONE) ||
(strategy == smuConstants.STRATEGY_TANKS_AND_SOLDIERS && spawnType == RobotType.TANK) ||
(strategy == smuConstants.STRATEGY_TANKS_AND_SOLDIERS && spawnType == RobotType.SOLDIER)
){
if(ore > myType.oreCost){
if (spawnUnit(spawnType)) return true;
} else {
//Add spawnType to queue
if (spawnQueue == 0){
rc.broadcast(smuIndices.freqQueue, spawnTypeInt);
}
return false;
}
}
}
return false;
}
//Spawns unit based on calling type. Performs all checks.
public boolean spawnOptimally() throws GameActionException {
if (rc.isCoreReady()){
int spawnQueue = rc.readBroadcast(smuIndices.freqQueue);
switch(myType){
case BARRACKS:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.SOLDIER)){
if (tryToSpawn(RobotType.SOLDIER)) return true;
}
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BASHER)){
if (tryToSpawn(RobotType.BASHER)) return true;
}
break;
case HQ:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BEAVER)){
if (tryToSpawn(RobotType.BEAVER)) return true;
}
break;
case HELIPAD:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.DRONE)){
if (tryToSpawn(RobotType.DRONE)) return true;
}
break;
case AEROSPACELAB:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.LAUNCHER)){
if (tryToSpawn(RobotType.LAUNCHER)) return true;
}
break;
case MINERFACTORY:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.MINER)){
if (tryToSpawn(RobotType.MINER)) return true;
}
break;
case TANKFACTORY:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.TANK)){
if (tryToSpawn(RobotType.TANK)) return true;
}
break;
case TECHNOLOGYINSTITUTE:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMPUTER)){
if (tryToSpawn(RobotType.COMPUTER)) return true;
}
break;
case TRAININGFIELD:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMMANDER)){
if (tryToSpawn(RobotType.COMMANDER)) return true;
}
break;
default:
// System.out.println("ERROR: No building type match found in spawnOptimally()!");
return false;
}
}//isCoreReady
return false;
}
//Gets direction, checks delays, and spawns unit
public boolean spawnUnit(RobotType spawnType) {
//Get a direction and then actually spawn the unit.
Direction randomDir = getSpawnDir(spawnType);
if(rc.isCoreReady() && randomDir != null){
try {
if (rc.canSpawn(randomDir, spawnType)) {
rc.spawn(randomDir, spawnType);
if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == spawnType) {
rc.broadcast(smuIndices.freqQueue, 0);
}
incrementCount(spawnType);
return true;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
return false;
}
//Spawns unit based on calling type. Performs all checks.
public void buildOptimally() throws GameActionException {
int round = Clock.getRoundNum();
double ore = rc.getTeamOre();
boolean buildingsOutrankUnits = true;
int queue = rc.readBroadcast(smuIndices.freqQueue);
RobotType[] arrayOfStructures = new RobotType[] {RobotType.AEROSPACELAB,
RobotType.BARRACKS, RobotType.HANDWASHSTATION, RobotType.HELIPAD, RobotType.HQ,
RobotType.MINERFACTORY, RobotType.SUPPLYDEPOT, RobotType.TANKFACTORY,
RobotType.TECHNOLOGYINSTITUTE, RobotType.TOWER, RobotType.TRAININGFIELD};
//If there is something in the queue and we can not replace it, then return
if (queue != 0 && !buildingsOutrankUnits){
// System.out.println("Queue full, can't outrank");
return;
}
//Check if there is a building in queue
if (Arrays.asList(arrayOfStructures).contains(IntToRobotType(queue))) {
//Build it if we can afford it
if (ore > IntToRobotType(queue).oreCost) {
// System.out.println("INFO: Satisfying queue. ("+IntToRobotType(queue).name()+")");
buildUnit(IntToRobotType(queue));
}
//Return either way, we can't replace buildings in the queue
return;
}
//Loop over structures and build or queue any needed ones
for (RobotType structure : arrayOfStructures) {
int intStructure = RobotTypeToInt(structure);
double weightOfStructure = getWeightOfRobotType(IntToRobotType(intStructure));
if (weightOfStructure == 1.0){
if (ore > IntToRobotType(intStructure).oreCost){
buildUnit(IntToRobotType(intStructure));
// System.out.println("Tried to build "+ IntToRobotType(intStructure));
} else {
rc.broadcast(smuIndices.freqQueue, intStructure);
// System.out.println("Scheduled a " + IntToRobotType(intStructure).name() +
// ". Need " + (IntToRobotType(intStructure).oreCost-ore) + " more ore.");
}
return;
}
}//end loop of structures
}
//Gets direction, checks delays, and builds unit
public boolean buildUnit(RobotType buildType) {
//Get a direction and then actually build the unit.
Direction randomDir = getBuildDir(buildType);
if(rc.isCoreReady() && randomDir != null){
try {
if (rc.canBuild(randomDir, buildType)) {
rc.build(randomDir, buildType);
if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == buildType) {
rc.broadcast(smuIndices.freqQueue, 0);
}
incrementCount(buildType);
return true;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
return false;
}
//Increment the currentAmount of a RobotType
public void incrementCount(RobotType type) throws GameActionException {
int intType = RobotTypeToInt(type);
int currentAmount = rc.readBroadcast(smuIndices.channel[intType]+0);
rc.broadcast(smuIndices.channel[intType+0], currentAmount+1);
}
public void transferSupplies() throws GameActionException {
double lowestSupply = rc.getSupplyLevel();
if (lowestSupply == 0) {
return;
}
int roundStart = Clock.getRoundNum();
final MapLocation myLocation = rc.getLocation();
RobotInfo[] nearbyAllies = rc.senseNearbyRobots(myLocation,GameConstants.SUPPLY_TRANSFER_RADIUS_SQUARED,rc.getTeam());
double transferAmount = 0;
MapLocation suppliesToThisLocation = null;
for(RobotInfo ri:nearbyAllies){
if (!ri.type.isBuilding && ri.supplyLevel < lowestSupply) {
lowestSupply = ri.supplyLevel;
transferAmount = (rc.getSupplyLevel()-ri.supplyLevel)/2;
suppliesToThisLocation = ri.location;
}
}
if(suppliesToThisLocation!=null){
if (roundStart == Clock.getRoundNum() && transferAmount > 0 && Clock.getBytecodesLeft() > 550) {
try {
rc.transferSupplies((int)transferAmount, suppliesToThisLocation);
} catch(GameActionException gax) {
gax.printStackTrace();
}
}
}
}
// true, I'm in the convoy or going to be
// false, no place in the convoy for me
public boolean formSupplyConvoy() {
try {
if (rc.readBroadcast(smuIndices.STRATEGY) == smuConstants.STRATEGY_DRONE_CONTAIN) {
return false;
}
} catch (GameActionException e1) {
e1.printStackTrace();
}
Direction directionForChain = getSupplyConvoyDirection(myHQ);
RobotInfo minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, myHQ, directionForChain);
if (minerAtEdge == null){
goToLocation(myHQ.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY));
return true;
} else if (minerAtEdge.ID == rc.getID()) {
return true;
}
RobotInfo previousMiner = null;
try {
while ((minerAtEdge != null || !minerAtEdge.type.isBuilding) && minerAtEdge.location.distanceSquaredTo(getRallyPoint()) > 4) {
directionForChain = getSupplyConvoyDirection(minerAtEdge.location);
previousMiner = minerAtEdge;
minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, minerAtEdge.location, directionForChain);
if (minerAtEdge == null) {
goToLocation(previousMiner.location.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY));
return true;
} else if (minerAtEdge.ID == rc.getID()) {
return true;
}
}
} catch (GameActionException e) {
e.printStackTrace();
}
return false;
}
public Direction getSupplyConvoyDirection(MapLocation startLocation) {
Direction directionForChain = myHQ.directionTo(theirHQ);
MapLocation locationToGo = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL && rc.canSenseLocation(locationToGo)) {
RobotInfo robotInDirection;
try {
robotInDirection = rc.senseRobotAtLocation(locationToGo);
if (robotInDirection == null || !robotInDirection.type.isBuilding) {
return directionForChain;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
Direction[] directions = {Direction.NORTH, Direction.NORTH_EAST, Direction.EAST, Direction.SOUTH_EAST, Direction.SOUTH, Direction.SOUTH_WEST, Direction.WEST, Direction.NORTH_WEST};
for (int i = 0; i < directions.length; i++) {
locationToGo = startLocation.add(directions[i], smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (directions[i] != directionForChain && directions[i] != Direction.OMNI && directions[i] != Direction.NONE
&& rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL) {
RobotInfo robotInDirection = null;
try {
if (rc.canSenseLocation(locationToGo)) robotInDirection = rc.senseRobotAtLocation(locationToGo);
if (robotInDirection == null || !robotInDirection.type.isBuilding) {
return directions[i];
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
}
return Direction.NONE;
}
public RobotInfo getUnitAtEdgeOfSupplyRangeOf(RobotType unitType, MapLocation startLocation, Direction directionForChain) {
MapLocation locationInChain = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (rc.canSenseLocation(locationInChain)) {
try {
return rc.senseRobotAtLocation(locationInChain);
} catch (GameActionException e) {
e.printStackTrace();
}
}
return null;
}
public MapLocation getSecondBaseLocation() {
Direction directionToTheirHQ = myHQ.directionTo(theirHQ);
MapLocation secondBase = null;
if (directionToTheirHQ == Direction.EAST || directionToTheirHQ == Direction.WEST) {
secondBase = getSecondBaseLocationInDirections(Direction.NORTH, Direction.SOUTH);
} else if (directionToTheirHQ == Direction.NORTH || directionToTheirHQ == Direction.SOUTH) {
secondBase = getSecondBaseLocationInDirections(Direction.EAST, Direction.WEST);
} else {
Direction[] directions = breakdownDirection(directionToTheirHQ);
secondBase = getSecondBaseLocationInDirections(directions[0], directions[1]);
}
if (secondBase != null) {
secondBase = secondBase.add(myHQ.directionTo(secondBase), 4);
}
return secondBase;
}
public MapLocation getSecondBaseLocationInDirections(Direction dir1, Direction dir2) {
MapLocation towers[] = rc.senseTowerLocations();
int maxDistance = Integer.MIN_VALUE;
int maxDistanceIndex = -1;
Direction dirToEnemy = myHQ.directionTo(theirHQ);
Direction dir1left = dir1.rotateLeft();
Direction dir1right = dir1.rotateRight();
Direction dir2left = dir2.rotateLeft();
Direction dir2right = dir2.rotateRight();
for (int i = 0; i<towers.length; i++) {
Direction dirToTower = myHQ.directionTo(towers[i]);
if (dirToTower == dir1 || dirToTower == dir2
|| (dir1left != dirToEnemy && dirToTower == dir1left)
|| (dir1right != dirToEnemy && dirToTower == dir1right)
|| (dir2left != dirToEnemy && dirToTower == dir2left)
|| (dir2right != dirToEnemy && dirToTower == dir2right)) {
int distanceToTower = myHQ.distanceSquaredTo(towers[i]);
if (distanceToTower > maxDistance) {
maxDistance = distanceToTower;
maxDistanceIndex = i;
}
}
}
if (maxDistanceIndex != -1) {
return towers[maxDistanceIndex];
}
return null;
}
public void beginningOfTurn() {
if (rc.senseEnemyHQLocation() != null) {
this.theirHQ = rc.senseEnemyHQLocation();
}
}
public void endOfTurn() {
}
public void go() throws GameActionException {
beginningOfTurn();
execute();
endOfTurn();
}
public void execute() throws GameActionException {
rc.yield();
}
public void supplyAndYield() throws GameActionException {
transferSupplies();
rc.yield();
}
public int myContainDirection = smuConstants.CLOCKWISE;
public MapLocation myContainPreviousLocation;
public void contain() {
MapLocation enemyHQ = rc.senseEnemyHQLocation();
MapLocation[] enemyTowers = rc.senseEnemyTowerLocations();
MapLocation myLocation = rc.getLocation();
int radiusFromHQ = 24;
if (enemyTowers.length >= 2) {
radiusFromHQ = 35;
}
MapLocation toBeContained = null;
RobotInfo[] enemies = rc.senseNearbyRobots(myType.sensorRadiusSquared, theirTeam);
for (RobotInfo enemy : enemies) {
if (myLocation.directionTo(enemy.location) != myLocation.directionTo(enemyHQ)) {
toBeContained = enemy.location;
break;
}
}
boolean attackingEnemy = false;
if (toBeContained != null) {
Direction directionToGo = myLocation.directionTo(toBeContained);
if (isLocationSafe(myLocation.add(directionToGo))) {
attackingEnemy = true;
goToLocation(myLocation.add(directionToGo));
}
}
if (!attackingEnemy && myLocation.distanceSquaredTo(enemyHQ) > radiusFromHQ + 3) {
// move towards the HQ
try {
RobotInfo[] nearbyTeammates = rc.senseNearbyRobots(4, myTeam);
int numAttackers = 0;
for (RobotInfo teammate : nearbyTeammates) {
if (!teammate.type.isBuilding && teammate.type != RobotType.MINER && teammate.type != RobotType.BEAVER) numAttackers++;
}
if (numAttackers >= getNumAttackersToContain()) {
moveOptimally();
}
} catch (GameActionException e) {
e.printStackTrace();
}
} else {
MapLocation locationToGo = null;
Direction directionToGo = null;
if (myContainDirection == smuConstants.CLOCKWISE) {
directionToGo = getClockwiseDirection(myLocation, enemyHQ);
} else {
directionToGo = getCounterClockwiseDirection(myLocation, enemyHQ);
}
locationToGo = myLocation.add(directionToGo);
if (rc.isPathable(myType, locationToGo)) {
if (isLocationSafe(locationToGo)) {
goToLocation(locationToGo);
} else {
Direction[] directions = breakdownDirection(directionToGo);
for (int i = 0; i < directions.length; i++) {
locationToGo = myLocation.add(directions[i]);
if (isLocationSafe(locationToGo)) {
goToLocation(locationToGo);
myContainPreviousLocation = myLocation;
return;
}
}
}
} else if (myContainPreviousLocation.equals(myLocation)){
if (myContainDirection == smuConstants.CLOCKWISE) {
myContainDirection = smuConstants.COUNTERCLOCKWISE;
} else {
myContainDirection = smuConstants.CLOCKWISE;
}
}
}
myContainPreviousLocation = myLocation;
}
public int getNumAttackersToContain() {
if (myType == RobotType.SOLDIER) {
return 2;
} else if (myType == RobotType.TANK) {
return 1;
} else if (myType == RobotType.DRONE) {
return 1;
} else {
return 2;
}
}
public boolean isLocationSafe(MapLocation location) {
int hqAttackRadius = RobotType.HQ.attackRadiusSquared;
if (rc.senseEnemyTowerLocations().length >= 2) hqAttackRadius = 35;
if (location.distanceSquaredTo(theirHQ) > hqAttackRadius) {
for (MapLocation tower : rc.senseEnemyTowerLocations()) {
if (location.distanceSquaredTo(tower) <= RobotType.TOWER.attackRadiusSquared) {
return false;
}
}
return true;
}
return false;
}
//TODO
public void mineOptimally() throws GameActionException {
MapLocation myLocation = rc.getLocation();
boolean debug = false;
// If you are sitting on ore, mine it!
if (rc.senseOre(myLocation) > 0){
if (rc.isCoreReady()){
rc.mine();
}
return;
}
Direction[] arrayOfDirections = new Direction[]{Direction.EAST, Direction.NORTH, Direction.NORTH_EAST, Direction.NORTH_WEST,
Direction.SOUTH, Direction.SOUTH_EAST, Direction.SOUTH_WEST, Direction.WEST};
List<MapLocation> likelyMineSites = new ArrayList<MapLocation>();
int numOfPossibleSites = 0;
//Check all directions for safety, validity, and ore
for (Direction dir : arrayOfDirections){
MapLocation site = myLocation.add(dir);
TerrainTile siteTerrainTile = rc.senseTerrainTile(site);
if(isLocationSafe(site) &&
rc.isPathable(myType, site) &&
siteTerrainTile != TerrainTile.OFF_MAP &&
siteTerrainTile == TerrainTile.NORMAL &&
rc.senseOre(site) > 0.0 &&
theirHQ.distanceSquaredTo(site) > RobotType.HQ.attackRadiusSquared+1){
likelyMineSites.add(site);
numOfPossibleSites++;
}
}
// If we have possible sites, sort them by ore and then check for adjacent miners.
if (numOfPossibleSites > 0) {
MapLocation[] possibleMineSites = likelyMineSites.toArray(new MapLocation[likelyMineSites.size()]);
//Sort possibleMineSites based on ore
Arrays.sort(possibleMineSites, new Comparator<MapLocation>() {
public int compare(MapLocation location1, MapLocation location2) {
double ore1 = 0;
double ore2 = 0;
if (location1 != null) ore1 = rc.senseOre(location1);
if (location2 != null) ore2 = rc.senseOre(location2);
return Double.compare(ore2, ore1); //descending ORE-der... heh heh heh
}
});
// if(debug)System.out.println("#"+possibleMineSites.length+" 0th: "+rc.senseOre(possibleMineSites[0])+" @ "+possibleMineSites[0].toString());
int numAdjacentMiners = 0;
double siteOre;
double siteWeight;
Direction siteDir;
//Get robots in the 5x5 square we are observing
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(8, myTeam);
// if(debug)System.out.println("##"+possibleMineSites.length+" nearbyRobots: "+nearbyRobots.length);
//Check possibleMineSites for adjacencies to other miners
for (int i =0; i < possibleMineSites.length; i++) {
MapLocation site = possibleMineSites[i];
numAdjacentMiners = 0;
// if(debug)System.out.println("###"+possibleMineSites.length+" ith "+possibleMineSites[i].toString()+" nearbyRobots: "+nearbyRobots.length);
for (int j = 0; j < nearbyRobots.length; j++) {
// if(debug)System.out.println("
if (nearbyRobots[j].type == RobotType.MINER
&& site.distanceSquaredTo(nearbyRobots[j].location) <= 2) {
// Another miner is too close
numAdjacentMiners++;
if (numAdjacentMiners >= 2) {
// if(debug)System.out.println("
site = null;
break;
}
}
}//end nearbyRobots
if (site != null){
siteOre = rc.senseOre(site) / 60.0;
siteWeight = siteOre - 0.25*numAdjacentMiners;
siteDir = myLocation.directionTo(site);
double roll = rand.nextDouble();
// if(debug)System.out.println("MINER: rolled "+roll+" against "+siteWeight+" for Dir-"+siteDir.toString());
if (roll < siteWeight){
moveOptimally(siteDir);
return;
}
}
}//end possibleMineSites
wideSearchForOre();
} else {
wideSearchForOre();
}
}
public void wideSearchForOre() throws GameActionException {
boolean debug = false;
// if (debug)System.out.println("WIDESEARCH: Bytecode Remaining: "+Clock.getBytecodesLeft()+" on round "+Clock.getRoundNum());
MapLocation myLocation = rc.getLocation();
MapLocation[] bigSearch = MapLocation.getAllMapLocationsWithinRadiusSq(myLocation, 100);
double maxOre = 0;
double possibleMineSiteOreValue = 0;
MapLocation bestMineSite = null;
for (MapLocation possibleMineSite : bigSearch){
if (rc.canSenseLocation(possibleMineSite)){
possibleMineSiteOreValue = rc.senseOre(possibleMineSite);
if (possibleMineSiteOreValue > 0.99){
if (possibleMineSiteOreValue > maxOre) {
bestMineSite = possibleMineSite;
maxOre = possibleMineSiteOreValue;
}
if (Clock.getBytecodesLeft() <= 800 && bestMineSite != null){
// if(debug)System.out.println("WSFOUND: Bytecode Remaining: "+Clock.getBytecodesLeft()+" moving to "+bestMineSite.toString());
moveOptimally(getMoveDir(bestMineSite));
return;
}
}
}
}
// Failed, move randomly
// if(debug)System.out.println("WSFAILED: Bytecode Remaining: "+Clock.getBytecodesLeft()+" on round "+Clock.getRoundNum());
if (rand.nextDouble() < 0.5) {
moveToRallyPoint();
} else {
moveOptimally(getDirectionsAway(this.myHQ));
}
}
public Direction[] breakdownDirection(Direction direction) {
Direction[] breakdown = new Direction[2];
switch(direction) {
case NORTH_EAST:
breakdown[0] = Direction.NORTH;
breakdown[1] = Direction.EAST;
break;
case SOUTH_EAST:
breakdown[0] = Direction.SOUTH;
breakdown[1] = Direction.EAST;
break;
case NORTH_WEST:
breakdown[0] = Direction.NORTH;
breakdown[1] = Direction.WEST;
break;
case SOUTH_WEST:
breakdown[0] = Direction.SOUTH;
breakdown[1] = Direction.WEST;
break;
default:
break;
}
return breakdown;
}
public Direction getClockwiseDirection(MapLocation myLocation, MapLocation anchor) {
Direction directionToAnchor = myLocation.directionTo(anchor);
if (directionToAnchor.equals(Direction.EAST) || directionToAnchor.equals(Direction.SOUTH_EAST)) {
return Direction.NORTH_EAST;
} else if (directionToAnchor.equals(Direction.SOUTH) || directionToAnchor.equals(Direction.SOUTH_WEST)) {
return Direction.SOUTH_EAST;
} else if (directionToAnchor.equals(Direction.WEST) || directionToAnchor.equals(Direction.NORTH_WEST)) {
return Direction.SOUTH_WEST;
} else if (directionToAnchor.equals(Direction.NORTH) || directionToAnchor.equals(Direction.NORTH_EAST)) {
return Direction.NORTH_WEST;
}
return Direction.NONE;
}
public Direction getCounterClockwiseDirection(MapLocation myLocation, MapLocation anchor) {
Direction oppositeDirection = getClockwiseDirection(myLocation, anchor);
if (oppositeDirection.equals(Direction.NORTH_EAST)) {
return Direction.SOUTH_WEST;
} else if (oppositeDirection.equals(Direction.SOUTH_EAST)) {
return Direction.NORTH_WEST;
} else if (oppositeDirection.equals(Direction.SOUTH_WEST)) {
return Direction.NORTH_EAST;
} else if (oppositeDirection.equals(Direction.NORTH_WEST)) {
return Direction.SOUTH_WEST;
}
return Direction.NONE;
}
// Defend
public boolean defendSelf() {
RobotInfo[] nearbyEnemies = getEnemiesInAttackRange();
if(nearbyEnemies != null && nearbyEnemies.length > 0) {
try {
if (rc.isWeaponReady()) {
attackLeastHealthEnemyInRange();
}
} catch (GameActionException e) {
e.printStackTrace();
}
return true;
}
return false;
}
public boolean defendTeammates() {
RobotInfo[] engagedRobots = getRobotsEngagedInAttack();
if(engagedRobots != null && engagedRobots.length>0) { // Check broadcasts for enemies that are being attacked
// TODO: Calculate which enemy is attacking/within range/closest to teammate
// For now, just picking the first enemy
// Once our unit is in range of the other unit, A1 will takeover
for (RobotInfo robot : engagedRobots) {
if (robot.team == theirTeam) {
goToLocation(robot.location);
}
}
return true;
}
return false;
}
public boolean defend() {
// A1, Protect Self
boolean isProtectingSelf = defendSelf();
if (isProtectingSelf) {
return true;
}
// A2, Protect Nearby
boolean isProtectingTeammates = defendTeammates();
if (isProtectingTeammates) {
return true;
}
return false;
}
public int RobotTypeToInt(RobotType type){
switch(type) {
case AEROSPACELAB:
return 1;
case BARRACKS:
return 2;
case BASHER:
return 3;
case BEAVER:
return 4;
case COMMANDER:
return 5;
case COMPUTER:
return 6;
case DRONE:
return 7;
case HANDWASHSTATION:
return 8;
case HELIPAD:
return 9;
case HQ:
return 10;
case LAUNCHER:
return 11;
case MINER:
return 12;
case MINERFACTORY:
return 13;
case MISSILE:
return 14;
case SOLDIER:
return 15;
case SUPPLYDEPOT:
return 16;
case TANK:
return 17;
case TANKFACTORY:
return 18;
case TECHNOLOGYINSTITUTE:
return 19;
case TOWER:
return 20;
case TRAININGFIELD:
return 21;
default:
return -1;
}
}
public RobotType IntToRobotType(int type){
switch(type) {
case 1:
return RobotType.AEROSPACELAB;
case 2:
return RobotType.BARRACKS;
case 3:
return RobotType.BASHER;
case 4:
return RobotType.BEAVER;
case 5:
return RobotType.COMMANDER;
case 6:
return RobotType.COMPUTER;
case 7:
return RobotType.DRONE;
case 8:
return RobotType.HANDWASHSTATION;
case 9:
return RobotType.HELIPAD;
case 10:
return RobotType.HQ;
case 11:
return RobotType.LAUNCHER;
case 12:
return RobotType.MINER;
case 13:
return RobotType.MINERFACTORY;
case 14:
return RobotType.MISSILE;
case 15:
return RobotType.SOLDIER;
case 16:
return RobotType.SUPPLYDEPOT;
case 17:
return RobotType.TANK;
case 18:
return RobotType.TANKFACTORY;
case 19:
return RobotType.TECHNOLOGYINSTITUTE;
case 20:
return RobotType.TOWER;
case 21:
return RobotType.TRAININGFIELD;
default:
return null;
}
}
// //Returns a weight representing the 'need' for the RobotType
// public double getWeightOfRobotType(RobotType type) throws GameActionException {
// int typeInt = RobotTypeToInt(type);
// if (rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) == 0) return 0;
// double weight = rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt) +
// (rc.readBroadcast(smuIndices.freqRoundToFinish + typeInt) - rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt)) /
// rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) * rc.readBroadcast(smuIndices.freqNum[typeInt]);
// return weight;
//Returns a weight representing the 'need' for the RobotType
public double getWeightOfRobotType(RobotType type) throws GameActionException {
int typeInt = RobotTypeToInt(type);
int round = Clock.getRoundNum();
double weight = 0;
if (!type.isBuilding) {
int currentAmount = rc.readBroadcast(smuIndices.channel[typeInt]+0);
int desiredAmount = rc.readBroadcast(smuIndices.channel[typeInt]+1);
int roundToBeginSpawning = rc.readBroadcast(smuIndices.channel[typeInt]+2);
int roundToFinishSpawning = rc.readBroadcast(smuIndices.channel[typeInt]+3);
//Return zero if unit is not desired. (Divide by zero protection)
if (desiredAmount == 0) {
// //System.out.println("Error: No desired "+IntToRobotType(typeInt));
return 0;
}
if (roundToBeginSpawning >= roundToFinishSpawning) {
// //System.out.println("Error: build > finish for: "+IntToRobotType(typeInt));
return 0;
}
if (round < roundToBeginSpawning) {
// //System.out.println("Error: Too early for "+IntToRobotType(typeInt));
return 0;
}
//The weight is equal to a point on the surface drawn by z = x^(m*y) where
double x = (double) (round - roundToBeginSpawning)
/ (double) (roundToFinishSpawning - roundToBeginSpawning);
double y = (double) currentAmount / (double) desiredAmount;
weight = smuConstants.weightScaleMagic
* Math.pow(x, (smuConstants.weightExponentMagic + y));
// //System.out.println("type: "+IntToRobotType(typeInt)+" x: " + x + " y: " + y + " weight: " + weight);
return weight;
} //end units
if (type.isBuilding){
int currentAmount = rc.readBroadcast(smuIndices.channel[typeInt]+0);
int desiredAmount = rc.readBroadcast(smuIndices.channel[typeInt]+1);
int nextRoundToBuild = rc.readBroadcast(smuIndices.channel[typeInt]+2+currentAmount);
int intQueuedType = rc.readBroadcast(smuIndices.freqQueue);
if (currentAmount < desiredAmount && nextRoundToBuild != 0) {
if (round > nextRoundToBuild && typeInt != intQueuedType) {
// It's not in the queue
return 1.0;
}
if (round > nextRoundToBuild && typeInt == intQueuedType) {
// It's in the queue
return 0.0;
}
if (round == nextRoundToBuild) {
return 1.0;
}
if (round < nextRoundToBuild) {
return 0.0;
}
// System.out.println("ERROR: Unexpected return path in getWeightOfRobotType " + type.name());
return weight;
} else if(currentAmount >= desiredAmount && currentAmount <= 4*desiredAmount && rc.getTeamOre() > 600) {
int strategy = rc.readBroadcast(smuIndices.STRATEGY);
if (strategy == smuConstants.STRATEGY_DRONE_CONTAIN) {
if (type == RobotType.HELIPAD || (type == RobotType.SUPPLYDEPOT && currentAmount <= 2*desiredAmount)){
return 1.0;
}
} else if (strategy == smuConstants.STRATEGY_TANKS_AND_SOLDIERS) {
if ( (type == RobotType.BARRACKS && currentAmount <= 2*rc.readBroadcast(smuIndices.channel[RobotTypeToInt(RobotType.TANKFACTORY)]+0)) ||
(type == RobotType.TANKFACTORY && currentAmount <= 2*rc.readBroadcast(smuIndices.channel[RobotTypeToInt(RobotType.BARRACKS)]+0)) ||
(type == RobotType.SUPPLYDEPOT && currentAmount <= 2*desiredAmount) ){
return 1.0;
}
}
} else {
return 0;
}
} //end structures
// System.out.println("ERROR: Unexpected return path in getWeightOfRobotType");
return weight;
}
public RobotInfo[] getEnemiesInAttackRange() {
return rc.senseNearbyRobots(myRange, theirTeam);
}
//TODO Use optimally instead?
public void goToLocation(MapLocation location) {
try {
if (rc.canSenseLocation(location) && rc.senseRobotAtLocation(location) != null
&& rc.getLocation().distanceSquaredTo(location)<3) { // 3 squares
return;
}
Direction direction = getMoveDir(location);
if (direction == null) return;
RobotInfo[] nearbyEnemies = rc.senseNearbyRobots(rc.getLocation().add(direction), RobotType.TOWER.attackRadiusSquared, theirTeam);
boolean towersNearby = false;
for (RobotInfo enemy : nearbyEnemies) {
if (enemy.type == RobotType.TOWER || enemy.type == RobotType.HQ) {
towersNearby = true;
break;
}
}
if (!towersNearby || Clock.getRoundNum() > smuConstants.roundToLaunchAttack) {
if (direction != null && rc.isCoreReady() && rc.canMove(direction) && Clock.getBytecodesLeft() > 55) {
rc.move(direction);
}
}
} catch (GameActionException e1) {
e1.printStackTrace();
}
}
public RobotInfo[] getRobotsEngagedInAttack() {
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(smuConstants.PROTECT_OTHERS_RANGE);
boolean hasEnemy = false;
boolean hasFriendly = false;
for (RobotInfo robot : nearbyRobots) {
if(robot.team == theirTeam && robot.type != RobotType.TOWER) {
hasEnemy = true;
if (hasFriendly) {
return nearbyRobots;
}
} else {
hasFriendly = true;
if (hasEnemy) {
return nearbyRobots;
}
}
}
return null;
}
public RobotInfo[] getTeammatesInAttackRange() {
return rc.senseNearbyRobots(myRange, myTeam);
}
public RobotInfo[] getTeammatesNearTower(MapLocation towerLocation) {
return rc.senseNearbyRobots(towerLocation, RobotType.TOWER.attackRadiusSquared, myTeam);
}
// Find out if there are any holes between a teams tower and their HQ
public MapLocation[] computeHoles() {
MapLocation[] towerLocations = rc.senseTowerLocations();
MapLocation[][] towerRadii = new MapLocation[towerLocations.length][];
for(int i = 0; i < towerLocations.length; i++) {
// Get all map locations that a tower can attack
MapLocation[] locations = MapLocation.getAllMapLocationsWithinRadiusSq(towerLocations[i], RobotType.TOWER.attackRadiusSquared);
Arrays.sort(locations);
towerRadii[i] = locations;
}
if(towerRadii.length == 0 || towerRadii[0] == null) {
return null;
}
// Naively say, if overlapping by two towers, there is no path
int[] overlapped = new int[towerRadii.length];
int holesBroadcastIndex = smuIndices.TOWER_HOLES_BEGIN;
for(int i = 0; i<towerRadii.length; i++) {
MapLocation[] locations = towerRadii[i];
boolean coveredLeft = false;
boolean coveredRight = false;
boolean coveredTop = false;
boolean coveredBottom = false;
for (int j = 0; j < towerRadii.length; j++) {
if (j != i) {
MapLocation[] otherLocations = towerRadii[j];
if (locations[0].x <= otherLocations[otherLocations.length-1].x &&
otherLocations[0].x <= locations[locations.length-1].x &&
locations[0].y <= otherLocations[otherLocations.length-1].y &&
otherLocations[0].y <= locations[locations.length-1].y) {
overlapped[i]++;
Direction otherTowerDir = towerLocations[i].directionTo(towerLocations[j]);
if (otherTowerDir.equals(Direction.EAST) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.SOUTH_EAST)) {
coveredLeft = true;
}
if (otherTowerDir.equals(Direction.WEST) || otherTowerDir.equals(Direction.NORTH_WEST) || otherTowerDir.equals(Direction.SOUTH_WEST)) {
coveredRight = true;
}
if (otherTowerDir.equals(Direction.NORTH) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.NORTH_WEST)) {
coveredTop = true;
}
if (otherTowerDir.equals(Direction.SOUTH) || otherTowerDir.equals(Direction.SOUTH_EAST) || otherTowerDir.equals(Direction.SOUTH_WEST)) {
coveredBottom = true;
}
}
}
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x - 1, locations[0].y))) {
overlapped[i]++;
coveredLeft = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[locations.length-1].x + 1, locations[0].y))) {
overlapped[i]++;
coveredRight = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[0].y - 1))) {
overlapped[i]++;
coveredTop = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[locations.length-1].y + 1))) {
overlapped[i]++;
coveredBottom = true;
}
// //System.out.println("Tower " + i + " overlapped " + overlapped[i] + " " + towerLocations[i]);
if (overlapped[i] < 2) {
try {
int towerAttackRadius = (int) Math.sqrt(RobotType.TOWER.attackRadiusSquared) + 1;
if (!coveredLeft) {
// //System.out.println("Tower " + towerLocations[i] + " Not covered left");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x - towerAttackRadius);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y);
holesBroadcastIndex+=2;
}
if (!coveredRight) {
// //System.out.println("Tower " + towerLocations[i] + " Not covered right");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x + towerAttackRadius);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y);
holesBroadcastIndex+=2;
}
if (!coveredTop) {
// //System.out.println("Tower " + towerLocations[i] + " Not covered top");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y - towerAttackRadius);
holesBroadcastIndex+=2;
}
if (!coveredBottom) {
// //System.out.println("Tower " + towerLocations[i] + " Not covered bottom");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y + towerAttackRadius);
holesBroadcastIndex+=2;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
}
// Signify end of holes
try {
rc.broadcast(holesBroadcastIndex, -1);
} catch (GameActionException e) {
e.printStackTrace();
}
// //System.out.println("BYTEEND on " + Clock.getRoundNum() + ": " + Clock.getBytecodeNum());
return null;
}
}
public static class HQ extends BaseBot {
public int xMin, xMax, yMin, yMax;
public int xpos, ypos;
public int totalNormal, totalVoid, totalProcessed;
public static double ratio;
public boolean isFinishedAnalyzing = false;
public boolean analyzedTowers = false;
public int defaultStrategy = smuConstants.STRATEGY_TANKS_AND_SOLDIERS;
public boolean hasChosenStrategyPrior = false;
public int strategy = defaultStrategy;
public int prevStrategy = 0;
public int numTowers;
public int numEnemyTowers;
public boolean dronesFailed = false;
public boolean analyzedPrevMatch = false;
public HQ(RobotController rc) {
super(rc);
numTowers = rc.senseTowerLocations().length;
numEnemyTowers = rc.senseEnemyTowerLocations().length;
xMin = Math.min(this.myHQ.x, this.theirHQ.x);
xMax = Math.max(this.myHQ.x, this.theirHQ.x);
yMin = Math.min(this.myHQ.y, this.theirHQ.y);
yMax = Math.max(this.myHQ.y, this.theirHQ.y);
xpos = xMin;
ypos = yMin;
totalNormal = totalVoid = totalProcessed = 0;
isFinishedAnalyzing = false;
try {
computeStrategy();
} catch (GameActionException e) {
e.printStackTrace();
}
computeHoles();
}
// For dead towers
public void resetSOS() throws GameActionException {
int roundSOSSent = rc.readBroadcast(smuIndices.TOWER_SOS_ROUND_SENT);
if (roundSOSSent + 3 > Clock.getRoundNum()) {
rc.broadcast(smuIndices.TOWER_SOS_X, 0);
rc.broadcast(smuIndices.TOWER_SOS_Y, 0);
}
}
public void analyzePreviousMatch() {
long[] prevGameTeamMemory = rc.getTeamMemory();
boolean hasData = false;
for (long memory : prevGameTeamMemory) {
if (memory != 0) {
hasData = true;
break;
}
}
if (hasData) {
double prevRatio = ((double) prevGameTeamMemory[smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT])/100.0;
int mostUsed = 0;
int mostUsedIndex = -1;
int secondMostUsed = 0;
int secondMostUsedIndex = -1;
for(int i = 0; i < 6; i++) { // 6 is number of different strategies
int numRoundsUsed = (int) prevGameTeamMemory[smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + i];
if (numRoundsUsed > mostUsed) {
secondMostUsed = mostUsed;
secondMostUsedIndex = mostUsedIndex;
mostUsed = numRoundsUsed;
mostUsedIndex = i;
} else if (numRoundsUsed > secondMostUsed) {
secondMostUsed = numRoundsUsed;
secondMostUsedIndex = i;
}
}
if (mostUsed == smuConstants.STRATEGY_DRONE_CONTAIN) {
dronesFailed = true;
// System.out.println(Clock.getRoundNum() + " Drones failed.");
} else {
if (ratio > 0.85 && prevRatio > 0.85) {
// Both Traversables
int i = 0;
while (prevGameTeamMemory[smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + i] != 0) {
i++;
}
int ourTowersDestroyed = i;
int j = 0;
while (prevGameTeamMemory[smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + j] != 0) {
j++;
}
int theirTowersDestroyed = j;
if (ourTowersDestroyed < theirTowersDestroyed) {
defaultStrategy = mostUsedIndex + 1;
} else {
if (secondMostUsedIndex != -1) {
defaultStrategy = secondMostUsedIndex + 1;
}
}
}
}
for (int i = 0; i < GameConstants.TEAM_MEMORY_LENGTH; i++) {
rc.setTeamMemory(i, 0);
}
}
analyzedPrevMatch = true;
}
public void analyzeMap() {
while (ypos < yMax + 1) {
TerrainTile t = rc.senseTerrainTile(new MapLocation(xpos, ypos));
if (t == TerrainTile.NORMAL) {
totalNormal++;
totalProcessed++;
}
else if (t == TerrainTile.VOID) {
totalVoid++;
totalProcessed++;
}
xpos++;
if (xpos == xMax + 1) {
xpos = xMin;
ypos++;
}
if (Clock.getBytecodesLeft() < 50) {
return;
}
}
ratio = (double) totalNormal / totalProcessed;
isFinishedAnalyzing = true;
}
public void chooseStrategy() throws GameActionException {
if (hasChosenStrategyPrior && Clock.getRoundNum() % 250 != 0) {
return;
}
if (rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) == smuConstants.NOT_CURRENTLY_BEING_CONTAINED) {
if (myHQ.distanceSquaredTo(theirHQ) > 2500 || ratio <= 0.85) {
// Void heavy map or large map
strategy = smuConstants.STRATEGY_DRONE_CONTAIN;
} else {
strategy = smuConstants.STRATEGY_TANKS_AND_SOLDIERS;
}
} else {
strategy = smuConstants.STRATEGY_TANKS_AND_SOLDIERS;
}
//STRATEGY_DRONE_CONTAIN = 1;
//STRATEGY_TANKS_AND_SOLDIERS = 2;
rc.broadcast(smuIndices.STRATEGY, strategy);
hasChosenStrategyPrior = true;
}
public void computeStrategy() throws GameActionException{
if (prevStrategy == strategy) {
return;
}
// [desiredNumOf, roundToBuild, roundToFinish]
int[] strategyAEROSPACELAB = new int[3];
int[] strategyBARRACKS = new int[3];
int[] strategyBASHER = new int[3];
int[] strategyBEAVER = new int[3];
int[] strategyCOMMANDER = new int[3];
int[] strategyCOMPUTER = new int[3];
int[] strategyDRONE = new int[3];
int[] strategyHANDWASHSTATION = new int[3];
int[] strategyHELIPAD = new int[3];
int[] strategyHQ = new int[3];
int[] strategyLAUNCHER = new int[3];
int[] strategyMINER = new int[3];
int[] strategyMINERFACTORY = new int[3];
int[] strategyMISSILE = new int[3];
int[] strategySOLDIER = new int[3];
int[] strategySUPPLYDEPOT = new int[3];
int[] strategyTANK = new int[3];
int[] strategyTANKFACTORY = new int[3];
int[] strategyTECHNOLOGYINSTITUTE = new int[3];
int[] strategyTOWER = new int[3];
int[] strategyTRAININGFIELD = new int[3];
if (strategy == smuConstants.STRATEGY_TANKS_AND_SOLDIERS) {
// System.out.println("COMPUTE STRATEGY: Tanks and Soldiers");
strategyAEROSPACELAB = new int[] {0};
strategyBARRACKS = new int[] {100, 650, 800};
strategyBASHER = new int[] {50, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 0};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {0, 0, 0};
strategyHANDWASHSTATION = new int[] {1850, 1860, 1870};
strategyHELIPAD = new int[] {0};
strategyHQ = new int[] {0};
strategyLAUNCHER = new int[] {0, 0, 0};
strategyMINER = new int[] {40, 1, 500};
strategyMINERFACTORY = new int[] {1, 200};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {80, 200, 1200};
// strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
strategySUPPLYDEPOT = new int[] {1000, 1400, 1500};
strategyTANK = new int[] {40, 500, 1800};
strategyTANKFACTORY = new int[] {400, 800};
strategyTECHNOLOGYINSTITUTE = new int[] {0};
strategyTOWER = new int[] {0};
strategyTRAININGFIELD = new int[] {0};
} else if(strategy == smuConstants.STRATEGY_DRONE_CONTAIN) {
// System.out.println("COMPUTE STRATEGY: Drone Contain");
strategyAEROSPACELAB = new int[] {0};
strategyBARRACKS = new int[] {0};
strategyBASHER = new int[] {0, 0, 0};
strategyBEAVER = new int[] {10, 0, 100};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {100, 100, 1800};
strategyHANDWASHSTATION = new int[] {1850, 1860, 1870};
strategyHELIPAD = new int[] {1, 300};
strategyHQ = new int[] {0};
strategyLAUNCHER = new int[] {0, 0, 0};
strategyMINER = new int[] {20, 100, 500};
strategyMINERFACTORY = new int[] {100, 500};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {0, 0, 0};
strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
strategyTANK = new int[] {0, 0, 0};
strategyTANKFACTORY = new int[] {0};
strategyTECHNOLOGYINSTITUTE = new int[] {0};
strategyTOWER = new int[] {0};
strategyTRAININGFIELD = new int[] {0};
}
//BE CAREFUL!!!
//TODO
int[][] strategyUnitArray = new int[][] {strategyBASHER, strategyBEAVER, strategyCOMMANDER, strategyCOMPUTER, strategyDRONE, strategyLAUNCHER, strategyMINER, strategyMISSILE, strategySOLDIER, strategyTANK};
int[] channelUnitArray = new int[] {smuIndices.channelBASHER, smuIndices.channelBEAVER, smuIndices.channelCOMMANDER, smuIndices.channelCOMPUTER, smuIndices.channelDRONE, smuIndices.channelLAUNCHER, smuIndices.channelMINER, smuIndices.channelMISSILE, smuIndices.channelSOLDIER, smuIndices.channelTANK};
int[][] strategyStructureArray = new int[][] {strategyAEROSPACELAB, strategyBARRACKS, strategyHANDWASHSTATION, strategyHELIPAD, strategyHQ, strategyMINERFACTORY, strategySUPPLYDEPOT, strategyTANKFACTORY, strategyTECHNOLOGYINSTITUTE, strategyTOWER, strategyTRAININGFIELD};
int[] channelStructureArray = new int[] {smuIndices.channelAEROSPACELAB, smuIndices.channelBARRACKS, smuIndices.channelHANDWASHSTATION, smuIndices.channelHELIPAD, smuIndices.channelHQ, smuIndices.channelMINERFACTORY, smuIndices.channelSUPPLYDEPOT, smuIndices.channelTANKFACTORY, smuIndices.channelTECHNOLOGYINSTITUTE, smuIndices.channelTOWER, smuIndices.channelTRAININGFIELD};
//Broadcast unit strategies
for (int i = 1; i < strategyUnitArray.length; i++) {
rc.broadcast(channelUnitArray[i] + 0, 0);
rc.broadcast(channelUnitArray[i] + 1, strategyUnitArray[i][0]);
rc.broadcast(channelUnitArray[i] + 2, strategyUnitArray[i][1]);
rc.broadcast(channelUnitArray[i] + 3, strategyUnitArray[i][2]);
}
//Broadcast structure strategies
for (int i = 1; i < strategyStructureArray.length; i++) {
rc.broadcast(channelStructureArray[i] + 0, 0);
if (strategyStructureArray[i].length > 1) {
rc.broadcast(channelStructureArray[i] + 1, strategyStructureArray[i].length);
for (int j = 0; j < strategyStructureArray[i].length; j++) {
rc.broadcast(channelStructureArray[i] + j + 2, strategyStructureArray[i][j]);
}
} else {
rc.broadcast(channelStructureArray[i] + 1, 0);
rc.broadcast(channelStructureArray[i] + 2, 0);
}
}
prevStrategy = strategy;
}
public void saveTeamMemory() {
long[] teamMemory = rc.getTeamMemory();;
int currRound = Clock.getRoundNum();
if (isFinishedAnalyzing && teamMemory[smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT] == 0) {
rc.setTeamMemory(smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT, (long) (ratio * 100));
}
rc.setTeamMemory(smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + strategy, teamMemory[smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + strategy] + 1);
if (teamMemory[smuTeamMemoryIndices.ROUND_OUR_HQ_ATTACKED] == 0) {
if (rc.getHealth() < RobotType.HQ.maxHealth) {
rc.setTeamMemory(smuTeamMemoryIndices.ROUND_OUR_HQ_ATTACKED, currRound);
}
}
int currNumTowers = rc.senseTowerLocations().length;
if (currNumTowers < numTowers) {
int towersIndex = 0;
while (teamMemory[smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + towersIndex] != 0) {
towersIndex++;
}
for (int i = 0; i < numTowers - currNumTowers; i++) {
rc.setTeamMemory(smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + towersIndex + i, currRound);
}
numTowers = currNumTowers;
}
int currNumEnemyTowers = rc.senseEnemyTowerLocations().length;
if (currNumEnemyTowers < numEnemyTowers) {
int towersIndex = 0;
while (teamMemory[smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + towersIndex] != 0) {
towersIndex++;
}
for (int i = 0; i < numEnemyTowers - currNumEnemyTowers; i++) {
rc.setTeamMemory(smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + towersIndex + i, currRound);
}
numEnemyTowers = currNumEnemyTowers;
}
}
public RobotType checkContainment() throws GameActionException {
RobotInfo[] enemyRobotsContaining = rc.senseNearbyRobots(50, theirTeam);
if (enemyRobotsContaining.length > 4) {
rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.CURRENTLY_BEING_CONTAINED);
int robotTypeContaining = getMajorityRobotType(enemyRobotsContaining);
rc.broadcast(smuIndices.HQ_BEING_CONTAINED_BY, robotTypeContaining);
return IntToRobotType(robotTypeContaining);
} else {
rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.NOT_CURRENTLY_BEING_CONTAINED);
return null;
}
}
public int getMajorityRobotType(RobotInfo[] enemyRobots) {
int[] enemyRobotTypes = new int[22]; //Max RobotType -> int value + 1
int highestValue = 0;
int highestValueIndex = -1;
for (int i = 0; i < enemyRobots.length; i++) {
int robotType = RobotTypeToInt(enemyRobots[i].type);
enemyRobotTypes[robotType] = enemyRobotTypes[robotType] + 1;
if (enemyRobotTypes[robotType] > highestValue) {
highestValue = enemyRobotTypes[robotType];
highestValueIndex = i;
}
}
return highestValueIndex;
}
public void setRallyPoint() throws GameActionException {
MapLocation rallyPoint = null;
RobotType beingContained = checkContainment();
if (beingContained == null) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
MapLocation[] ourTowers = rc.senseTowerLocations();
if (ourTowers != null && ourTowers.length > 0) {
int closestTower = -1;
int closestDistanceToEnemyHQ = Integer.MAX_VALUE;
for (int i = 0; i < ourTowers.length; i++) {
int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ);
if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) {
closestDistanceToEnemyHQ = currDistanceToEnemyHQ;
closestTower = i;
}
}
rallyPoint = ourTowers[closestTower].add(ourTowers[closestTower].directionTo(theirHQ), 2);
}
} else {
MapLocation[] enemyTowers = rc.senseEnemyTowerLocations();
if (enemyTowers == null || enemyTowers.length <= smuConstants.numTowersRemainingToAttackHQ) {
rallyPoint = rc.senseEnemyHQLocation();
} else {
rallyPoint = enemyTowers[0];
}
}
} else {
rallyPoint = getSecondBaseLocation();
if (rallyPoint != null) {
rallyPoint = rallyPoint.add(rallyPoint.directionTo(theirHQ), 8);
}
}
if (rallyPoint != null) {
rc.broadcast(smuIndices.RALLY_POINT_X, rallyPoint.x);
rc.broadcast(smuIndices.RALLY_POINT_Y, rallyPoint.y);
}
}
public void execute() throws GameActionException {
spawnOptimally();
setRallyPoint();
attackLeastHealthEnemyInRange();
resetSOS();
transferSupplies();
if (!isFinishedAnalyzing) {
analyzeMap();
} else {
if (!analyzedPrevMatch) analyzePreviousMatch();
chooseStrategy();
try {
computeStrategy();
} catch (GameActionException e) {
e.printStackTrace();
}
}
if (analyzedPrevMatch) saveTeamMemory();
rc.yield();
}
}
//BEAVER
public static class Beaver extends BaseBot {
public MapLocation secondBase;
public Beaver(RobotController rc) {
super(rc);
Random rand = new Random(rc.getID());
if (rand.nextDouble() < smuConstants.percentBeaversToGoToSecondBase) {
secondBase = getSecondBaseLocation();
}
}
public void execute() throws GameActionException {
fleeMissile();
if (secondBase != null && rc.getLocation().distanceSquaredTo(secondBase) > 6) {
goToLocation(secondBase);
}
buildOptimally();
transferSupplies();
if (Clock.getRoundNum() > 400) defend();
if (rc.isCoreReady()) {
//mine
if (rc.senseOre(rc.getLocation()) > 0) {
rc.mine();
}
else {
moveOptimally();
}
}
rc.yield();
}
}
//MINERFACTORY
public static class Minerfactory extends BaseBot {
public Minerfactory(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//MINER
public static class Miner extends BaseBot {
public Miner(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
boolean inConvoy = false;
if (Clock.getRoundNum()>smuConstants.roundToFormSupplyConvoy
&& rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) != smuConstants.CURRENTLY_BEING_CONTAINED) {
inConvoy = formSupplyConvoy();
}
if (!inConvoy) {
if (!defend()) {
// //System.out.println("Mining optimally");
mineOptimally();
}
} else if(!defendSelf()) {
if (rc.isCoreReady() && rc.senseOre(rc.getLocation()) > 0) {
rc.mine();
}
}
transferSupplies();
rc.yield();
}
}
//BARRACKS
public static class Barracks extends BaseBot {
public Barracks(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//SOLDIER
public static class Soldier extends BaseBot {
public Soldier(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
fleeMissile();
defendTowerSOS();
if (!defend()) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
contain();
} else {
moveToRallyPoint();
}
}
transferSupplies();
rc.yield();
}
}
//BASHER
public static class Basher extends BaseBot {
public Basher(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
contain();
} else {
moveToRallyPoint();
}
transferSupplies();
rc.yield();
}
}
//TANK
public static class Tank extends BaseBot {
public Tank(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
fleeMissile();
defendTowerSOS();
if (!defend()) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
contain();
} else {
moveToRallyPoint();
}
}
transferSupplies();
rc.yield();
}
}
//DRONE
public static class Drone extends BaseBot {
public Drone(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
fleeMissile();
defendTowerSOS();
if (!defendSelf()) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
contain();
} else {
moveToRallyPoint();
}
}
transferSupplies();
rc.yield();
}
}
//TOWER
public static class Tower extends BaseBot {
public double healthLastRound;
public int lastRoundLostHealth = 0;
public Tower(RobotController rc) {
super(rc);
healthLastRound = rc.getHealth();
}
public void handleSOS() throws GameActionException {
double currentHealth = rc.getHealth();
int currRound = Clock.getRoundNum();
int towerX = rc.readBroadcast(smuIndices.TOWER_SOS_X);
int towerY = rc.readBroadcast(smuIndices.TOWER_SOS_Y);
MapLocation towerSOSing = null;
if (towerX != 0 && towerY != 0) {
towerSOSing = new MapLocation(towerX, towerY);
}
MapLocation myLocation = rc.getLocation();
if ((towerX == 0 && towerY == 0) || towerSOSing == myLocation) {
if (currentHealth < healthLastRound) {
rc.broadcast(smuIndices.TOWER_SOS_X, myLocation.x);
rc.broadcast(smuIndices.TOWER_SOS_Y, myLocation.y);
rc.broadcast(smuIndices.TOWER_SOS_ROUND_SENT, currRound);
} else if (lastRoundLostHealth + 2 < currRound) {
rc.broadcast(smuIndices.TOWER_SOS_X, 0);
rc.broadcast(smuIndices.TOWER_SOS_Y, 0);
rc.broadcast(smuIndices.TOWER_SOS_ROUND_SENT, 0);
}
}
healthLastRound = currentHealth;
}
public void execute() throws GameActionException {
handleSOS();
transferSupplies();
attackLeastHealthEnemyInRange();
rc.yield();
}
}
//SUPPLYDEPOT
public static class Supplydepot extends BaseBot {
public Supplydepot(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
rc.yield();
}
}
//HANDWASHSTATION
public static class Handwashstation extends BaseBot {
public Handwashstation(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
rc.yield();
}
}
//TANKFACTORY
public static class Tankfactory extends BaseBot {
public Tankfactory(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//HELIPAD
public static class Helipad extends BaseBot {
public Helipad(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//AEROSPACELAB
public static class Aerospacelab extends BaseBot {
public Aerospacelab(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//LAUNCHER
public static class Launcher extends BaseBot {
public Launcher(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
boolean launched = false;
if (rc.getMissileCount() > 0) {
Direction targetDir = getDirOfLauncherTarget();
if (targetDir != null && rc.isWeaponReady()){
if (rc.canLaunch(targetDir)){
rc.launchMissile(targetDir);
launched = true;
}
}
}
if (!launched) {
contain();
}
rc.yield();
}
}
//MISSILE
public static class Missile extends BaseBot {
public Direction dirToTarget = null;
public Missile(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (dirToTarget == null) {
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(2, myTeam);
for (RobotInfo robot : nearbyRobots) {
if (robot.type == RobotType.LAUNCHER) {
dirToTarget = rc.getLocation().directionTo(robot.location).opposite();
}
}
// //System.out.println("dirToTarget: "+dirToTarget.name());
}
if (rc.isCoreReady() && rc.canMove(dirToTarget)){
rc.move(dirToTarget);
}
// if (getTeammatesInAttackRange().length <= 1 && getTeammatesInAttackRange().length > 4){
// rc.explode();
rc.yield();
}
}
}
|
package com.flipkart.zjsonpatch;
import java.util.EnumSet;
public enum DiffFlags {
OMIT_VALUE_ON_REMOVE,
OMIT_MOVE_OPERATION, //only have ADD, REMOVE, REPLACE, COPY Don't normalize operations into MOVE
OMIT_COPY_OPERATION; //only have ADD, REMOVE, REPLACE, MOVE, Don't normalize operations into COPY
public static EnumSet<DiffFlags> defaults() {
return EnumSet.of(OMIT_VALUE_ON_REMOVE);
}
public static EnumSet<DiffFlags> dontNormalizeOpIntoMoveAndCopy() {
return EnumSet.of(OMIT_MOVE_OPERATION, OMIT_COPY_OPERATION);
}
}
|
package org.pentaho.di.ui.trans.steps.sapinput;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.steps.sapinput.SapInputMeta;
import org.pentaho.di.trans.steps.sapinput.sap.SAPConnectionFactory;
import org.pentaho.di.trans.steps.sapinput.sap.SAPConnection;
import org.pentaho.di.trans.steps.sapinput.sap.SAPFunction;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
/**
* Displays results of a search operation in a list of SAP functions
*
* @author Matt
* @since 19-06-2003
*/
public class SapFunctionBrowser extends Dialog
{
private static Class<?> PKG = SapInputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private Label wlFunction;
private Text wFunction;
private Button wbFunction;
private TableView wResult;
private Button wOK;
private Button wCancel;
private Shell shell;
private PropsUI props;
private DatabaseMeta sapConnection;
private String searchString;
private VariableSpace space;
private SAPFunction function;
private List<SAPFunction> functionList;
public SapFunctionBrowser(Shell parent, VariableSpace space, int style, DatabaseMeta sapConnection, String searchString)
{
super(parent, style);
this.space = space;
this.sapConnection = sapConnection;
this.searchString = searchString;
props = PropsUI.getInstance();
functionList = new ArrayList<SAPFunction>(); // Empty by default...
}
public SAPFunction open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX);
props.setLook(shell);
shell.setImage(GUIResource.getInstance().getImageSpoon());
int middle = Const.MIDDLE_PCT;
int margin = Const.MARGIN;
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "SapFunctionBrowser.Title"));
// Function
wlFunction=new Label(shell, SWT.RIGHT);
wlFunction.setText(BaseMessages.getString(PKG, "SapInputDialog.Function.Label")); //$NON-NLS-1$
props.setLook(wlFunction);
FormData fdlFunction = new FormData();
fdlFunction.left = new FormAttachment(0, 0);
fdlFunction.right = new FormAttachment(middle, -margin);
fdlFunction.top = new FormAttachment(0, 0);
wlFunction.setLayoutData(fdlFunction);
wbFunction = new Button(shell, SWT.PUSH);
props.setLook(wbFunction);
wbFunction.setText(BaseMessages.getString(PKG, "SapInputDialog.FindFunctionButton.Label")); //$NON-NLS-1$
FormData fdbFunction = new FormData();
fdbFunction.right = new FormAttachment(100, 0);
fdbFunction.top = new FormAttachment(0, 0);
wbFunction.setLayoutData(fdbFunction);
wbFunction.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) {
searchString = wFunction.getText();
getData();
}});
wFunction=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFunction);
FormData fdFunction = new FormData();
fdFunction.left = new FormAttachment(middle, 0);
fdFunction.right = new FormAttachment(wbFunction, -margin);
fdFunction.top = new FormAttachment(0, margin);
wFunction.setLayoutData(fdFunction);
Control lastControl = wFunction;
// The buttons at the bottom of the dialog
wOK = new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wOK.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { ok(); } });
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
wCancel.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { cancel(); } });
// Position the buttons...
BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel, }, Const.MARGIN, null);
// The search results...
ColumnInfo[] columns = new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "SapFunctionBrowser.ResultView.Name.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
new ColumnInfo(BaseMessages.getString(PKG, "SapFunctionBrowser.ResultView.Groupname.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
new ColumnInfo(BaseMessages.getString(PKG, "SapFunctionBrowser.ResultView.Application.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
new ColumnInfo(BaseMessages.getString(PKG, "SapFunctionBrowser.ResultView.Description.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
};
wResult = new TableView(space, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, columns, 0, null, props);
wResult.setSortable(true);
FormData fdResults = new FormData();
fdResults.left = new FormAttachment(0, 0);
fdResults.top = new FormAttachment(lastControl, margin);
fdResults.right = new FormAttachment(100, 0);
fdResults.bottom = new FormAttachment(wOK, -3*margin);
wResult.setLayoutData(fdResults);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
getData();
// Set the shell size, based upon previous time...
BaseStepDialog.setSize(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return function;
}
private void dispose() {
WindowProperty winprop = new WindowProperty(shell);
props.setScreen(winprop);
shell.dispose();
}
protected void cancel() {
function = null;
dispose();
}
protected void ok() {
function = null;
int selectionIndex = wResult.getSelectionIndex();
if (selectionIndex>=0 && selectionIndex<functionList.size()) {
function = functionList.get(selectionIndex);
}
dispose();
}
protected void find(String searchString) {
this.searchString = searchString;
SAPConnection sc = SAPConnectionFactory.create();
try {
sc.open(sapConnection);
functionList = new ArrayList<SAPFunction>(sc.getFunctions(searchString));
} catch(Exception e) {
new ErrorDialog(shell,
BaseMessages.getString(PKG, "SapFunctionBrowser.ExceptionDialog.ErrorDuringSearch.Title"),
BaseMessages.getString(PKG, "SapFunctionBrowser.ExceptionDialog.ErrorDuringSearch.Message"),
e
);
} finally {
sc.close();
}
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
private void getData()
{
shell.getDisplay().asyncExec(new Runnable()
{
public void run()
{
Cursor hourGlass = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
try {
shell.setCursor(hourGlass);
if (Const.isEmpty(searchString)) {
return;
}
wFunction.setText(searchString);
find(searchString);
// Clear out everything, always leaves one row
wResult.clearAll(false);
for (int i=0;i<functionList.size();i++) {
SAPFunction sapFunction = functionList.get(i);
TableItem item;
if (i==0) {
item = wResult.table.getItem(0);
} else {
item = new TableItem(wResult.table, SWT.NONE);
}
int colnr=1;
item.setText(colnr++, Const.NVL(sapFunction.getName(), ""));
item.setText(colnr++, Const.NVL(sapFunction.getGroup(), ""));
item.setText(colnr++, Const.NVL(sapFunction.getApplication(), ""));
item.setText(colnr++, Const.NVL(sapFunction.getDescription(), ""));
}
wResult.setRowNums();
wResult.optWidth(true);
}
finally {
shell.setCursor(null);
hourGlass.dispose();
}
}
});
}
}
|
package net.c4k3.Portals;
import java.util.UUID;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Location;
public class PortalCommand implements CommandExecutor {
private BlockFace[] path = {BlockFace.DOWN, BlockFace.EAST, BlockFace.UP,
BlockFace.UP, BlockFace.UP, BlockFace.WEST, BlockFace.WEST,
BlockFace.DOWN, BlockFace.DOWN, BlockFace.DOWN};
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player player = null;
if (sender instanceof Player){
player = (Player) sender;
}
if (player == null) {
Portals.instance.getLogger().info("You must be a player to use this command.");
return true;
}
if (args.length > 1) {
player.sendMessage(ChatColor.RED + "Invalid arguments. Correct usage is /portal [buy/set]");
Portals.instance.getLogger().info(player.getName() + " entered invalid arguments.");
return true;
}
if (args.length == 0) {
teleport(player);
return true;
}
String arg = args[0].toLowerCase();
if (arg.startsWith("buy")) {
purchase(player);
return true;
} else if (arg.startsWith("set")) {
set(player);
return true;
} else if (arg.startsWith("info")) {
show_info(player);
return true;
}
player.sendMessage(ChatColor.RED + "Invalid arguments. Correct usage is /portal [buy/set]");
Portals.instance.getLogger().info(player.getName() + " entered invalid arguments.");
return true;
}
/**
* For teleporting the given player
* @param player Player who used the command
*/
@SuppressWarnings("deprecation")
private void teleport(Player player) {
Location location = player.getLocation();
Location destination = SQLite.get_other_portal(location);
/* If this portal is not a Portals portal */
if (destination == null) {
Portals.instance.getLogger().info(player.getName() + " destination was null, showing info.");
show_info(player);
return;
}
Portals.instance.getLogger().info("Teleporting "
+ player.getName() + " to " + destination.getWorld().getName()
+ " " + destination.getBlockX() + " " + destination.getBlockY()
+ " " + destination.getBlockZ());
Location fLoc = new Location(destination.getWorld(), destination.getBlockX(), destination.getBlockY() - 1, destination.getBlockZ());
player.sendBlockChange(fLoc, fLoc.getBlock().getType(), fLoc.getBlock().getData());
player.teleport(destination);
}
/**
* Show info about portals to the player
* @param player
*/
private void show_info(Player player) {
String message = ChatColor.GREEN + "Type " + ChatColor.AQUA + "/portal buy"
+ ChatColor.GREEN + " to purchase a portal set."
+ "\n Then type " + ChatColor.AQUA + "/portal set"
+ ChatColor.GREEN + " to set the portals.";
UUID uuid = player.getUniqueId();
int portal_count = SQLite.get_purchased_portals(uuid);
message += "\nYou have purchased " + ChatColor.AQUA + portal_count
+ ChatColor.GREEN + " portals.";
String log_message = "Showing info to " + player.getName() + ": " + portal_count + " portals available.";
Location unset = SQLite.get_unset_portal(uuid);
if (unset != null) {
message += "\nYou are currently placing a portal set. Take care not to die!";
log_message += "Player is currently placing a portal set.";
} else {
log_message += "Player is not currently placing a portal set.";
}
player.sendMessage(message);
Portals.instance.getLogger().info(log_message);
}
/**
* To be called when a player tries to set a portal,
* whether it's a new portal pair or the second portal.
* @param player Player setting the portal.
*/
private void set(Player player) {
UUID uuid = player.getUniqueId();
Location location = player.getLocation();
String world = location.getWorld().getName();
if (!(world.equals("world") || world.equals("world_nether") || world.equals("world_the_end"))) {
player.sendMessage(ChatColor.RED + "You cannot place portals in this world.");
Portals.instance.getLogger().info(player.getName() + " is unable to place portals in this world.");
return;
}
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
if ((Math.abs(x) < 40 && Math.abs(z) < 40 && world.equals("world") && (!player.isOp()))
|| y >= 250 || y <= 5) {
player.sendMessage(ChatColor.RED + "You cannot place place portals at this location.");
Portals.instance.getLogger().info(player.getName() + " is unable to place portals at this location.");
return;
}
Block block = location.getBlock();
for (int i = 0; i < path.length; i++) {
block = block.getRelative(path[i]);
if (block.getType() != Material.OBSIDIAN) {
player.sendMessage(ChatColor.RED + "A portal is not yet ready here. "
+ "Please build a 4 blocks high 3 blocks wide east-west portal, "
+ "making the inner size 2x1, barely enough for a single player.");
Portals.instance.getLogger().info(player.getName() + " did not have a ready portal.");
return;
}
}
Location unset = SQLite.get_unset_portal(uuid);
if (unset == null) {
set_no_unset(player);
} else {
set_has_unset(player, unset);
}
}
/**
* For when the player is using /portal set and does not have an unset portal
* @param player Player using the command
*/
private void set_no_unset(Player player) {
UUID uuid = player.getUniqueId();
Location location = player.getLocation();
int amount = SQLite.get_purchased_portals(uuid);
if (amount < 1) {
player.sendMessage(ChatColor.RED + "You do not have any portals."
+ " Purchase one with /portal buy, the price is 1 diamond block and 5 lapis blocks.");
Portals.instance.getLogger().info(player.getName() + " did not have any purchased portals.");
return;
}
SQLite.decrement_purchased_portals(uuid);
SQLite.insert_unset_portal(uuid, location);
player.sendMessage(ChatColor.GREEN + "You have successfully set one end of the portal here."
+ " Go to where you want the other end to be at, and do /portal set again."
+ " Be sure not to die or place any blocks here before you set the other end,"
+ " because in that case this location will be forgotten,"
+ " and you'll have to do everything all over again.");
Portals.instance.getLogger().info(player.getName() + " successfully created an unset portal.");
}
/**
* For when the player is using /portal set and already has an unset portal
* @param player Player using the command
* @param unset Location of the already set unset portal
*/
private void set_has_unset(Player player, Location unset) {
Location location = player.getLocation();
UUID uuid = player.getUniqueId();
SQLite.delete_unset_portal(uuid);
Block block = unset.getBlock();
for (int i = 0; i < path.length; i++) {
block = block.getRelative(path[i]);
if (block.getType() != Material.OBSIDIAN) {
player.sendMessage(ChatColor.RED + "Someone has broken the other end of the portal. "
+ "This portal has been lost.");
Portals.instance.getLogger().info(player.getName() + "'s other portal was broken.");
return;
}
}
SQLite.insert_portal_pair(unset, location);
player.sendMessage(ChatColor.GREEN + "Your portals have successfully been set up.");
Portals.instance.getLogger().info(player.getName() + " successfully created a portal set.");
}
/**
* To be called when a player purchases a portal-pair
* @param player Player who is purchasing the portals
*/
private void purchase(Player player) {
ItemStack diamond = new ItemStack(Material.DIAMOND_BLOCK);
ItemStack lapis = new ItemStack(Material.LAPIS_BLOCK);
/* First check that the player has the required items */
if (player.getInventory().containsAtLeast(diamond, 1) == false) {
player.sendMessage(ChatColor.RED + "You do not have enough "
+ "diamond blocks to purchase a portal. It costs 1 "
+ "diamond block and 5 lapis lazuli blocks to purchase a portal.");
Portals.instance.getLogger().info(player.getName() + " did not have enough diamond blocks.");
return;
}
if (player.getInventory().containsAtLeast(lapis, 5) == false) {
player.sendMessage(ChatColor.RED + "You do not have enough lapis "
+ "lazuli blocks to purchase a portal. It costs 1 diamond "
+ "block and 5 lapis lazuli blocks to purchase a portal.");
Portals.instance.getLogger().info(player.getName() + " did not have enough lapis blocks.");
return;
}
/* Now remove the correct amount of items */
int diamonds_left = 1;
int lapis_left = 5;
for (int i = 0; i < player.getInventory().getSize(); i++) {
ItemStack item = player.getInventory().getItem(i);
if (diamonds_left == 0 && lapis_left == 0)
break;
if (item == null)
continue;
if (item.getType() != Material.DIAMOND_BLOCK && item.getType() != Material.LAPIS_BLOCK)
continue;
if (item.getType() == Material.DIAMOND_BLOCK) {
if (diamonds_left == 0)
continue;
if (item.getAmount() == 1) {
player.getInventory().clear(i);
} else {
item.setAmount(item.getAmount() - 1);
}
diamonds_left = 0;
} else {
if (lapis_left == 0)
continue;
if (item.getAmount() <= lapis_left) {
lapis_left -= item.getAmount();
player.getInventory().clear(i);
} else {
item.setAmount(item.getAmount() - lapis_left);
lapis_left = 0;
}
}
}
SQLite.increment_purchased_portals(player.getUniqueId());
player.sendMessage(ChatColor.GREEN + "Congratulations, you have purchased a portal.");
Portals.instance.getLogger().info(player.getName() + " purchased 1 portal.");
}
}
|
// This file is part of the "OPeNDAP 4 Data Server (aka Hyrax)" project.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
package opendap.wcs;
import opendap.coreServlet.DispatchHandler;
import opendap.coreServlet.DispatchServlet;
import opendap.coreServlet.ReqInfo;
import opendap.coreServlet.Scrub;
import opendap.bes.BesAPI;
import opendap.bes.Version;
import opendap.bes.BESError;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import org.jdom.transform.XSLTransformer;
import org.slf4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import thredds.servlet.ServletUtil;
public class WcsDispatchHandler implements DispatchHandler {
private Logger log;
private boolean initialized;
private DispatchServlet dispatchServlet;
private String prefix = "/wcs";
public WcsDispatchHandler() {
super();
log = org.slf4j.LoggerFactory.getLogger(getClass());
initialized = false;
}
public void sendWCSResponse(HttpServletRequest request,
HttpServletResponse response) {
String dataSource = ReqInfo.getDataSource(request);
String requestSuffix = ReqInfo.getRequestSuffix(request);
boolean isContentsRequest = false;
log.debug("dataSource=" + dataSource);
String s = dataSource;
if (dataSource.startsWith("/"))
s = dataSource.substring(1, dataSource.length());
if (s.endsWith("contents") && requestSuffix.equals("html")) {
s = s.substring(0, s.lastIndexOf("contents"));
isContentsRequest = true;
}
String[] path = s.split("/", 0);
String msg = "path[" + path.length + "]:\n";
for (int i = 0; i < path.length; i++)
msg += " path[" + i + "]: " + path[i] + "\n";
log.debug(msg);
String projectName, siteName, serviceName, coverageName, dateName;
try {
if(path.length >= 6){
projectName = path[1];
siteName = path[2];
serviceName = path[3];
coverageName = path[4];
dateName = path[5];
// By adding back the rest of the bits we can support date range
// subsampling because it uses "/" to seperate the bits.
for(int i=6; i<path.length ;i++)
dateName += "/"+path[i];
log.debug("Requested DAP DATA!." +
" projectName=" + projectName +
" siteName: " + siteName +
" serviceName: " + serviceName +
" coverageName: " + coverageName +
" dateName: " + dateName +
" dataSource: " + dataSource);
sendDAPResponse(request,
response,
projectName,
siteName,
serviceName,
coverageName,
dateName);
}
else {
if (!dataSource.endsWith("/") && !isContentsRequest) {
// Now that we certain that this is a directory request we
// redirect the URL without a trailing slash to the one with.
// This keeps everything copacetic downstream when it's time
// to build the directory document.
response.sendRedirect(Scrub.urlContent(request.getContextPath() + dataSource + "/"));
}
switch (path.length) {
case 0:
log.error("This line should never be executed.");
break;
case 1:
log.debug("Requested Projects page. dataSource=" + dataSource);
sendProjectsPage(request, response);
break;
case 2:
projectName = path[1];
log.debug("Sending Sites page. " +
"projectName=" + projectName +
" dataSource=" + dataSource);
sendSitesPage(request,
response,
projectName);
break;
case 3:
projectName = path[1];
siteName = path[2];
log.debug("Sending WCSServers page." +
" projectName=" + projectName +
" siteName: " + siteName +
" dataSource=" + dataSource);
sendServersPage(request,
response,
projectName,
siteName);
break;
case 4:
projectName = path[1];
siteName = path[2];
serviceName = path[3];
log.debug("Sending CoverageOfferings page." +
" projectName=" + projectName +
" siteName: " + siteName +
" serviceName: " + serviceName +
" dataSource=" + dataSource);
sendCoverageOfferingsList(request,
response,
projectName,
siteName,
serviceName);
break;
case 5:
projectName = path[1];
siteName = path[2];
serviceName = path[3];
coverageName = path[4];
log.debug("Sending Coverage page." +
" projectName=" + projectName +
" siteName: " + siteName +
" serviceName: " + serviceName +
" coverageName: " + coverageName +
" dataSource=" + dataSource);
sendCoveragePage(request,
response,
projectName,
siteName,
serviceName,
coverageName);
break;
default:
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
log.info("Sent BAD URL.");
break;
}
}
}
catch (Exception e) {
log.error(e.getMessage());
}
}
public void init(DispatchServlet servlet, Element config) throws Exception {
if (initialized) return;
List children;
dispatchServlet = servlet;
Element e = config.getChild("prefix");
if(e!=null)
prefix = e.getTextTrim();
//Get config file name from config Element
children = config.getChildren("File");
if (children.isEmpty()) {
throw new Exception("Bad Configuration. The <Handler> " +
"element that declares " + this.getClass().getName() +
" MUST provide 1 or more <File> " +
"child elements.");
} else {
log.debug("processing WCS configuration file(s)...");
String contentPath = ServletUtil.getContentPath(servlet);
Iterator i = children.iterator();
Element fileElem;
String filename;
while (i.hasNext()) {
fileElem = (Element) i.next();
filename = contentPath + fileElem.getTextTrim();
log.debug("configuration file: " + filename);
WcsManager.init(filename);
log.debug("configuration file: " + filename+" processing complete.");
}
}
// Read Config and establish Config state.
log.info("Initialized.");
initialized = true;
}
public boolean requestCanBeHandled(HttpServletRequest request) throws Exception {
return wcsRequestDispatch(request, null, false);
}
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
wcsRequestDispatch(request, response, true);
}
private boolean wcsRequestDispatch(HttpServletRequest request,
HttpServletResponse response,
boolean sendResponse)
throws Exception {
String relativeURL = ReqInfo.getFullSourceName(request);
if(relativeURL.startsWith("/"))
relativeURL = relativeURL.substring(1,relativeURL.length());
boolean wcsRequest = false;
if (relativeURL != null) {
if (relativeURL.startsWith(prefix)) {
wcsRequest = true;
if (sendResponse) {
sendWCSResponse(request, response);
log.info("Sent WCS Response");
}
}
}
return wcsRequest;
}
public long getLastModified(HttpServletRequest req) {
return -1;
}
public void destroy() {
WcsManager.destroy();
log.info("Destroy Complete");
}
private Element newDataset(String name,
boolean isData,
boolean thredds_collection,
long size,
Date date) {
Element e;
SimpleDateFormat sdf;
String s;
Element dataset = new Element("dataset");
dataset.setAttribute("isData", isData + "");
dataset.setAttribute("thredds_collection", thredds_collection + "");
e = new Element("name");
e.setText(name);
dataset.addContent(e);
e = new Element("size");
e.setText(size + "");
dataset.addContent(e);
Element lastModified = new Element("lastmodified");
e = new Element("date");
sdf = new SimpleDateFormat("yyyy-MM-dd");
s = sdf.format(date);
e.setText(s);
lastModified.addContent(e);
e = new Element("time");
sdf = new SimpleDateFormat("HH:mm:ss z");
s = sdf.format(date);
e.setText(s);
lastModified.addContent(e);
dataset.addContent(lastModified);
return dataset;
}
public void sendProjectsPage(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Element p;
long size = 0;
String collectionName = Scrub.urlContent(ReqInfo.getFullSourceName(request));
if (collectionName.endsWith("/contents.html")) {
collectionName = collectionName.substring(0, collectionName.lastIndexOf("contents.html"));
}
if (!collectionName.endsWith("/"))
collectionName += "/";
log.debug("collectionName: " + collectionName);
Element root = newDataset(collectionName, false, true, size, new Date());
root.setAttribute("prefix", "/");
Collection<Project> projects = WcsManager.getProjects();
for (Project proj : projects) {
//size = proj.getSize();
p = newDataset(proj.getName(), false, true, 0, new Date());
root.addContent(p);
}
Document catalog = new Document(root);
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
String xsltDoc = ServletUtil.getPath(dispatchServlet, "/docs/xsl/contents.xsl");
XSLTransformer transformer = new XSLTransformer(xsltDoc);
Document contentsPage = transformer.transform(catalog);
//xmlo.output(catalog, System.out);
//xmlo.output(contentsPage, System.out);
response.setContentType("text/html");
response.setHeader("Content-Description", "dods_directory");
response.setStatus(HttpServletResponse.SC_OK);
xmlo.output(contentsPage, response.getWriter());
}
public void sendSitesPage(HttpServletRequest request,
HttpServletResponse response,
String projectName)
throws Exception {
String collectionName = Scrub.urlContent(ReqInfo.getFullSourceName(request));
if (collectionName.endsWith("/contents.html")) {
collectionName = collectionName.substring(0, collectionName.lastIndexOf("contents.html"));
}
if (!collectionName.endsWith("/"))
collectionName += "/";
log.debug("collectionName: " + collectionName);
Document catalog = new Document();
Element s;
long size = 0;
Element root = newDataset(collectionName, false, true, size, new Date());
root.setAttribute("prefix", "/");
catalog.setRootElement(root);
Project project = WcsManager.getProject(projectName);
if (project == null) {
log.error("sendSitesPage() Project: \"" + projectName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Vector<Site> sites = project.getSites();
for (Site site : sites) {
//size = WcsManager.getWcsServiceCount();
s = newDataset(site.getName(), false, true, 0, new Date());
root.addContent(s);
}
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
String xsltDoc = ServletUtil.getPath(dispatchServlet, "/docs/xsl/contents.xsl");
XSLTransformer transformer = new XSLTransformer(xsltDoc);
Document contentsPage = transformer.transform(catalog);
//xmlo.output(catalog, System.out);
//xmlo.output(contentsPage, System.out);
response.setContentType("text/html");
response.setHeader("Content-Description", "dods_directory");
response.setStatus(HttpServletResponse.SC_OK);
xmlo.output(contentsPage, response.getWriter());
}
public void sendServersPage(HttpServletRequest request,
HttpServletResponse response,
String projectName,
String siteName)
throws Exception {
String collectionName = Scrub.urlContent(ReqInfo.getFullSourceName(request));
if (collectionName.endsWith("/contents.html")) {
collectionName = collectionName.substring(0, collectionName.lastIndexOf("contents.html"));
}
if (!collectionName.endsWith("/"))
collectionName += "/";
log.debug("collectionName: " + collectionName);
Document catalog = new Document();
Element s;
long size = 0;
Element root = newDataset(collectionName, false, true, size, new Date());
root.setAttribute("prefix", "/");
catalog.setRootElement(root);
Project project = WcsManager.getProject(projectName);
if (project == null) {
log.error("sendServersPage() Project: \"" + projectName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Site site = project.getSite(siteName);
if (site == null) {
log.error("sendServersPage() Site: \"" + siteName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Collection<WcsService> services = WcsManager.getWcsServices();
for (WcsService service : services) {
//size = service.getCoverageCount();
s = newDataset(service.getName(), false, true, 0, new Date());
root.addContent(s);
}
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
String xsltDoc = ServletUtil.getPath(dispatchServlet, "/docs/xsl/contents.xsl");
XSLTransformer transformer = new XSLTransformer(xsltDoc);
Document contentsPage = transformer.transform(catalog);
//xmlo.output(catalog, System.out);
//xmlo.output(contentsPage, System.out);
response.setContentType("text/html");
response.setHeader("Content-Description", "dods_directory");
response.setStatus(HttpServletResponse.SC_OK);
xmlo.output(contentsPage, response.getWriter());
}
public void sendCoverageOfferingsList(HttpServletRequest request,
HttpServletResponse response,
String projectName,
String siteName,
String serviceName)
throws Exception {
String collectionName = Scrub.urlContent(ReqInfo.getFullSourceName(request));
if (collectionName.endsWith("/contents.html")) {
collectionName = collectionName.substring(0, collectionName.lastIndexOf("contents.html"));
}
if (!collectionName.endsWith("/"))
collectionName += "/";
log.debug("collectionName: " + collectionName);
/*
Element root = newDataset(collectionName, false, true, size, new Date());
root.setAttribute("prefix", "/");
catalog.setRootElement(root);
*/
Project project = WcsManager.getProject(projectName);
if (project == null) {
log.error("sendCoverageOfferingsList() Project: \"" + projectName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Site site = project.getSite(siteName);
if (site == null) {
log.error("sendCoverageOfferingsList() Site: \"" + siteName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
WcsService service = WcsManager.getWcsService(serviceName);
if (service == null) {
log.error("sendCoverageOfferingsList() WcsService: \"" + serviceName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
String xsltDoc = ServletUtil.getPath(dispatchServlet, "/docs/xsl/wcs_coveragesList.xsl");
XSLTransformer transformer = new XSLTransformer(xsltDoc);
service.lock();
try {
Document capDoc = service.getCapabilitiesDocument();
//xmlo.output(capDoc, System.out);
Document contentsPage = transformer.transform(capDoc);
//xmlo.output(contentsPage, System.out);
response.setContentType("text/html");
response.setHeader("Content-Description", "dods_directory");
response.setStatus(HttpServletResponse.SC_OK);
xmlo.output(contentsPage, response.getWriter());
}
finally {
service.unlock();
}
}
public void sendCoveragePage(HttpServletRequest request,
HttpServletResponse response,
String projectName,
String siteName,
String serviceName,
String coverageName)
throws Exception {
/*
String collectionName = Scrub.urlContent(ReqInfo.getFullSourceName(request));
if (collectionName.endsWith("/contents.html")) {
collectionName = collectionName.substring(0, collectionName.lastIndexOf("contents.html"));
}
if (!collectionName.endsWith("/"))
collectionName += "/";
log.debug("collectionName: " + collectionName);
*/
Project project = WcsManager.getProject(projectName);
if (project == null) {
log.error("sendCoveragePage() Project: \"" + projectName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Site site = project.getSite(siteName);
if (site == null) {
log.error("sendCoveragePage() Site: \"" + siteName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
WcsService service = WcsManager.getWcsService(serviceName);
if (service == null) {
log.error("sendCoveragePage() WcsService: \"" + serviceName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
service.lock();
try {
WcsCoverageOffering coverage = service.getCoverageOffering(coverageName);
if (coverage == null) {
log.error("sendCoveragePage() Coverage: \"" + coverageName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
else {
log.debug("sendCoveragePage() Sending Coverage: \"" + coverage.getName() + "\"");
Element coff = coverage.getConfigElement();
Element s;
DateFormat df = new SimpleDateFormat("yyy-mm-dd");
coff.detach();
Document doc = new Document(coff);
Document pageContent = null;
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
String xsltDoc = ServletUtil.getPath(dispatchServlet, "/docs/xsl/wcs_coveragePage.xsl");
XSLTransformer transformer = new XSLTransformer(xsltDoc);
if(coverage.hasTemporalDomain()){
log.debug("sendCoveragePage() " + coverage.getName() +
" has a temporal domain. Adding time datasets.");
Element dset = coff.getChild(WCS.DOMAIN_SET,WCS.NS);
Element tdom = dset.getChild(WCS.TEMPORAL_DOMAIN,WCS.NS);
Vector<String> dates = coverage.generateDateStrings();
for (String day : dates) {
s = newDataset(day, true, false, 0, df.parse(day));
tdom.addContent(s);
}
pageContent = transformer.transform(doc);
}
else if(coverage.hasSpatialDomain()){
log.debug("sendCoveragePage() " + coverage.getName() +
" has no temporal domain.");
pageContent = transformer.transform(doc);
}
xmlo.output(coff, System.out);
xmlo.output(pageContent, System.out);
response.setContentType("text/html");
response.setHeader("Content-Description", "dods_directory");
response.setStatus(HttpServletResponse.SC_OK);
xmlo.output(pageContent, response.getWriter());
}
}
catch(Exception e){
e.printStackTrace(System.out);
}
finally {
service.unlock();
}
}
public void sendDAPResponse(HttpServletRequest request,
HttpServletResponse response,
String projectName,
String siteName,
String serviceName,
String coverageName,
String dateName)
throws Exception {
String dataSource = ReqInfo.getDataSource(request);
String requestSuffix = ReqInfo.getRequestSuffix(request);
Project project = WcsManager.getProject(projectName);
if (project == null) {
log.error("sendDAPResponse() Project: \"" + projectName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Site site = project.getSite(siteName);
if (site == null) {
log.error("sendDAPResponse() Site: \"" + siteName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
WcsService service = WcsManager.getWcsService(serviceName);
if (service == null) {
log.error("sendDAPResponse() WcsService: \"" + serviceName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String wcsRequestURL="";
service.lock();
try {
WcsCoverageOffering coverage = service.getCoverageOffering(coverageName);
if (coverage == null) {
log.error("sendDAPResponse() Coverage: \"" + serviceName + "\" not found.");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
if(dateName.equals("dataset"))
dateName = null;
wcsRequestURL = service.getWcsRequestURL(site,coverage,dateName);
log.debug("wcsRequestURL: "+wcsRequestURL);
}
catch (Exception e){
e.printStackTrace(System.out);
}
finally{
service.unlock();
}
if ( // DDS Response?
requestSuffix.equalsIgnoreCase("dds")
) {
sendDDS(request, response, wcsRequestURL);
log.info("Sent DDS");
} else if ( // DAS Response?
requestSuffix.equalsIgnoreCase("das")
) {
sendDAS(request, response, wcsRequestURL);
log.info("Sent DAS");
} else if ( // DDX Response?
requestSuffix.equalsIgnoreCase("ddx")
) {
sendDDX(request, response, wcsRequestURL);
log.info("Sent DDX");
} else if ( // DAP2 (aka .dods) Response?
requestSuffix.equalsIgnoreCase("dods")
) {
sendDAP2Data(request, response, wcsRequestURL);
log.info("Sent DAP2 Data");
} else if ( // ASCII Data Response.
requestSuffix.equalsIgnoreCase("asc") ||
requestSuffix.equalsIgnoreCase("ascii")
) {
sendASCII(request, response, wcsRequestURL);
log.info("Sent ASCII");
} else if ( // Info Response?
requestSuffix.equalsIgnoreCase("info")
) {
sendINFO(request, response, wcsRequestURL);
log.info("Sent Info");
} else if ( //HTML Request Form (aka The Interface From Hell) Response?
requestSuffix.equalsIgnoreCase("html") ||
requestSuffix.equalsIgnoreCase("htm")
) {
sendHTMLRequestForm(request, response, wcsRequestURL);
log.info("Sent HTML Request Form");
} else if (requestSuffix.equals("")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
log.info("Sent BAD URL (missing Suffix)");
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
log.info("Sent BAD URL - not an OPeNDAP request suffix.");
}
}
private void sendDDS(HttpServletRequest request, HttpServletResponse response, String wcsRequestURL) throws Exception {
String dataSource = ReqInfo.getDataSource(request);
String constraintExpression = ReqInfo.getConstraintExpression(request);
log.debug("sendDDS() for dataset: " + dataSource);
response.setContentType("text/plain");
response.setHeader("XDODS-Server", Version.getXDODSServerVersion(request));
response.setHeader("XOPeNDAP-Server", Version.getXOPeNDAPServerVersion(request));
response.setHeader("XDAP", Version.getXDAPVersion(request));
response.setHeader("Content-Description", "dods_dds");
// Commented because of a bug in the OPeNDAP C++ stuff...
//response.setHeader("Content-Encoding", "plain");
response.setStatus(HttpServletResponse.SC_OK);
OutputStream os = response.getOutputStream();
ByteArrayOutputStream erros = new ByteArrayOutputStream();
if(!BesAPI.besGetWcsTransaction( BesAPI.DDS,
dataSource,
constraintExpression,
os,
erros,
BesAPI.DAP2_ERRORS,
wcsRequestURL)
){
String msg = new String(erros.toByteArray());
log.error("sendDDS() encounterd a BESError: "+msg);
os.write(msg.getBytes());
}
os.flush();
}
private void sendDAS(HttpServletRequest request, HttpServletResponse response, String wcsRequestURL) throws Exception {
String dataSource = ReqInfo.getDataSource(request);
String constraintExpression = ReqInfo.getConstraintExpression(request);
log.debug("sendDAS() for dataset: " + dataSource);
response.setContentType("text/plain");
response.setHeader("XDODS-Server", Version.getXDODSServerVersion(request));
response.setHeader("XOPeNDAP-Server", Version.getXOPeNDAPServerVersion(request));
response.setHeader("XDAP", Version.getXDAPVersion(request));
response.setHeader("Content-Description", "dods_dds");
// Commented because of a bug in the OPeNDAP C++ stuff...
//response.setHeader("Content-Encoding", "plain");
response.setStatus(HttpServletResponse.SC_OK);
OutputStream os = response.getOutputStream();
ByteArrayOutputStream erros = new ByteArrayOutputStream();
if(!BesAPI.besGetWcsTransaction(
BesAPI.DAS,
dataSource,
constraintExpression,
os,
erros,
BesAPI.DAP2_ERRORS,
wcsRequestURL)){
String msg = new String(erros.toByteArray());
log.error("sendDAS() encounterd a BESError: "+msg);
os.write(msg.getBytes());
}
os.flush();
}
private void sendDDX(HttpServletRequest request, HttpServletResponse response, String wcsRequestURL) throws Exception {
String dataSource = ReqInfo.getDataSource(request);
String constraintExpression = ReqInfo.getConstraintExpression(request);
log.debug("sendDDX() for dataset: " + dataSource);
response.setContentType("text/plain");
response.setHeader("XDODS-Server", Version.getXDODSServerVersion(request));
response.setHeader("XOPeNDAP-Server", Version.getXOPeNDAPServerVersion(request));
response.setHeader("XDAP", Version.getXDAPVersion(request));
response.setHeader("Content-Description", "dods_dds");
// Commented because of a bug in the OPeNDAP C++ stuff...
//response.setHeader("Content-Encoding", "plain");
response.setStatus(HttpServletResponse.SC_OK);
OutputStream os = response.getOutputStream();
ByteArrayOutputStream erros = new ByteArrayOutputStream();
if(!BesAPI.besGetWcsTransaction(
BesAPI.DDX,
dataSource,
constraintExpression,
os,
erros,
BesAPI.DAP2_ERRORS,
wcsRequestURL)){
String msg = new String(erros.toByteArray());
log.error("sendDDX() encounterd a BESError: "+msg);
os.write(msg.getBytes());
}
os.flush();
}
private void sendDAP2Data(HttpServletRequest request, HttpServletResponse response, String wcsRequestURL) throws Exception {
String dataSource = ReqInfo.getDataSource(request);
String constraintExpression = ReqInfo.getConstraintExpression(request);
log.debug("sendDAP2Data() for dataset: " + dataSource);
response.setContentType("text/plain");
response.setHeader("XDODS-Server", Version.getXDODSServerVersion(request));
response.setHeader("XOPeNDAP-Server", Version.getXOPeNDAPServerVersion(request));
response.setHeader("XDAP", Version.getXDAPVersion(request));
response.setHeader("Content-Description", "dods_dds");
// Commented because of a bug in the OPeNDAP C++ stuff...
//response.setHeader("Content-Encoding", "plain");
response.setStatus(HttpServletResponse.SC_OK);
OutputStream os = response.getOutputStream();
ByteArrayOutputStream erros = new ByteArrayOutputStream();
if(!BesAPI.besGetWcsTransaction(
BesAPI.DAP2,
dataSource,
constraintExpression,
os,
erros,
BesAPI.DAP2_ERRORS,
wcsRequestURL)){
String msg = new String(erros.toByteArray());
log.error("sendDAP2Data() encounterd a BESError: "+msg);
os.write(msg.getBytes());
}
os.flush();
}
private void sendASCII(HttpServletRequest request, HttpServletResponse response, String wcsRequestURL) throws Exception {
String dataSource = ReqInfo.getDataSource(request);
String constraintExpression = ReqInfo.getConstraintExpression(request);
log.debug("sendASCII() for dataset: " + dataSource);
response.setContentType("text/plain");
response.setHeader("XDODS-Server", Version.getXDODSServerVersion(request));
response.setHeader("XOPeNDAP-Server", Version.getXOPeNDAPServerVersion(request));
response.setHeader("XDAP", Version.getXDAPVersion(request));
response.setHeader("Content-Description", "dods_dds");
// Commented because of a bug in the OPeNDAP C++ stuff...
//response.setHeader("Content-Encoding", "plain");
response.setStatus(HttpServletResponse.SC_OK);
OutputStream os = response.getOutputStream();
ByteArrayOutputStream erros = new ByteArrayOutputStream();
if(!BesAPI.besGetWcsTransaction(
BesAPI.ASCII,
dataSource,
constraintExpression,
os,
erros,
BesAPI.XML_ERRORS,
wcsRequestURL)){
BESError besError = new BESError(new ByteArrayInputStream(erros.toByteArray()));
besError.sendErrorResponse(dispatchServlet,response);
log.error("sendASCII() encounterd a BESError: "+besError.getMessage());
}
os.flush();
}
private void sendINFO(HttpServletRequest request, HttpServletResponse response, String wcsRequestURL) throws Exception {
String dataSource = ReqInfo.getDataSource(request);
String constraintExpression = ReqInfo.getConstraintExpression(request);
log.debug("sendINFO() for dataset: " + dataSource);
response.setContentType("text/html");
response.setHeader("XDODS-Server", Version.getXDODSServerVersion(request));
response.setHeader("XOPeNDAP-Server", Version.getXOPeNDAPServerVersion(request));
response.setHeader("XDAP", Version.getXDAPVersion(request));
response.setHeader("Content-Description", "dods_dds");
// Commented because of a bug in the OPeNDAP C++ stuff...
//response.setHeader("Content-Encoding", "plain");
response.setStatus(HttpServletResponse.SC_OK);
OutputStream os = response.getOutputStream();
ByteArrayOutputStream erros = new ByteArrayOutputStream();
if(!BesAPI.besGetWcsTransaction(
BesAPI.INFO_PAGE,
dataSource,
constraintExpression,
os,
erros,
BesAPI.XML_ERRORS,
wcsRequestURL)){
BESError besError = new BESError(new ByteArrayInputStream(erros.toByteArray()));
besError.sendErrorResponse(dispatchServlet,response);
log.error("sendINFO() encounterd a BESError: "+besError.getMessage());
}
os.flush();
}
private void sendHTMLRequestForm(HttpServletRequest request, HttpServletResponse response, String wcsRequestURL) throws Exception {
String dataSource = ReqInfo.getDataSource(request);
String requestSuffix = ReqInfo.getRequestSuffix(request);
log.debug("sendHTMLRequestForm() for dataset: " + dataSource);
response.setContentType("text/html");
response.setHeader("XDODS-Server", Version.getXDODSServerVersion(request));
response.setHeader("XOPeNDAP-Server", Version.getXOPeNDAPServerVersion(request));
response.setHeader("XDAP", Version.getXDAPVersion(request));
response.setHeader("Content-Description", "dods_form");
response.setStatus(HttpServletResponse.SC_OK);
log.debug("sendHTMLRequestForm(): Sending HTML Data Request Form For: "
+ dataSource +
" CE: '" + request.getQueryString() + "'");
OutputStream os = response.getOutputStream();
String url = request.getRequestURL().toString();
int suffix_start = url.lastIndexOf("." + requestSuffix);
url = url.substring(0, suffix_start);
log.debug("sendHTMLRequestForm(): HTML Form URL: " + url);
ByteArrayOutputStream erros = new ByteArrayOutputStream();
if(!BesAPI.writeWcsHTMLForm(
dataSource,
url,
os,
erros,wcsRequestURL)){
BESError besError = new BESError(new ByteArrayInputStream(erros.toByteArray()));
besError.sendErrorResponse(dispatchServlet,response);
String msg = besError.getMessage();
System.out.println(msg);
System.err.println(msg);
log.error("sendHTMLRequestForm() encounterd a BESError: "+msg);
}
os.flush();
}
}
|
package com.humegatech.inliner;
import java.nio.charset.Charset;
import org.apache.commons.lang.StringUtils;
import com.phloc.css.ECSSVersion;
import com.phloc.css.ICSSWriterSettings;
import com.phloc.css.decl.CSSDeclaration;
import com.phloc.css.decl.CSSSelector;
import com.phloc.css.decl.CSSStyleRule;
import com.phloc.css.decl.CascadingStyleSheet;
import com.phloc.css.reader.CSSReader;
import com.phloc.css.writer.CSSWriterSettings;
public class CssInliner {
private static final Charset CHARSET = Charset.forName("UTF-8");
private static final ECSSVersion CSS_VERSION = ECSSVersion.CSS30;
// Using 0, but value doesn't matter for us since we're not indenting (or
// supporting indented CSS yet)
private static final int INDENT_LEVEL = 0;
/*
* Passing true for the second parameter causes the writer to strip all
* whitespace from the output: perfect for inlining
*/
private static final ICSSWriterSettings WRITER_SETTINGS = new CSSWriterSettings(ECSSVersion.CSS30, true);
/**
* Take CSS and a class selector and produce the css inlined
*
* @param css
* CSS
* @param cssClassSelector
* class for which to inline the css
* @return String representing inlined css
*/
public static String inlineCssClass(final String css, final String cssClassSelector) {
final String classDeclarations = getDeclarationsForClassSelector(cssClassSelector, css);
return (StringUtils.isNotBlank(classDeclarations) ? classDeclarations : null);
}
/**
* Take CSS and an id selector and produce the css inlined
*
* @param css
* CSS
* @param cssIdSelector
* id for which to inline the css
* @return String representing inlined css
*/
public static String inlineCssId(final String css, final String cssIdSelector) {
final String idDeclarations = getDeclarationsForIdSelector(cssIdSelector, css);
return (StringUtils.isNotBlank(idDeclarations) ? idDeclarations : "");
}
/**
* Return the declarations for a CSS class selector as a String suitable for
* inlining (newlines, extra spaces, etc. removed). Assumes '.' starts class
* selector name so will append it if missing.
*
* @param classSelectorName
* CSS selector element name
* @param css
* CSS document
* @return declarations for selector stripped of whitespace
*/
protected static String getDeclarationsForClassSelector(final String classSelectorName, final String css) {
final String localClassSelectorName = formatSelector(CssSelector.CLASS_SELECTOR, classSelectorName);
return getDeclarations(localClassSelectorName, css);
}
/**
* Return the declarations for a CSS id selector as a String suitable for
* inlining (newlines, extra spaces, etc. removed). Assumes '#' starts id
* selector name so will append it if missing.
*
* @param idSelectorName
* CSS selector element name
* @param css
* CSS document
* @return declarations for selector stripped of whitespace
*/
protected static String getDeclarationsForIdSelector(final String idSelectorName, final String css) {
final String localIdSelectorName = formatSelector(CssSelector.ID_SELECTOR, idSelectorName);
return getDeclarations(localIdSelectorName, css);
}
/**
* Return the declarations for a CSS inlining (newlines, extra spaces, etc. removed).
*
* @param selectorName
* CSS selector element name
* @param css
* CSS document
* @return declarations for selector stripped of whitespace
*/
protected static String getDeclarations(final String selectorName, final String css) {
String declarationString = "";
for (final CSSStyleRule styleRule : parseCss(css).getAllStyleRules()) {
for (final CSSSelector selector : styleRule.getAllSelectors()) {
if (selector.getAsCSSString(WRITER_SETTINGS, INDENT_LEVEL).equalsIgnoreCase(selectorName)) {
for (final CSSDeclaration declaration : styleRule.getAllDeclarations()) {
declarationString += declaration.getAsCSSString(WRITER_SETTINGS, INDENT_LEVEL) + ";";
}
break;
}
}
}
return declarationString;
}
/**
* Wraps whatever CSS parse implementation we're using
*
* @param css
* CSS document
* @return CascadingStyleSheet object representing the CSS
*/
protected static CascadingStyleSheet parseCss(final String css) {
final CascadingStyleSheet aCss = CSSReader.readFromString(css, CHARSET, CSS_VERSION);
return aCss;
}
private static String formatSelector(final CssSelector selector, final String selectorName) {
return selectorName.startsWith(selector.selector()) ? selectorName : selector.selector() + selectorName;
}
}
|
package com.jaamsim.render;
import java.util.ArrayList;
import java.util.Arrays;
import com.jaamsim.ui.View;
public class VisibilityInfo {
private static final int[] ALL_VIEWS = new int[0];
private final int[] viewIDs;
private final double minDist;
private final double maxDist;
public VisibilityInfo(ArrayList<View> views, double minDist, double maxDist) {
if (views == null || views.size() == 0) {
viewIDs = ALL_VIEWS;
}
else {
viewIDs = new int[views.size()];
for (int i = 0; i < views.size(); i++)
viewIDs[i] = views.get(i).getID();
}
this.minDist = minDist;
this.maxDist = maxDist;
}
public final boolean isVisible(int viewID, double dist) {
// Test the distance is in the visible range
if (dist < minDist || dist > maxDist)
return false;
return isVisible(viewID);
}
public final boolean isVisible(int viewID) {
// If no limitation on views, we must be visible
if (viewIDs.length == 0)
return true;
for (int i = 0; i < viewIDs.length; i++) {
if (viewIDs[i] == viewID)
return true;
}
return false;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof VisibilityInfo)) {
return false;
}
VisibilityInfo vi = (VisibilityInfo)o;
return Arrays.equals(vi.viewIDs, viewIDs) && vi.minDist == minDist && vi.maxDist == maxDist;
}
}
|
//Namespace
package com.katujo.web.utils;
//Java imports
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Scannotation imports
import org.scannotation.AnnotationDB;
import org.scannotation.WarUrlFinder;
//Google imports
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* The router filter that routes incoming request to the annotated classes using the package and
* the method name as the path.
* @author Johan Hertz
* @author Johanna Sundh
*/
public class RouterFilter implements Filter
{
//The map to hold the routes <String=path, Route>
private final Map<String, Route> routes = new ConcurrentHashMap<String, Route>();
//The map/set to hold the path where to mask request data on error (String=path, IGNORE)
private final Map<String, Object> maskOnError = new ConcurrentHashMap<String, Object>();
//The no parameters object
private static final Object[] NO_PARAMETERS = new Object[]{};
//The JSON content type
private static final String JSON_CONTENT_TYPE = "application/json";
//The character encoding to use when sending back JSON data
private static final String JSON_CHARACTER_ENCODING = "UTF-8";
//The binary array content type
private static final String BINARY_CONTENT_TYPE = "application/octet-stream";
//The thread local field to hold the HTTP request data
private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<>();
//The thread local field to hold the HTTP response data
private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<>();
/*
* Init the filter.
* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig config) throws ServletException
{
//Try to init the filter
try
{
//Get the path where to mask request data
for(String path : maskRequestDataOnError(config))
maskOnError.put(path, NO_PARAMETERS);
//Get the scanned classes
Set<String> classesScanned = scanRoutes(config);
//Get the web.xml classes
Set<String> classesWebXml = webXmlRoutes(config);
//Create the classes
Set<String> classes = new HashSet<String>(classesScanned.size() + classesWebXml.size());
//Add the classes
classes.addAll(classesScanned);
classes.addAll(classesWebXml);
//Get the base package
//TODO: Remove legacy scan property rename to scan
String basePackage = config.getInitParameter("base-package") != null ? config.getInitParameter("base-package") : config.getInitParameter("scan");
//Set the default base package to empty string array
String[] basePackages = basePackage != null ? basePackage.split(";") : new String[0];
//Get the extension that will be added to the end of every path
String extension = config.getInitParameter("extension");
//Get the print paths flag
boolean printPaths = "true".equals(config.getInitParameter("print-paths"));
//Create the route objects
for(String clazz : classes)
{
//Get the routes class
Class<?> routeClass = Class.forName(clazz);
//Get the package name
String routePackage = routeClass.getPackage().getName();
//Create the base path
String base = routePackage;
//Set base
if(basePackages != null && basePackages.length != 0)
{
//Found
boolean found = false;
//Check every base package
for(String basePack : basePackages)
{
//Check if the package match the base package
if(routePackage.startsWith(basePack))
{
//Set base
base = routePackage.substring(basePack.length()).replace('.', '/') + "/";
//Set found
found = true;
}
}
//Route does not match any of the base packages
if(!found)
continue;
}
//Create an instance of the route
Object instance = routeClass.getConstructor(new Class[] {}).newInstance(new Object[]{});
//Add the controller methods
for(Method method : routeClass.getMethods())
{
//Only add public methods
if(!"public".equals(Modifier.toString(method.getModifiers())))
continue;
//Only add methods that are declared in route class
if(method.getDeclaringClass() != routeClass)
continue;
//Create the parameter type
int type = Route.NO_PARAMETER;
//If the parameters length is 1 only allow JSON parameters and primitives
if(method.getParameterTypes().length == 1)
{
if(method.getParameterTypes()[0] == JsonObject.class) type = Route.JSON_OBJECT;
else if(method.getParameterTypes()[0] == JsonArray.class) type = Route.JSON_ARRAY;
else if(method.getParameterTypes()[0] == JsonElement.class) type = Route.JSON_ELEMENT;
else if(method.getParameterTypes()[0] == boolean.class || method.getParameterTypes()[0] == Boolean.class) type = Route.PRIMITIVE_BOOLEAN;
else if(method.getParameterTypes()[0] == double.class || method.getParameterTypes()[0] == Double.class) type = Route.PRIMITIVE_DOUBLE;
else if(method.getParameterTypes()[0] == int.class || method.getParameterTypes()[0] == Integer.class) type = Route.PRIMITIVE_INT;
else if(method.getParameterTypes()[0] == long.class || method.getParameterTypes()[0] == Long.class) type = Route.PRIMITIVE_LONG;
else if(method.getParameterTypes()[0] == String.class) type = Route.PRIMITIVE_STRING;
else continue;
}
//If the parameter length is 2 only allow HttpServletRequest and HttpServletResponse
else if(method.getParameterTypes().length == 2 &&
method.getParameterTypes()[0] == HttpServletRequest.class &&
method.getParameterTypes()[1] == HttpServletResponse.class)
type = Route.REQUEST_RESPONSE;
//Ignore any other method that has parameter
else if(method.getParameterTypes().length != 0)
continue;
//Create the path
String path = base + method.getName() + extension;
//Check that the path has not already been added unique
if(routes.containsKey(path))
throw new Exception("Path " + path + " is not unique");
//Add the path
routes.put(path, new Route(instance, method, type));
}
}
//Create the out put list
List<String> list = new ArrayList<>();
//Print the paths setup
for(String path : routes.keySet())
list.add(routes.get(path).instance.getClass().getSimpleName() + "(" + (routes.get(path).method.getName() + "): " + path));
//Sort the list
Collections.sort(list);
//Print the list
for(String item : list)
if(printPaths)
System.out.println(item);
}
//Failed
catch(Exception ex)
{
throw new ServletException("Failed to init RouterFilter", ex);
}
}
/*
* Run the filter.
* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException
{
//Try to run the filter
try
{
//Cast the request and response
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//Set the thread local fields
RouterFilter.request.set(request);
RouterFilter.response.set(response);
//Invoke the route
Object data = invoke(request, response);
//Send the data as the response
send(request, response, data);
}
//Failed
catch(Exception ex)
{
throw new ServletException("Failed to route request", ex);
}
//Clean up
finally
{
RouterFilter.request.set(null);
RouterFilter.response.set(null);
}
}
/**
* Invoke a route.
* @param request
* @param response
* @return
* @throws Exception
*/
private Object invoke(HttpServletRequest request, HttpServletResponse response) throws Exception
{
//Create fields that will be used in the exception message
String path = null;
JsonElement requestData = null;
//Try to invoke route
try
{
//Get the path
path = request.getServletPath();
//Try to get the path from the URI instead
if(path == null || "".equals(path))
{
//Get the URI
String uri = request.getRequestURI();
//Get the index of the second /
int index = uri.indexOf('/', 3);
//Clean the path
path = uri.substring(index);
//Remove the first duplicate /
if(path.startsWith("
path = path.substring(1);
}
//Get the route
Route route = routes.get(path);
//Check if there is a route for the path
if(route == null)
throw new Exception("Could not find a route for path \"" + path + "\"");
//Create the return data
Object returnData = null;
//Get the request data
requestData = JsonFilter.getJson();
//Invoke the method on the instance with the no parameters
if(route.parameterType == Route.NO_PARAMETER)
returnData = route.method.invoke(route.instance, NO_PARAMETERS);
//Invoke the method on the instance with a JSON object parameter
else if(route.parameterType == Route.JSON_OBJECT)
returnData = route.method.invoke(route.instance, requestData == null ? requestData : requestData.getAsJsonObject());
//Invoke the method on the instance with a JSON array parameter
else if(route.parameterType == Route.JSON_ARRAY)
returnData = route.method.invoke(route.instance, requestData == null ? requestData : requestData.getAsJsonArray());
//Invoke the method on the instance with a JSON element parameter
else if(route.parameterType == Route.JSON_ELEMENT)
returnData = route.method.invoke(route.instance, requestData);
//Invoke the method on the instance with a boolean as the parameter
else if(route.parameterType == Route.PRIMITIVE_BOOLEAN)
returnData = route.method.invoke(route.instance, requestData.getAsBoolean());
//Invoke the method on the instance with a double as the parameter
else if(route.parameterType == Route.PRIMITIVE_DOUBLE)
returnData = route.method.invoke(route.instance, requestData.getAsDouble());
//Invoke the method on the instance with a integer as the parameter
else if(route.parameterType == Route.PRIMITIVE_INT)
returnData = route.method.invoke(route.instance, requestData.getAsInt());
//Invoke the method on the instance with a long as the parameter
else if(route.parameterType == Route.PRIMITIVE_LONG)
returnData = route.method.invoke(route.instance, requestData.getAsLong());
//Invoke the method on the instance with a string as the parameter
else if(route.parameterType == Route.PRIMITIVE_STRING)
returnData = route.method.invoke(route.instance, requestData.getAsString());
//Invoke the method on the instance with the request and response parameters
else if(route.parameterType == Route.REQUEST_RESPONSE)
returnData = route.method.invoke(route.instance, new Object[]{request, response});
//The parameter type has not been implemented yet
else throw new Exception("The parameter type " + route.parameterType + " has not been implemented");
//Return the return data
return returnData;
}
//Failed
catch(Exception ex)
{
//Create the message
String message = "Failed to invoke route for path " + path;
//Check if masked
if(maskOnError.containsKey(path))
message += "\n\tRequest Data: **MASKED**";
//Check if request data is set
else if(requestData == null)
message += " (request data not set)";
//Add the request data to the exception
else message += "\n\tRequest Data: " + requestData.toString();
//Throw the exception
throw new Exception(message, ex);
}
}
/**
* Send the return data as the response.
* @param request
* @param response
* @param data
* @throws Exception
*/
private void send(HttpServletRequest request, HttpServletResponse response, Object data) throws Exception
{
//Try to send the data
try
{
//Don't do anything if the response data is not set
if(data == null)
;
//Send the response back as JSON data
else if(data instanceof JsonElement)
{
//Set the response type
response.setContentType(JSON_CONTENT_TYPE);
response.setCharacterEncoding(JSON_CHARACTER_ENCODING);
//Print the JSON to the output stream
response.getWriter().print(data.toString());
}
//Send the response back as a JSON string primitive
else if(data instanceof String)
{
//Set the response type
response.setContentType(JSON_CONTENT_TYPE);
response.setCharacterEncoding(JSON_CHARACTER_ENCODING);
//Create the primitive
JsonPrimitive primitive = new JsonPrimitive((String) data);
//Print the JSON to the output stream
response.getWriter().print(primitive.toString());
}
//Send the response back as a JSON number primitive
else if(data instanceof Double || data instanceof Long || data instanceof Integer || data instanceof Number)
{
//Set the response type
response.setContentType(JSON_CONTENT_TYPE);
response.setCharacterEncoding(JSON_CHARACTER_ENCODING);
//Create the primitive
JsonPrimitive primitive = new JsonPrimitive((Number) data);
//Print the JSON to the output stream
response.getWriter().print(primitive.toString());
}
//Send the response back as a JSON number primitive that can be cast as a date
else if(data instanceof Date)
{
//Set the response type
response.setContentType(JSON_CONTENT_TYPE);
response.setCharacterEncoding(JSON_CHARACTER_ENCODING);
//Create the primitive
JsonPrimitive primitive = new JsonPrimitive(((Date) data).getTime());
//Print the JSON to the output stream
response.getWriter().print(primitive.toString());
}
//Send the response back as a JSON boolean primitive
else if(data instanceof Boolean)
{
//Set the response type
response.setContentType(JSON_CONTENT_TYPE);
response.setCharacterEncoding(JSON_CHARACTER_ENCODING);
//Create the primitive
JsonPrimitive primitive = new JsonPrimitive((boolean) data);
//Print the JSON to the output stream
response.getWriter().print(primitive.toString());
}
//Send the response back as binary data
else if(data instanceof byte[])
{
//Set the response type
response.setContentType(BINARY_CONTENT_TYPE);
//Write the data
response.getOutputStream().write((byte[]) data);
}
//The data type returned by the route is unrecognised
else throw new Exception("Unrecognised route return type " + data.getClass().getCanonicalName());
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to send data response", ex);
}
}
/*
* Destroy the filter.
* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {}
/**
* Get the request (for the current request thread).
* @return
*/
public static HttpServletRequest getRequest()
{
return request.get();
}
/**
* Get the response (for the current request thread).
* @return
*/
public static HttpServletResponse getResponse()
{
return response.get();
}
/**
* Scan for the routes.
* @param config
* @return
* @throws Exception
*/
private static Set<String> scanRoutes(FilterConfig config) throws Exception
{
//Try to scan for routes
try
{
//Get the URL
URL urlClasses = WarUrlFinder.findWebInfClassesPath(config.getServletContext());
URL[] urlLib = WarUrlFinder.findWebInfLibClasspaths(config.getServletContext());
//Could not find the URL
if(urlClasses == null)
return new HashSet<String>();
//Set the libraries to scan
String[] libraries = config.getInitParameter("scan-library") != null ? config.getInitParameter("scan-library").split(";") : new String[0];
//Create the annotation database
AnnotationDB database = new AnnotationDB();
//Create empty list for URLs
List<URL> list = new ArrayList<URL>();
//Add urlClasses
list.add(urlClasses);
//Search library
for(URL url : urlLib)
{
for(String library : libraries)
{
//Get name of file
String name = url.getFile().substring(url.getFile().lastIndexOf("/") +1);
//Add to list if name matches library
if(library.toLowerCase().equals(name.toLowerCase()))
list.add(url);
}
}
//Create array
URL[] allUrls = new URL[list.size()];
//Fill array
for(int i = 0; i < list.size(); i++)
allUrls[i] = list.get(i);
//Scan the URL
database.scanArchives(allUrls);
//Get the classes marked with the controller annotation
Set<String> classes = database.getAnnotationIndex().get(com.katujo.web.utils.Route.class.getCanonicalName());
//Return empty if not set
if(classes == null)
return new HashSet<String>();
//Return the classes
return classes;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to scan for routes", ex);
}
}
/**
* Read the routes from the web.xml file.
* @param config
* @return
* @throws Exception
*/
private static Set<String> webXmlRoutes(FilterConfig config) throws Exception
{
//Try to read the routes from the web.xml file
try
{
//Get the routes
String routes = config.getInitParameter("routes");
//Check if routes is set
if(routes == null)
return new HashSet<String>();
//Split the routes
String[] split = routes.split(";");
//Create the set
Set<String> classes = new HashSet<String>();
//Add the classes
for(String item : split)
if(!item.trim().equals(""))
classes.add(item.trim());
//Return the set
return classes;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to read web.xml routes", ex);
}
}
/**
* Read the routes from the web.xml file.
* @param config
* @return
* @throws Exception
*/
private static Set<String> maskRequestDataOnError(FilterConfig config) throws Exception
{
//Try to read the routes from the web.xml file
try
{
//Get the routes
String paths = config.getInitParameter("mask-request-data-on-error");
//Check if routes is set
if(paths == null)
return new HashSet<String>();
//Split the routes
String[] split = paths.split(";");
//Create the set of paths
Set<String> set = new HashSet<String>();
//Add the classes
for(String item : split)
if(!item.trim().equals(""))
set.add(item.trim());
//Return the set
return set;
}
//Failed
catch(Exception ex)
{
throw new Exception("Failed to read web.xml mask-request-data-on-error", ex);
}
}
/*
* Class to hold a route.
*/
private class Route
{
//Fields
public Object instance;
public Method method;
public int parameterType;
//Parameter types
public static final int NO_PARAMETER = 1;
public static final int JSON_ELEMENT = 2;
public static final int JSON_ARRAY = 3;
public static final int JSON_OBJECT = 4;
public static final int PRIMITIVE_BOOLEAN = 5;
public static final int PRIMITIVE_DOUBLE = 6;
public static final int PRIMITIVE_INT = 7;
public static final int PRIMITIVE_LONG = 8;
public static final int PRIMITIVE_STRING = 9;
public static final int REQUEST_RESPONSE = 10;
/**
* Create the object.
* @param instance
* @param method
*/
public Route(Object instance, Method method, int parameterType)
{
this.instance = instance;
this.method = method;
this.parameterType = parameterType;
}
}
}
|
package org.biojava.bio.structure ;
import org.biojava.bio.structure.StructureException ;
import org.biojava.bio.structure.jama.Matrix;
/** utility operations on Atoms, AminoAcids, etc.
* <p>
* Currently the
* coordinates of an Atom are stored as an array of size 3
* (double[3]). It would be more powerful to use Point3D from
* javax.vecmath. but unfortunately this is not a part of standard
* java installations, since it comes with java3d . So to keep things
* simple at the moment biojava does not depend on java3d.
* @author Andreas Prlic
* @since 1.4
* @version %I% %G%
*/
public class Calc {
public Calc(){
}
// 180 / pi
static double RADIAN = 57.29577951 ;
public final static float radiansPerDegree = (float) (2 * Math.PI / 360);
public final static float degreesPerRadian = (float) (360 / (2 * Math.PI));
/**
* calculate distance between two atoms.
*
* @param a an Atom object
* @param b an Atom object
* @return a double
* @throws StructureException ...
*/
public static double getDistance(Atom a, Atom b)
throws StructureException
{
double x = a.getX() - b.getX();
double y = a.getY() - b.getY();
double z = a.getZ() - b.getZ();
double s = x * x + y * y + z * z;
double dist = Math.sqrt(s);
return dist ;
}
private static void nullCheck(Atom a)
throws StructureException
{
if (a == null) {
throw new StructureException("Atom is null!");
}
}
/** add two atoms ( a + b).
*
* @param a an Atom object
* @param b an Atom object
* @return an Atom object
*/
public static Atom add(Atom a, Atom b){
double[] coords = new double[3] ;
coords[0] = a.getX() + b.getX();
coords[1] = a.getY() + b.getY();
coords[2] = a.getZ() + b.getZ();
Atom c = new AtomImpl();
c.setCoords(coords);
return c ;
}
/** substract two atoms ( a - b).
*
* @param a an Atom object
* @param b an Atom object
* @return an Atom object
* @throws StructureException ...
*/
public static Atom substract(Atom a, Atom b)
throws StructureException
{
nullCheck(a) ;
nullCheck(b) ;
double[] coords = new double[3] ;
coords[0] = a.getX() - b.getX();
coords[1] = a.getY() - b.getY();
coords[2] = a.getZ() - b.getZ();
Atom c = new AtomImpl();
c.setCoords(coords);
return c ;
}
/** Vector product .
*
* @param a an Atom object
* @param b an Atom object
* @return an Atom object
*/
public static Atom vectorProduct(Atom a , Atom b){
double[] coords = new double[3];
coords[0] = a.getY() * b.getZ() - a.getZ() * b.getY();
coords[1] = a.getZ() * b.getX() - a.getX() * b.getZ();
coords[2] = a.getX() * b.getY() - a.getY() * b.getX();
Atom c = new AtomImpl();
c.setCoords(coords);
return c ;
}
/** skalar product.
*
* @param a an Atom object
* @param b an Atom object
* @return a double
*/
public static double skalarProduct(Atom a, Atom b){
double skalar ;
skalar = a.getX() * b.getX() + a.getY()* b.getY() + a.getZ() * b.getZ();
return skalar ;
}
/** amount.
*
* @param a an Atom object
* @return a double
*/
public static double amount(Atom a){
return Math.sqrt(skalarProduct(a,a));
}
/** angle.
*
* @param a an Atom object
* @param b an Atom object
* @return a double
*/
public static double angle(Atom a, Atom b){
double skalar;
double angle;
skalar = skalarProduct(a,b);
angle = skalar/( amount(a) * amount (b) );
angle = Math.acos(angle);
angle = angle * RADIAN ;
return angle;
}
/** return the unit vector of vector a .
*
* @param a an Atom object
* @return an Atom object
*/
public static Atom unitVector(Atom a) {
double amount = amount(a) ;
Atom U = a ;
double[] coords = new double[3];
coords[0] = a.getX() / amount ;
coords[1] = a.getY() / amount ;
coords[2] = a.getZ() / amount ;
U.setCoords(coords);
return U ;
}
/** torsion angle
* = angle between the normal vectors of the
* two plains a-b-c and b-c-d.
*
* @param a an Atom object
* @param b an Atom object
* @param c an Atom object
* @param d an Atom object
* @return a double
* @throws StructureException ...
*/
public static double torsionAngle(Atom a, Atom b, Atom c, Atom d)
throws StructureException
{
Atom ab = substract(a,b);
Atom cb = substract(c,b);
Atom bc = substract(b,c);
Atom dc = substract(d,c);
Atom abc = vectorProduct(ab,cb);
Atom bcd = vectorProduct(bc,dc);
double angl = angle(abc,bcd) ;
/* calc the sign: */
Atom vecprod = vectorProduct(abc,bcd);
double val = skalarProduct(cb,vecprod);
if (val<0.0) angl = -angl ;
return angl;
}
/** phi angle.
*
* @param a an AminoAcid object
* @param b an AminoAcid object
* @return a double
* @throws StructureException ...
*/
public static double getPhi(AminoAcid a, AminoAcid b)
throws StructureException
{
if ( ! isConnected(a,b)){
throw new StructureException("can not calc Phi - AminoAcids are not connected!") ;
}
Atom a_C = a.getC();
Atom b_N = b.getN();
Atom b_CA = b.getCA();
Atom b_C = b.getC();
double phi = torsionAngle(a_C,b_N,b_CA,b_C);
return phi ;
}
/** psi angle.
*
* @param a an AminoAcid object
* @param b an AminoAcid object
* @return a double
* @throws StructureException ...
*/
public static double getPsi(AminoAcid a, AminoAcid b)
throws StructureException
{
if ( ! isConnected(a,b)) {
throw new StructureException("can not calc Psi - AminoAcids are not connected!") ;
}
Atom a_N = a.getN();
Atom a_CA = a.getCA();
Atom a_C = a.getC();
Atom b_N = b.getN();
double psi = torsionAngle(a_N,a_CA,a_C,b_N);
return psi ;
}
/** test if two amino acids are connected, i.e.
* if the distance from C to N < 2,5 Angstrom.
*
* @param a an AminoAcid object
* @param b an AminoAcid object
* @return true if ...
* @throws StructureException ...
*/
public static boolean isConnected(AminoAcid a, AminoAcid b)
throws StructureException
{
Atom C = a.getC();
Atom N = b.getN();
// one could also check if the CA atoms are < 4 A...
double distance = getDistance(C,N);
if ( distance < 2.5) {
return true ;
} else {
return false ;
}
}
/** rotate a single atom aroud a rotation matrix.
* matrix must be a 3x3 matrix.
* @param atom
* @param m
*/
public static void rotate(Atom atom, double[][] m){
double x = atom.getX();
double y = atom.getY() ;
double z = atom.getZ();
double nx = m[0][0] * x + m[0][1] * y + m[0][2] * z ;
double ny = m[1][0] * x + m[1][1] * y + m[1][2] * z ;
double nz = m[2][0] * x + m[2][1] * y + m[2][2] * z ;
double[] coords = new double[3] ;
coords[0] = nx ;
coords[1] = ny ;
coords[2] = nz ;
atom.setCoords(coords);
}
/** rotate a structure .
*
* @param structure a Structure object
* @param rotationmatrix an array (3x3) of double representing the rotation matrix.
* @throws StructureException ...
*/
public static void rotate(Structure structure, double[][] rotationmatrix)
throws StructureException
{
double[][]m = rotationmatrix;
if ( m.length != 3 ) {
throw new StructureException ("matrix does not have size 3x3 !");
}
AtomIterator iter = new AtomIterator(structure) ;
while (iter.hasNext()) {
Atom atom = (Atom) iter.next() ;
Calc.rotate(atom,rotationmatrix);
}
}
/** rotate a structure .
*
* @param group a group object
* @param rotationmatrix an array (3x3) of double representing the rotation matrix.
* @throws StructureException ...
*/
public static void rotate(Group group, double[][] rotationmatrix)
throws StructureException
{
double[][]m = rotationmatrix;
if ( m.length != 3 ) {
throw new StructureException ("matrix does not have size 3x3 !");
}
AtomIterator iter = new AtomIterator(group) ;
while (iter.hasNext()) {
Atom atom = null ;
atom = (Atom) iter.next() ;
rotate(atom,rotationmatrix);
}
}
/** rotate an atom around a Matrix object
*
* @param atom
* @param m
*/
public static void rotate(Atom atom, Matrix m){
double x = atom.getX();
double y = atom.getY() ;
double z = atom.getZ();
double[][] ad = new double[][]{{x,y,z}};
Matrix am = new Matrix(ad);
Matrix na = am.times(m);
double[] coords = new double[3] ;
coords[0] = na.get(0,0);
coords[1] = na.get(0,1);
coords[2] = na.get(0,2);
atom.setCoords(coords);
}
/** rotate a group object
*
* @param group a group to be rotated
* @param m a Matrix object representing the translation matrix
*/
public static void rotate(Group group, Matrix m){
AtomIterator iter = new AtomIterator(group) ;
while (iter.hasNext()) {
Atom atom = (Atom) iter.next() ;
rotate(atom,m);
}
}
/** rotate a structure object
*
* @param structure
* @param m
*/
public static void rotate(Structure structure, Matrix m){
AtomIterator iter = new AtomIterator(structure) ;
while (iter.hasNext()) {
Atom atom = (Atom) iter.next() ;
rotate(atom,m);
}
}
/** calculate structure + Matrix coodinates ...
*
* @param s
* @param matrix
*/
public static void plus(Structure s, Matrix matrix){
AtomIterator iter = new AtomIterator(s) ;
Atom oldAtom = null;
Atom rotOldAtom = null;
while (iter.hasNext()) {
Atom atom = null ;
atom = (Atom) iter.next() ;
try {
if ( oldAtom != null){
//System.out.println("before " +getDistance(oldAtom,atom));
}
} catch (Exception e){
e.printStackTrace();
}
oldAtom = (Atom)atom.clone();
double x = atom.getX();
double y = atom.getY() ;
double z = atom.getZ();
double[][] ad = new double[][]{{x,y,z}};
Matrix am = new Matrix(ad);
Matrix na = am.plus(matrix);
double[] coords = new double[3] ;
coords[0] = na.get(0,0);
coords[1] = na.get(0,1);
coords[2] = na.get(0,2);
atom.setCoords(coords);
try {
if ( rotOldAtom != null){
//System.out.println("after " + getDistance(rotOldAtom,atom));
}
} catch (Exception e){
e.printStackTrace();
}
rotOldAtom = (Atom) atom.clone();
}
}
/** shift a structure with a vector.
*
* @param structure a Structure object
* @param a an Atom object representing a shift vector
*/
public static void shift(Structure structure, Atom a ){
AtomIterator iter = new AtomIterator(structure) ;
while (iter.hasNext() ) {
Atom atom = null ;
atom = (Atom) iter.next() ;
Atom natom = add(atom,a);
double x = natom.getX();
double y = natom.getY() ;
double z = natom.getZ();
atom.setX(x);
atom.setY(y);
atom.setZ(z);
}
}
/** shift a vector
*
* @param a vector a
* @param b vector b
*/
public static void shift(Atom a, Atom b){
Atom natom = add(a,b);
double x = natom.getX();
double y = natom.getY() ;
double z = natom.getZ();
a.setX(x);
a.setY(y);
a.setZ(z);
}
/** shift a Group with a vector.
*
* @param group a group object
* @param a an Atom object representing a shift vector
*/
public static void shift(Group group , Atom a ){
AtomIterator iter = new AtomIterator(group) ;
while (iter.hasNext() ) {
Atom atom = null ;
atom = (Atom) iter.next() ;
Atom natom = add(atom,a);
double x = natom.getX();
double y = natom.getY() ;
double z = natom.getZ();
atom.setX(x);
atom.setY(y);
atom.setZ(z);
}
}
/** returns the center of mass of the set of atoms
* @param atomSet a set of Atoms
* @return an Atom representing the Centroid of the set of atoms
*/
public static Atom getCentroid(Atom[] atomSet){
double[] coords = new double[3];
coords[0] = 0;
coords[1] = 0;
coords[2] = 0 ;
for (int i =0 ; i < atomSet.length; i++){
Atom a = atomSet[i];
coords[0] += a.getX();
coords[1] += a.getY();
coords[2] += a.getZ();
}
int n = atomSet.length;
coords[0] = coords[0] / n;
coords[1] = coords[1] / n;
coords[2] = coords[2] / n;
Atom vec = new AtomImpl();
vec.setCoords(coords);
return vec;
}
public static Atom getCenterVector(Atom[] atomSet){
Atom centroid = getCentroid(atomSet);
double[] coords = new double[3];
coords[0] = 0 - centroid.getX();
coords[1] = 0 - centroid.getY();
coords[2] = 0 - centroid.getZ();
Atom shiftVec = new AtomImpl();
shiftVec.setCoords(coords);
return shiftVec;
}
/** center the atoms at the Centroid
* @param atomSet a set of Atoms
* @return an Atom representing the Centroid of the set of atoms
* @throws StructureException
* */
public static Atom[] centerAtoms(Atom[] atomSet) throws StructureException {
Atom shiftVector = getCenterVector(atomSet);
Atom[] newAtoms = new AtomImpl[atomSet.length];
for (int i =0 ; i < atomSet.length; i++){
Atom a = atomSet[i];
Atom n = add(a,shiftVector);
newAtoms[i] = n ;
}
return newAtoms;
}
/** creates a virtual C-beta atom. this might be needed when working with GLY
*
* thanks to Peter Lackner for a python template of this method.
* @param amino
* @return a "virtual" CB atom
* @throws StructureException
*/
public static Atom createVirtualCBAtom(AminoAcid amino)
throws StructureException{
AminoAcid ala = StandardAminoAcid.getAminoAcid("ALA");
Atom aN = ala.getN();
Atom aCA = ala.getCA();
Atom aC = ala.getC();
Atom aCB = ala.getCB();
Atom[] arr1 = new Atom[3];
arr1[0] = aN;
arr1[1] = aCA;
arr1[2] = aC;
Atom[] arr2 = new Atom[3];
arr2[0] = amino.getN();
arr2[1] = amino.getCA();
arr2[2] = amino.getC();
// ok now we got the two arrays, do a SVD:
SVDSuperimposer svd = new SVDSuperimposer(arr2,arr1);
Matrix rotMatrix = svd.getRotation();
Atom tranMatrix = svd.getTranslation();
Calc.rotate(aCB,rotMatrix);
Atom virtualCB = Calc.add(aCB,tranMatrix);
virtualCB.setName("CB");
virtualCB.setFullName(" CB ");
return virtualCB;
}
/** get euler angles for a matrix given in ZYZ convention.
* (as e.g. used by Jmol)
*
* @param m
* @return the euler values for a rotation around Z, Y, Z in degrees...
*/
public static double[] getZYZEuler(Matrix m) {
double m22 = m.get(2,2);
double rY = (float) Math.acos(m22) * degreesPerRadian;
double rZ1, rZ2;
if (m22 > .999d || m22 < -.999d) {
rZ1 = (double) Math.atan2(m.get(1,0), m.get(1,1)) * degreesPerRadian;
rZ2 = 0;
} else {
rZ1 = (double) Math.atan2(m.get(2,1), -m.get(2,0)) * degreesPerRadian;
rZ2 = (double) Math.atan2(m.get(1,2), m.get(0,2)) * degreesPerRadian;
}
return new double[] {rZ1,rY,rZ2};
}
public static double[] getXYZEuler(Matrix m){
double heading, attitude, bank;
// Assuming the angles are in radians.
if (m.get(1,0) > 0.998) { // singularity at north pole
heading = Math.atan2(m.get(0,2),m.get(2,2));
attitude = Math.PI/2;
bank = 0;
} else if (m.get(1,0) < -0.998) { // singularity at south pole
heading = Math.atan2(m.get(0,2),m.get(2,2));
attitude = -Math.PI/2;
bank = 0;
} else {
heading = Math.atan2(-m.get(2,0),m.get(0,0));
bank = Math.atan2(-m.get(1,2),m.get(1,1));
attitude = Math.asin(m.get(1,0));
}
return new double[] { heading, attitude, bank };
}
public static Matrix matrixFromEuler(double heading, double attitude, double bank) {
// Assuming the angles are in radians.
double ch = Math.cos(heading);
double sh = Math.sin(heading);
double ca = Math.cos(attitude);
double sa = Math.sin(attitude);
double cb = Math.cos(bank);
double sb = Math.sin(bank);
Matrix m = new Matrix(3,3);
m.set(0,0, ch * ca);
m.set(0,1, sh*sb - ch*sa*cb);
m.set(0,2, ch*sa*sb + sh*cb);
m.set(1,0, sa);
m.set(1,1, ca*cb);
m.set(1,2, -ca*sb);
m.set(2,0, -sh*ca);
m.set(2,1, sh*sa*cb + ch*sb);
m.set(2,2, -sh*sa*sb + ch*cb);
return m;
}
}
|
package org.biojava.bio.structure ;
import org.biojava.bio.structure.StructureException ;
import org.biojava.bio.structure.jama.Matrix;
/** utility operations on Atoms, AminoAcids, etc.
* <p>
* Currently the
* coordinates of an Atom are stored as an array of size 3
* (double[3]). It would be more powerful to use Point3D from
* javax.vecmath. but unfortunately this is not a part of standard
* java installations, since it comes with java3d . So to keep things
* simple at the moment biojava does not depend on java3d.
* @author Andreas Prlic
* @since 1.4
* @version %I% %G%
*/
public class Calc {
public Calc(){
}
// 180 / pi
static double RADIAN = 57.29577951 ;
/**
* calculate distance between two atoms.
*
* @param a an Atom object
* @param b an Atom object
* @return a double
* @throws StructureException ...
*/
public static double getDistance(Atom a, Atom b)
throws StructureException
{
Atom c = substract(b,a);
double dist = amount(c) ;
return dist ;
}
private static void nullCheck(Atom a)
throws StructureException
{
if (a == null) {
throw new StructureException("Atom is null!");
}
}
/** add two atoms ( a + b).
*
* @param a an Atom object
* @param b an Atom object
* @return an Atom object
*/
public static Atom add(Atom a, Atom b){
double[] coords = new double[3] ;
coords[0] = a.getX() + b.getX();
coords[1] = a.getY() + b.getY();
coords[2] = a.getZ() + b.getZ();
Atom c = new AtomImpl();
c.setCoords(coords);
return c ;
}
/** substract two atoms ( a - b).
*
* @param a an Atom object
* @param b an Atom object
* @return an Atom object
* @throws StructureException ...
*/
public static Atom substract(Atom a, Atom b)
throws StructureException
{
nullCheck(a) ;
nullCheck(b) ;
double[] coords = new double[3] ;
coords[0] = a.getX() - b.getX();
coords[1] = a.getY() - b.getY();
coords[2] = a.getZ() - b.getZ();
Atom c = new AtomImpl();
c.setCoords(coords);
return c ;
}
/** Vector product .
*
* @param a an Atom object
* @param b an Atom object
* @return an Atom object
*/
public static Atom vectorProduct(Atom a , Atom b){
double[] coords = new double[3];
coords[0] = a.getY() * b.getZ() - a.getZ() * b.getY();
coords[1] = a.getZ() * b.getX() - a.getX() * b.getZ();
coords[2] = a.getX() * b.getY() - a.getY() * b.getX();
Atom c = new AtomImpl();
c.setCoords(coords);
return c ;
}
/** skalar product.
*
* @param a an Atom object
* @param b an Atom object
* @return a double
*/
public static double skalarProduct(Atom a, Atom b){
double skalar ;
skalar = a.getX() * b.getX() + a.getY()* b.getY() + a.getZ() * b.getZ();
return skalar ;
}
/** amount.
*
* @param a an Atom object
* @return a double
*/
public static double amount(Atom a){
return Math.sqrt(skalarProduct(a,a));
}
/** angle.
*
* @param a an Atom object
* @param b an Atom object
* @return a double
*/
public static double angle(Atom a, Atom b){
double skalar;
double angle;
skalar = skalarProduct(a,b);
angle = skalar/( amount(a) * amount (b) );
angle = Math.acos(angle);
angle = angle * RADIAN ;
return angle;
}
/** return the unit vector of vector a .
*
* @param a an Atom object
* @return an Atom object
*/
public static Atom unitVector(Atom a) {
double amount = amount(a) ;
Atom U = a ;
double[] coords = new double[3];
coords[0] = a.getX() / amount ;
coords[1] = a.getY() / amount ;
coords[2] = a.getZ() / amount ;
U.setCoords(coords);
return U ;
}
/** torsion angle
* = angle between the normal vectors of the
* two plains a-b-c and b-c-d.
*
* @param a an Atom object
* @param b an Atom object
* @param c an Atom object
* @param d an Atom object
* @return a double
* @throws StructureException ...
*/
public static double torsionAngle(Atom a, Atom b, Atom c, Atom d)
throws StructureException
{
Atom ab = substract(a,b);
Atom cb = substract(c,b);
Atom bc = substract(b,c);
Atom dc = substract(d,c);
Atom abc = vectorProduct(ab,cb);
Atom bcd = vectorProduct(bc,dc);
double angl = angle(abc,bcd) ;
/* calc the sign: */
Atom vecprod = vectorProduct(abc,bcd);
double val = skalarProduct(cb,vecprod);
if (val<0.0) angl = -angl ;
return angl;
}
/** phi angle.
*
* @param a an AminoAcid object
* @param b an AminoAcid object
* @return a double
* @throws StructureException ...
*/
public static double getPhi(AminoAcid a, AminoAcid b)
throws StructureException
{
if ( ! isConnected(a,b)){
throw new StructureException("can not calc Phi - AminoAcids are not connected!") ;
}
Atom a_C = a.getC();
Atom b_N = b.getN();
Atom b_CA = b.getCA();
Atom b_C = b.getC();
double phi = torsionAngle(a_C,b_N,b_CA,b_C);
return phi ;
}
/** psi angle.
*
* @param a an AminoAcid object
* @param b an AminoAcid object
* @return a double
* @throws StructureException ...
*/
public static double getPsi(AminoAcid a, AminoAcid b)
throws StructureException
{
if ( ! isConnected(a,b)) {
throw new StructureException("can not calc Psi - AminoAcids are not connected!") ;
}
Atom a_N = a.getN();
Atom a_CA = a.getCA();
Atom a_C = a.getC();
Atom b_N = b.getN();
double psi = torsionAngle(a_N,a_CA,a_C,b_N);
return psi ;
}
/** test if two amino acids are connected, i.e.
* if the distance from C to N < 2,5 Angstrom.
*
* @param a an AminoAcid object
* @param b an AminoAcid object
* @return true if ...
* @throws StructureException ...
*/
public static boolean isConnected(AminoAcid a, AminoAcid b)
throws StructureException
{
Atom C = a.getC();
Atom N = b.getN();
// one could also check if the CA atoms are < 4 A...
double distance = getDistance(C,N);
if ( distance < 2.5) {
return true ;
} else {
return false ;
}
}
/** rotate a single atom aroud a rotation matrix.
* matrix must be a 3x3 matrix.
* @param atom
* @param m
*/
public static void rotate(Atom atom, double[][] m){
double x = atom.getX();
double y = atom.getY() ;
double z = atom.getZ();
double nx = m[0][0] * x + m[0][1] * y + m[0][2] * z ;
double ny = m[1][0] * x + m[1][1] * y + m[1][2] * z ;
double nz = m[2][0] * x + m[2][1] * y + m[2][2] * z ;
double[] coords = new double[3] ;
coords[0] = nx ;
coords[1] = ny ;
coords[2] = nz ;
atom.setCoords(coords);
}
/** rotate a structure .
*
* @param structure a Structure object
* @param rotationmatrix an array (3x3) of double representing the rotation matrix.
* @throws StructureException ...
*/
public static void rotate(Structure structure, double[][] rotationmatrix)
throws StructureException
{
double[][]m = rotationmatrix;
if ( m.length != 3 ) {
throw new StructureException ("matrix does not have size 3x3 !");
}
AtomIterator iter = new AtomIterator(structure) ;
while (iter.hasNext()) {
Atom atom = (Atom) iter.next() ;
Calc.rotate(atom,rotationmatrix);
}
}
/** rotate a structure .
*
* @param group a group object
* @param rotationmatrix an array (3x3) of double representing the rotation matrix.
* @throws StructureException ...
*/
public static void rotate(Group group, double[][] rotationmatrix)
throws StructureException
{
double[][]m = rotationmatrix;
if ( m.length != 3 ) {
throw new StructureException ("matrix does not have size 3x3 !");
}
AtomIterator iter = new AtomIterator(group) ;
while (iter.hasNext()) {
Atom atom = null ;
atom = (Atom) iter.next() ;
rotate(atom,rotationmatrix);
}
}
/** rotate an atom around a Matrix object
*
* @param atom
* @param m
*/
public static void rotate(Atom atom, Matrix m){
double x = atom.getX();
double y = atom.getY() ;
double z = atom.getZ();
double[][] ad = new double[][]{{x,y,z}};
Matrix am = new Matrix(ad);
Matrix na = am.times(m);
double[] coords = new double[3] ;
coords[0] = na.get(0,0);
coords[1] = na.get(0,1);
coords[2] = na.get(0,2);
atom.setCoords(coords);
}
/** rotate a group object
*
* @param group a group to be rotated
* @param m a Matrix object representing the translation matrix
*/
public static void rotate(Group group, Matrix m){
AtomIterator iter = new AtomIterator(group) ;
while (iter.hasNext()) {
Atom atom = (Atom) iter.next() ;
rotate(atom,m);
}
}
/** rotate a structure object
*
* @param structure
* @param m
*/
public static void rotate(Structure structure, Matrix m){
AtomIterator iter = new AtomIterator(structure) ;
while (iter.hasNext()) {
Atom atom = (Atom) iter.next() ;
rotate(atom,m);
}
}
/** calculate structure + Matrix coodinates ...
*
* @param s
* @param matrix
*/
public static void plus(Structure s, Matrix matrix){
AtomIterator iter = new AtomIterator(s) ;
Atom oldAtom = null;
Atom rotOldAtom = null;
while (iter.hasNext()) {
Atom atom = null ;
atom = (Atom) iter.next() ;
try {
if ( oldAtom != null){
//System.out.println("before " +getDistance(oldAtom,atom));
}
} catch (Exception e){
e.printStackTrace();
}
oldAtom = (Atom)atom.clone();
double x = atom.getX();
double y = atom.getY() ;
double z = atom.getZ();
double[][] ad = new double[][]{{x,y,z}};
Matrix am = new Matrix(ad);
Matrix na = am.plus(matrix);
double[] coords = new double[3] ;
coords[0] = na.get(0,0);
coords[1] = na.get(0,1);
coords[2] = na.get(0,2);
atom.setCoords(coords);
try {
if ( rotOldAtom != null){
//System.out.println("after " + getDistance(rotOldAtom,atom));
}
} catch (Exception e){
e.printStackTrace();
}
rotOldAtom = (Atom) atom.clone();
}
}
/** shift a structure with a vector.
*
* @param structure a Structure object
* @param a an Atom object representing a shift vector
*/
public static void shift(Structure structure, Atom a ){
AtomIterator iter = new AtomIterator(structure) ;
while (iter.hasNext() ) {
Atom atom = null ;
atom = (Atom) iter.next() ;
Atom natom = add(atom,a);
double x = natom.getX();
double y = natom.getY() ;
double z = natom.getZ();
atom.setX(x);
atom.setY(y);
atom.setZ(z);
}
}
/** shift a vector
*
* @param a vector a
* @param b vector b
*/
public static void shift(Atom a, Atom b){
Atom natom = add(a,b);
double x = natom.getX();
double y = natom.getY() ;
double z = natom.getZ();
a.setX(x);
a.setY(y);
a.setZ(z);
}
/** shift a Group with a vector.
*
* @param group a group object
* @param a an Atom object representing a shift vector
*/
public static void shift(Group group , Atom a ){
AtomIterator iter = new AtomIterator(group) ;
while (iter.hasNext() ) {
Atom atom = null ;
atom = (Atom) iter.next() ;
Atom natom = add(atom,a);
double x = natom.getX();
double y = natom.getY() ;
double z = natom.getZ();
atom.setX(x);
atom.setY(y);
atom.setZ(z);
}
}
/** returns the center of mass of the set of atoms
*
*/
public static Atom getCentroid(Atom[] atomSet){
double[] coords = new double[3];
coords[0] = 0;
coords[1] = 0;
coords[2] = 0 ;
for (int i =0 ; i < atomSet.length; i++){
Atom a = atomSet[i];
coords[0] += a.getX();
coords[1] += a.getY();
coords[2] += a.getZ();
}
int n = atomSet.length;
coords[0] = coords[0] / n;
coords[1] = coords[1] / n;
coords[2] = coords[2] / n;
Atom vec = new AtomImpl();
vec.setCoords(coords);
return vec;
}
public static Atom getCenterVector(Atom[] atomSet){
Atom centroid = getCentroid(atomSet);
double[] coords = new double[3];
coords[0] = 0 - centroid.getX();
coords[1] = 0 - centroid.getY();
coords[2] = 0 - centroid.getZ();
Atom shiftVec = new AtomImpl();
shiftVec.setCoords(coords);
return shiftVec;
}
/** center the atoms at the Centroid
* */
public static Atom[] centerAtoms(Atom[] atomSet) throws StructureException {
Atom shiftVector = getCenterVector(atomSet);
Atom[] newAtoms = new AtomImpl[atomSet.length];
for (int i =0 ; i < atomSet.length; i++){
Atom a = atomSet[i];
Atom n = add(a,shiftVector);
newAtoms[i] = n ;
}
return newAtoms;
}
/** creates a virtual C-beta atom. this might be needed when working with GLY
*
* thanks to Peter Lackner for a python template of this method.
* @param amino
* @return a "virtual" CB atom
*/
public static Atom createVirtualCBAtom(AminoAcid amino)
throws StructureException{
AminoAcid ala = StandardAminoAcid.getAminoAcid("ALA");
Atom aN = ala.getN();
Atom aCA = ala.getCA();
Atom aC = ala.getC();
Atom aCB = ala.getCB();
Atom[] arr1 = new Atom[3];
arr1[0] = aN;
arr1[1] = aCA;
arr1[2] = aC;
Atom[] arr2 = new Atom[3];
arr2[0] = amino.getN();
arr2[1] = amino.getCA();
arr2[2] = amino.getC();
// ok now we got the two arrays, do a SVD:
SVDSuperimposer svd = new SVDSuperimposer(arr2,arr1);
Matrix rotMatrix = svd.getRotation();
Atom tranMatrix = svd.getTranslation();
Calc.rotate(aCB,rotMatrix);
Atom virtualCB = Calc.add(aCB,tranMatrix);
virtualCB.setName("CB");
virtualCB.setFullName(" CB ");
return virtualCB;
}
}
|
package org.biojava.bio.symbol;
import java.util.List;
import java.util.ArrayList;
import org.biojava.bio.seq.io.SymbolTokenization;
//import org.biojava.bio.seq.Sequence;
//import org.biojava.bio.seq.Feature;
import org.biojava.bio.BioException;
//import org.biojava.utils.ChangeVetoException;
/**
* Class to describe a regex-like pattern. The pattern
* is a list of other patterns or Symbols in the target
* FiniteAlphabet. These are added to the list with
* addSymbol and addPattern calls. The pattern can be
* reiterated a number of times (deafult is once).
* <p>
* It is also possible for the Pattern to contain variant
* Patterns. These variants are started with beginNextVariant().
*
* @author David Huen
* @since 1.4
*/
public class Pattern
{
private List patternList;
private FiniteAlphabet alfa;
private int min = 1;
private int max = 1;
private String label;
private SymbolTokenization symToke = null;
/**
* @param label A String describing the Pattern.
* @param alfa The FiniteAlphabet the Pattern is defined over.
*/
public Pattern(String label, FiniteAlphabet alfa)
{
this.alfa = alfa;
this.label = label;
patternList = new ArrayList();
}
/**
* Add a Symbol to the end of the Pattern.
*/
public void addSymbol(Symbol sym)
throws IllegalAlphabetException
{
if (!alfa.contains(sym))
throw new IllegalAlphabetException(sym.getName() + " is not in Alphabet " + alfa.getName());
patternList.add(sym);
}
/**
* Add a Pattern to the end of the current Pattern.
*/
public void addPattern(Pattern pattern)
throws IllegalAlphabetException
{
if (alfa != pattern.getAlphabet())
throw new IllegalAlphabetException(pattern.getAlphabet().getName() + " is not compatible with Alphabet " + alfa.getName());
patternList.add(pattern);
}
/**
* Start a variant Pattern within this Pattern.
*/
public void beginNextVariant()
{
}
public Alphabet getAlphabet() { return alfa; }
public int getMin() { return min; }
public int getMax() { return max; }
public String getLabel() { return label; }
/**
* Minimum number of times the Pattern is to be matched.
*/
public void setMin(int min)
throws IllegalArgumentException
{
if (min < 0)
throw new IllegalArgumentException("number of repeats must be non-negative.");
else
this.min = min;
}
/**
* Maximum number of times the Pattern is to be matched.
*/
public void setMax(int max)
{
if (max < 0)
throw new IllegalArgumentException("number of repeats must be non-negative.");
else
this.max = max;
}
/**
* Set the label for this pattern.
*/
public void setLabel(String label)
{
this.label = label;
}
List getPatternList()
{
return patternList;
}
public String toString()
{
try {
return toString(Pattern.this);
}
catch (Exception e) {
e.printStackTrace();
return "";
}
}
private String stringify()
throws BioException, IllegalSymbolException
{
if (symToke == null) symToke = alfa.getTokenization("token");
StringBuffer s = new StringBuffer();
for (int i=0; i < patternList.size(); i++) {
Object currElem = patternList.get(i);
if (currElem instanceof Symbol) {
//System.out.println("symbol is " + ((Symbol) currElem).getName());
s.append(symToke.tokenizeSymbol((Symbol) currElem));
}
else if (currElem instanceof Pattern) {
s.append(toString((Pattern) currElem));
}
}
return s.toString();
}
private String toString(Pattern p)
throws BioException, IllegalSymbolException
{
StringBuffer s = new StringBuffer();
boolean hasCount = (p.getMin() != 1) || (p.getMax() != 1);
boolean needParen = hasCount || (p.getPatternList().size() > 1);
if (needParen) s.append('(');
s.append(p.stringify());
if (needParen) s.append(')');
if (hasCount) {
s.append('{');
s.append(Integer.toString(p.getMin()));
s.append(',');
s.append(Integer.toString(p.getMax()));
s.append('}');
}
return s.toString();
}
}
|
package com.shc.silenceengine.io;
import com.shc.silenceengine.core.SilenceException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
/**
* <p> A FilePath is handle to a file that can be both an external file besides the JAR, or has an absolute path from
* the root of the filesystem or is a resource packed in some JAR in the classpath. This class uses some tricks to find
* the other properties of the resources like is that a directory or a file, it's size and also whether it exists. To
* construct a FilePath, use either {@link #getExternalFile(String)} or {@link #getResourceFile(String)} methods.</p>
*
* <pre>
* FilePath resource = FilePath.getResourceFile("resources/test.png");
* FilePath external = FilePath.getExternalFile("C:/Windows/explorer.exe");
* </pre>
*
* <p> Once you create a FilePath, you can derive new files if that is a directory, or you can get the parent path of a
* path. You can also get a list of files in a directory denoted by a FilePath instance. To read from a file, or to
* write to a file, you can get an {@link InputStream} or an {@link OutputStream} by using {@link #getInputStream()} and
* {@link #getOutputStream()} methods.</p>
*
* <p> For external files, this class uses the {@link Files} class of Java NIO package. For resources, there are two
* ways. If the resource is accessed from an IDE, it uses a {@link File} instance with the URI returned by the class
* loader's {@link ClassLoader#getResource(String)} method. If the resource is accessed from a running JAR, then an
* instance of {@link JarFile} is created using reflection, and it's entries are used to access the attributes.</p>
*
* @author Sri Harsha Chilakapati
*/
public class FilePath
{
/**
* The UNIX style path separator ({@code /}) character. All the path strings are converted to this character when
* creating an instance with the constructor.
*/
public static final char SEPARATOR = '/';
// The path of the resource, and the type
private String path;
private Type type;
/**
* Constructs an instance of FilePath by taking a path string, and a type.
*
* @param path The path string of the path
* @param type The type of the file, one of {@link Type#EXTERNAL} or {@link Type#RESOURCE}.
*
* @throws IOException When an error occurred reading the attributes of the file path.
*/
private FilePath(String path, Type type) throws IOException
{
this.path = path.replaceAll("\\\\", "/").replaceAll("/+", "/").trim();
this.type = type;
//// switch (type)
//// case EXTERNAL:
//// directory = Files.isDirectory(Paths.get(path));
////// exists = Files.exists(Paths.get(path));
////// size = exists() ? Files.size(Paths.get(path)) : -1;
//// break;
//// case RESOURCE:
//// directory = this.path.endsWith("/");
////// exists = existsInJar() || FilePath.class.getClassLoader().getResource(path) != null;
////// size = exists ? calculateResourceSize() : -1;
//// break;
}
/**
* This method calculates the size of the resource file or the directory. If this path is a directory, then the size
* is the sum of all the files in this directory. Otherwise the size is calculated either by retrieving the JarEntry
* of the resource, or by delegating it to the Files class with a path, in case of running from the IDE.
*
* @return The size of the FilePath, in bytes.
*
* @throws IOException If an error occurred while accessing the file path.
*/
private long calculateResourceSize() throws IOException
{
long size = 0;
if (isDirectory())
{
// If this path is a directory, then the size is the sum of all the files in it.
List<FilePath> files = listFiles();
for (FilePath path : files)
size += path.sizeInBytes();
}
else
{
// Otherwise, try to find the location of the executable JAR
File jarFile = new File(FilePath.class.getProtectionDomain().getCodeSource().getLocation().getPath().replaceAll("%20", " "));
// If this is a JAR file, we are running through an executable JAR. Construct a JarFile instance
// and use that instance to read the entries from the JAR.
if (jarFile.isFile())
{
JarFile jar = new JarFile(jarFile);
// Collect all the entries whose name equals with the path
List<JarEntry> entries = jar.stream().filter(e -> e.getName().equals(path))
.collect(Collectors.toList());
size = entries.get(0).getSize();
jar.close();
}
else
{
try
{
// This is a resource, but the file is requested when running from an IDE. We can safely delegate
// the work to the Files class now.
size = Files.size(Paths.get(FilePath.class.getClassLoader().getResource(path).toURI()));
}
catch (URISyntaxException e)
{
SilenceException.reThrow(e);
}
}
}
return size;
}
/**
* This method finds whether this path exists in the executable JAR file.
*
* @return True if the file exists, else false.
*
* @throws IOException If an error occurs when accessing the JAR file.
*/
private boolean existsInJar() throws IOException
{
boolean exists = false;
File jarFile = new File(FilePath.class.getProtectionDomain().getCodeSource().getLocation().getPath().replaceAll("%20", " "));
if (jarFile.isFile())
{
JarFile jar = new JarFile(jarFile);
exists = jar.stream().filter(e -> e.getName().startsWith(path)).count() > 0;
jar.close();
}
return exists;
}
public String getPath()
{
return path;
}
public Type getType()
{
return type;
}
public boolean exists()
{
if (getType() == Type.EXTERNAL)
return Files.exists(Paths.get(path));
else
try
{
return existsInJar() || FilePath.class.getClassLoader().getResource(path) != null;
}
catch (IOException e)
{
SilenceException.reThrow(e);
}
return false;
}
public boolean isDirectory()
{
if (!exists())
return false;
if (getType() == Type.EXTERNAL)
return Files.isDirectory(Paths.get(path));
else
{
boolean isDirectory = false;
try
{
File file = new File(FilePath.class.getProtectionDomain().getCodeSource().getLocation().getPath().replaceAll("%20", " "));
if (file.isFile())
{
JarFile jarFile = new JarFile(file);
isDirectory = jarFile.stream().filter(e -> e.getName().startsWith(path)).count() > 1;
jarFile.close();
}
else
{
isDirectory = Files.isDirectory(Paths.get(FilePath.class.getClassLoader().getResource(path).toURI()));
}
}
catch (Exception e)
{
SilenceException.reThrow(e);
}
return isDirectory;
}
}
public InputStream getInputStream() throws IOException
{
if (isDirectory())
throw new SilenceException("Cannot read from a directory.");
if (!exists())
throw new SilenceException("Cannot read from a non existing file.");
InputStream inputStream = null;
switch (type)
{
case EXTERNAL:
inputStream = Files.newInputStream(Paths.get(path));
break;
case RESOURCE:
inputStream = FilePath.class.getClassLoader().getResourceAsStream(path);
}
return inputStream;
}
public OutputStream getOutputStream() throws IOException
{
if (type == Type.RESOURCE)
throw new SilenceException("Cannot write to a resource file.");
if (isDirectory())
throw new SilenceException("Cannot write to a directory.");
return Files.newOutputStream(Paths.get(path));
}
public Reader getReader() throws IOException
{
return new InputStreamReader(getInputStream());
}
public Writer getWriter() throws IOException
{
return new OutputStreamWriter(getOutputStream());
}
public void copyTo(FilePath path) throws IOException
{
byte[] buffer = new byte[1024];
int length;
try (InputStream inputStream = getInputStream(); OutputStream outputStream = path.getOutputStream())
{
while ((length = inputStream.read(buffer)) > 0)
{
outputStream.write(buffer, 0, length);
}
}
// path.size = Files.size(Paths.get(path.getPath()));
// path.exists = true;
}
public void moveTo(FilePath path) throws IOException
{
if (getType() == Type.RESOURCE || path.getType() == Type.EXTERNAL)
throw new SilenceException("Cannot move resource files!");
Files.move(Paths.get(this.path), Paths.get(path.getPath()));
}
public void mkdirs() throws IOException
{
if (getType() == Type.RESOURCE)
throw new SilenceException("Cannot create resource directories!");
if (!isDirectory())
throw new SilenceException("Cannot create directories for a path that denotes a file!");
Files.createDirectories(Paths.get(path));
}
public void createFile() throws IOException
{
if (getType() == Type.RESOURCE)
throw new SilenceException("Cannot create resource files!");
if (isDirectory())
throw new SilenceException("Cannot convert a directory to a file");
Files.createFile(Paths.get(path));
}
public FilePath getParent() throws IOException
{
String[] parts = path.split("/");
String path = parts[0];
for (int i = 1; i < parts.length - 1; i++)
path += "/" + parts[i] + "/";
return new FilePath(path + "/", type);
}
public FilePath getChild(String path) throws IOException
{
if (!isDirectory())
throw new SilenceException("Cannot get a child for a file.");
if (!exists())
throw new SilenceException("Cannot get a child for a non existing directory.");
return new FilePath(this.path + SEPARATOR + path, type);
}
public boolean delete() throws IOException
{
if (getType() == Type.RESOURCE)
throw new SilenceException("Cannot delete resource files.");
return Files.deleteIfExists(Paths.get(path));
}
public String getExtension()
{
String[] parts = getPath().split("\\.(?=[^\\.]+$)");
return parts.length > 1 ? parts[1] : "";
}
public long sizeInBytes()
{
if (!exists())
return -1;
try
{
if (getType() == Type.EXTERNAL)
return Files.size(Paths.get(path));
else
return calculateResourceSize();
}
catch (IOException e)
{
SilenceException.reThrow(e);
}
return -1;
}
public List<FilePath> listFiles() throws IOException
{
if (!isDirectory())
throw new SilenceException("Cannot list files in a path which is not a directory.");
if (!exists())
throw new SilenceException("Cannot list files in a non existing directory.");
List<FilePath> list = new ArrayList<>();
if (getType() == Type.EXTERNAL)
{
File file = new File(path);
for (File child : file.listFiles())
list.add(new FilePath(path + SEPARATOR + child.getPath().replace(file.getPath(), ""), getType()));
}
else
{
File file = new File(FilePath.class.getProtectionDomain().getCodeSource().getLocation().getPath().replaceAll("%20", " "));
if (file.isFile())
{
JarFile jarFile = new JarFile(file);
List<JarEntry> entries = jarFile.stream().filter(e -> e.getName().startsWith(path))
.collect(Collectors.toList());
for (JarEntry entry : entries)
{
list.add(new FilePath(entry.getName(), getType()));
}
jarFile.close();
}
else
{
try
{
List<Path> paths = Files.list(Paths.get(FilePath.class.getClassLoader().getResource(path).toURI()))
.collect(Collectors.toList());
for (Path path : paths)
{
list.add(new FilePath(this.path + SEPARATOR + path.toFile().getName(), getType()));
}
}
catch (URISyntaxException e)
{
SilenceException.reThrow(e);
}
}
}
return Collections.unmodifiableList(list);
}
public static FilePath getExternalFile(String path) throws IOException
{
return new FilePath(path, Type.EXTERNAL);
}
public static FilePath getResourceFile(String path) throws IOException
{
return new FilePath(path, Type.RESOURCE);
}
public enum Type
{
EXTERNAL, RESOURCE
}
@Override
public String toString()
{
return "FilePath{" +
"path='" + path + '\'' +
", extension='" + getExtension() + "'" +
", type=" + type +
", isDirectory=" + isDirectory() +
", exists=" + exists() +
", size=" + sizeInBytes() +
'}';
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FilePath filePath = (FilePath) o;
return isDirectory() == filePath.isDirectory() &&
exists() == filePath.exists() &&
sizeInBytes() == filePath.sizeInBytes() &&
getPath().equals(filePath.getPath()) &&
getType() == filePath.getType();
}
@Override
public int hashCode()
{
int result = getPath().hashCode();
result = 31 * result + getType().hashCode();
result = 31 * result + (isDirectory() ? 1 : 0);
result = 31 * result + (exists() ? 1 : 0);
result = 31 * result + (int) (sizeInBytes() ^ (sizeInBytes() >>> 32));
return result;
}
}
|
package org.coinjoin.rsa;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
public class BlindSignUtil {
private static SecureRandom random;
static {
// Initialize RSA KeyPair Generator and RNG
random = new SecureRandom();
}
public static KeyPair freshRSAKeyPair() {
// TODO: Complete
return null;
}
/**
* Given m, calculates (m^d)modN
* @param p: RSA Private Key
* @param blinded: Raw Byte Array representing "m"
* @return
*/
public static byte[] signData(PrivateKey p, byte[] blinded) {
BigInteger sig = new BigInteger(blinded);
RSAPrivateKey privKey = (RSAPrivateKey)p;
sig = sig.modPow(privKey.getPrivateExponent(), privKey.getModulus());
return sig.toByteArray();
}
public static boolean verifyData(PublicKey p, byte[] data, byte[] signature) {
RSAPublicKey pub = (RSAPublicKey)p;
return (new BigInteger(signature).modPow(pub.getPublicExponent(), pub.getModulus()))
.equals(new BigInteger(data));
}
public static BlindedData blindData(PublicKey p, byte[] data) {
RSAPublicKey pub = (RSAPublicKey)p;
byte[] rand = new byte[pub.getModulus().bitLength() / 8];
BigInteger r = BigInteger.ONE;
while(!r.gcd(pub.getModulus()).equals(BigInteger.ONE) || r.equals(BigInteger.ONE) || r.equals(pub.getModulus())) {
random.nextBytes(rand);
r = new BigInteger(1, rand);
}
BigInteger bData = ((r.modPow(pub.getPublicExponent(),pub.getModulus()))
.multiply(new BigInteger(data))).mod(pub.getModulus());
return new BlindedData(r, bData.toByteArray());
}
public static byte[] unblindSignature(PublicKey p, BlindedData bData, byte[] bSig) {
RSAPublicKey pub = (RSAPublicKey)p;
BigInteger sig = bData.GetMultiplier().modInverse(pub.getModulus())
.multiply(new BigInteger(bSig)).mod(pub.getModulus());
return sig.toByteArray();
}
}
|
package com.skelril.aurora;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.util.entity.player.PlayerUtil;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.Polygonal2DSelection;
import com.sk89q.worldedit.bukkit.selections.Selection;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.skelril.aurora.util.ChatUtil;
import com.skelril.aurora.util.item.ItemUtil;
import com.skelril.hackbook.ChunkBook;
import com.skelril.hackbook.exceptions.UnsupportedFeatureException;
import com.zachsthings.libcomponents.ComponentInformation;
import com.zachsthings.libcomponents.bukkit.BukkitComponent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
@ComponentInformation(friendlyName = "ADebug", desc = "Debug tools")
public class DebugComponent extends BukkitComponent {
private final CommandBook inst = CommandBook.inst();
private final Server server = CommandBook.server();
@Override
public void enable() {
//noinspection AccessStaticViaInstance
//inst.registerEvents(new InventoryCorruptionFixer());
//noinspection AccessStaticViaInstance
//inst.registerEvents(new BlockDebug());
//registerCommands(FoodInfo.class);
//registerCommands(ChunkLighter.class);
//registerCommands(LocationDebug.class);
//registerCommands(RegionVolumeTest.class);
// Bug fixes
// Fixes an issue where potion effects are not removed from players on death
//noinspection AccessStaticViaInstance
//inst.registerEvents(new PotionDeathFix());
//noinspection AccessStaticViaInstance
//inst.registerEvents(new ItemSpawnPrinter());
//noinspection AccessStaticViaInstance
//inst.registerEvents(new DamageSys());
}
private class InventoryCorruptionFixer implements Listener {
@EventHandler
public void onLogin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (!player.getName().equals("Dark_Arc")) return;
ItemStack[] inventory = player.getInventory().getContents();
inventory = ItemUtil.removeItemOfType(inventory, Material.DOUBLE_PLANT.getId());
player.getInventory().setContents(inventory);
}
}
public class FoodInfo {
@Command(aliases = {"foodstats"}, desc = "Report hunger info",
flags = "", min = 0, max = 0)
@CommandPermissions("aurora.debug.foodstats")
public void myLocCmd(CommandContext args, CommandSender sender) throws CommandException {
Player player = PlayerUtil.checkPlayer(sender);
ChatUtil.sendNotice(player, "Food level: " + player.getFoodLevel());
ChatUtil.sendNotice(player, "Sat. level: " + player.getSaturation());
ChatUtil.sendNotice(player, "Exh. level: " + player.getExhaustion());
}
}
public class ChunkLighter {
@Command(aliases = {"relight"}, desc = "Get your location",
flags = "", min = 0, max = 0)
@CommandPermissions("aurora.debug.relight")
public void myLocCmd(CommandContext args, CommandSender sender) throws CommandException {
Player player = PlayerUtil.checkPlayer(sender);
try {
ChunkBook.relight(player.getLocation().getChunk());
} catch (UnsupportedFeatureException e) {
throw new CommandException("This feature is not currently supported.");
}
ChatUtil.sendNotice(player, "The chunk lighting has successfully been recalculated.");
}
}
public class LocationDebug {
@Command(aliases = {"myloc"}, desc = "Get your location",
flags = "", min = 0, max = 0)
public void myLocCmd(CommandContext args, CommandSender sender) throws CommandException {
Location l = PlayerUtil.checkPlayer(sender).getLocation();
ChatUtil.sendNotice(sender, "X: " + l.getX() + ", Y:" + l.getY() + ", Z: " + l.getZ());
ChatUtil.sendNotice(sender, "Pitch: " + l.getPitch() + ", Yaw: " + l.getYaw());
}
}
public class RegionVolumeTest {
@Command(aliases = {"rgvol"}, desc = "Calculate the volume of the currently selected region",
flags = "", min = 0, max = 0)
public void myLocCmd(CommandContext args, CommandSender sender) throws CommandException {
WorldEditPlugin worldEdit = (WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit");
Selection selection = worldEdit.getSelection(PlayerUtil.checkPlayer(sender));
if (selection != null) {
if (selection instanceof Polygonal2DSelection) {
ProtectedPolygonalRegion region = new ProtectedPolygonalRegion(
"test",
((Polygonal2DSelection) selection).getNativePoints(),
selection.getMinimumPoint().getBlockY(),
selection.getMaximumPoint().getBlockY()
);
ChatUtil.sendNotice(sender, "Region Volume: " + region.volume());
}
// Do something with min/max
} else {
throw new CommandException("No selection found!");
}
}
}
private class BlockDebug implements Listener {
@EventHandler
public void onRightClick(PlayerInteractEvent event) {
ItemStack held = event.getItem();
if (held != null && held.getType() == Material.COAL && event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Block block = event.getClickedBlock();
ChatUtil.sendNotice(event.getPlayer(),
"Block name: " + block.getType()
+ ", Type ID: " + block.getTypeId()
+ ", Block data: " + block.getData()
);
event.setUseInteractedBlock(Event.Result.DENY);
}
}
}
private class PotionDeathFix implements Listener {
@EventHandler
public void onRespawn(final PlayerRespawnEvent event) {
server.getScheduler().runTaskLater(inst, () -> {
Player player = event.getPlayer();
for (PotionEffect next : player.getActivePotionEffects()) {
player.addPotionEffect(new PotionEffect(next.getType(), 0, 0), true);
}
}, 1);
}
}
private class ItemSpawnPrinter implements Listener {
@EventHandler
public void onItemSpawn(final ItemSpawnEvent event) {
Location l = event.getEntity().getLocation();
ChatUtil.sendDebug("X: " + l.getX() + ", Y:" + l.getY() + ", Z: " + l.getZ());
}
}
private class DamageSys implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
double damage = event.getDamage(EntityDamageEvent.DamageModifier.BASE);
double origDamage = event.getOriginalDamage(EntityDamageEvent.DamageModifier.BASE);
if (damage == origDamage) return;
for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) {
if (modifier == EntityDamageEvent.DamageModifier.BASE) continue;
if (!event.isApplicable(modifier)) continue;
event.setDamage(modifier, event.getDamage(modifier) * (damage / origDamage));
}
}
}
}
|
package com.virjar.sipsoup.util;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.virjar.sipsoup.exception.EvaluateException;
import com.virjar.sipsoup.exception.FinalTypeNotSameException;
import com.virjar.sipsoup.model.SIPNode;
import com.virjar.sipsoup.model.XpathEvaluator;
import com.virjar.sipsoup.parse.expression.SyntaxNode;
/**
* @author virjar
*/
public class XpathUtil {
/**
* index
*
* @param e
* @return
*/
public static int getElIndexInSameTags(Element e) {
Elements chs = e.parent().children();
int index = 1;
for (Element cur : chs) {
if (e.tagName().equals(cur.tagName())) {
if (e.equals(cur)) {
return index;
} else {
index ++;
}
}
}
return index;
}
/**
*
*
* @param e
* @return
*/
public static int sameTagElNums(Element e) {
Elements els = e.parent().getElementsByTag(e.tagName());
return els.size();
}
public static void checkSameResultType(Collection<XpathEvaluator> xpathEvaluators)
throws FinalTypeNotSameException {
SIPNode.NodeType nodeType = null;
for (XpathEvaluator xpathEvaluator : xpathEvaluators) {
if (nodeType == null) {
nodeType = xpathEvaluator.judeNodeType();
} else if (nodeType != xpathEvaluator.judeNodeType()) {
throw new FinalTypeNotSameException();
}
}
}
public static String toPlainString(Object obj) {
if (obj == null) {
return "null";
}
return obj.toString();
}
public static Element root(Element el) {
while (el.parent() == null) {
el = el.parent();
}
return el;
}
public static BigDecimal toBigDecimal(Number number) {
if (number instanceof BigDecimal) {
return (BigDecimal) number;
}
if (number instanceof Integer) {
return new BigDecimal(number.intValue());
}
if (number instanceof Double || number instanceof Float) {// BigDecimal float double
return new BigDecimal(number.doubleValue());
}
if (number instanceof Long) {
return BigDecimal.valueOf(number.longValue());
}
return new BigDecimal(number.toString());
}
public static Integer firstParamToInt(List<SyntaxNode> params, Element element, String functionName) {
if (params.size() > 0) {
Object calc = params.get(0).calc(element);
if (calc != null && !(calc instanceof Integer)) {
throw new EvaluateException(functionName + " parameter must be integer");
} else {
if (calc != null) {
return (Integer) calc;
}
}
}
return null;
}
public static List<Element> transformToElement(List<SIPNode> SIPNodes) {
return Lists.newLinkedList(Iterables.transform(Iterables.filter(SIPNodes, new Predicate<SIPNode>() {
@Override
public boolean apply(SIPNode input) {
return input.getElement() != null;
}
}), new Function<SIPNode, Element>() {
@Override
public Element apply(SIPNode input) {
return input.getElement();
}
}));
}
public static List<String> transformToString(List<SIPNode> SIPNodes) {
return Lists.newLinkedList(Iterables.transform(Iterables.filter(SIPNodes, new Predicate<SIPNode>() {
@Override
public boolean apply(SIPNode input) {
return input.isText();
}
}), new Function<SIPNode, String>() {
@Override
public String apply(SIPNode input) {
return input.getTextVal();
}
}));
}
}
|
package collections;
import collections.interfaces.Locator;
import collections.interfaces.OrderedDictionary;
import java.util.Iterator;
/**
* @author yvesbeutler
* Basic implementation of a search tree.
*/
public class MyAVLTree<K extends Comparable<? super K>, E> implements OrderedDictionary<K, E> {
private Node root;
private int size;
private class Node implements Locator<K, E> {
K key;
E element;
int height;
Node parent, left, right;
Object creator = MyAVLTree.this;
Node() {}
Node(K key, E element) {
this.key = key;
this.element = element;
}
@Override
public E getElement() {
return element;
}
@Override
public K key() {
return key;
}
boolean isExternal() {
return left == null;
}
boolean isLeftChild() {
return parent != null && parent.left == this;
}
boolean isRightChild() {
return parent != null && parent.right == this;
}
void expand(K key, E element) {
this.key = key;
this.element = element;
left = new Node();
right = new Node();
left.parent = this;
right.parent = this;
height = 1;
}
}
public static void main(String[] args) {
MyAVLTree<Integer, String> avl = new MyAVLTree<>();
avl.addRoot(4, "");
avl.insert(7, "Sascha");
avl.insert(2, "Joy");
avl.insert(5, "Joris");
avl.printKeys();
}
private void addRoot(K key, E element) {
root = new Node(key, element);
root.left = new Node();
root.right = new Node();
}
private void printKeys() {
System.out.println("size: " + size());
}
private void adjustHeightAboveAndBalance(Node node) {
node = node.parent;
while (node != null) {
// get new height
int h = 1 + Math.max(node.left.height, node.right.height);
boolean balanced = Math.abs(node.left.height - node.right.height) < 2;
if (node.height == h && balanced) {
return;
}
// set new height
node.height = h;
if (!balanced) {
// adjust structure
node = restructure(node);
}
node = node.parent;
}
}
private Node restructure(Node node) {
Node parent = node.parent;
Node x, y, z = node;
Node a, b, c, t1, t2;
// if left subtree > right subtree
if (z.left.height > z.right.height) {
c = z;
y = z.left;
// check if single or double rotation
if (y.left.height > z.right.height) {
x = y.left;
t1 = x.right;
t2 = y.right;
b = y;
a = x;
} else {
// double rotation
x = y.right;
t1 = x.left;
t2 = x.right;
a = y;
b = x;
}
}
// if right subtree > left subtree
else {
a = z;
y = z.right;
// check if single or double rotation
if (y.right.height >= y.left.height) {
x = y.right;
b = y;
c = x;
t1 = y.left;
t2 = x.left;
} else {
x = y.left;
b = x;
c = y;
t1 = x.left;
t2 = x.right;
}
}
// switch nodes
b.parent = parent;
if (parent != null) {
if (parent.left == z) {
parent.left = b;
} else {
parent.right = b;
}
} else {
root = b;
}
b.right = c;
b.left = a;
a.parent = b;
c.parent = b;
// for subtree
a.right = t1;
t1.parent = a;
c.left = t2;
t2.parent = c;
// calculate new heights
a.height = Math.max(a.left.height, a.right.height) + 1;
c.height = Math.max(c.left.height, c.right.height) + 1;
b.height = Math.max(b.left.height, b.right.height) + 1;
return b;
}
@Override
public int size() {
return size;
}
@Override
public Locator<K, E> find(K key) {
return null;
}
@Override
public Locator<K, E>[] findAll(K key) {
return null;
}
@Override
public Locator<K, E> insert(K key, E o) {
Node node = root;
while (!node.isExternal()) {
if (key.compareTo(node.key) < 0) {
node = node.left;
} else {
node = node.right;
}
}
// add content to former external node
node.expand(key, o);
// set new height and balance
adjustHeightAboveAndBalance(node);
size++;
return node;
}
@Override
public void remove(Locator<K, E> loc) {
}
@Override
public Locator<K, E> closestBefore(K key) {
return null;
}
@Override
public Locator<K, E> closestAfter(K key) {
return null;
}
@Override
public Locator<K, E> next(Locator<K, E> loc) {
return null;
}
@Override
public Locator<K, E> previous(Locator<K, E> loc) {
return null;
}
@Override
public Locator<K, E> min() {
return null;
}
@Override
public Locator<K, E> max() {
return null;
}
@Override
public Iterator<Locator<K, E>> sortedLocators() {
return null;
}
}
|
package com.wizzardo.servlet;
import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.http.Path;
import com.wizzardo.http.request.Header;
import com.wizzardo.http.response.CookieBuilder;
import com.wizzardo.http.response.Response;
import com.wizzardo.http.response.Status;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class HttpResponse extends Response implements HttpServletResponse {
protected static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
private ByteArrayOutputStream buffer;
private PrintWriter writer;
private int status = 200;
private String statusMessage;
private Context context;
private HttpRequest request;
protected String contentType;
protected String charset;
boolean hasWriter() {
return writer != null;
}
byte[] getData() {
if (writer == null)
return null;
writer.flush();
byte[] bytes = buffer.toByteArray();
buffer.reset();
return bytes;
}
void setContext(Context context) {
this.context = context;
}
void setRequest(HttpRequest request) {
this.request = request;
}
@Override
public void addCookie(Cookie cookie) {
CookieBuilder cb = new CookieBuilder(cookie.getName(), cookie.getValue());
if (cookie.getMaxAge() > 0)
cb.expires(System.currentTimeMillis() + 1000 * cookie.getMaxAge());
else if (cookie.getMaxAge() == 0)
cb.expires(0);
if (cookie.getPath() != null)
cb.path(cookie.getPath());
if (cookie.getDomain() != null)
cb.domain(cookie.getDomain());
if (cookie.isHttpOnly())
cb.httpOnly();
if (cookie.getSecure())
cb.secure();
String c = cb.build();
if (cookie.getComment() != null)
cookie.setVersion(1);
if (cookie.getVersion() != 0) {
StringBuilder sb = new StringBuilder(c);
sb.append(";Version=").append(cookie.getVersion());
if (cookie.getComment() != null)
sb.append(";Comment=").append(cookie.getComment());
c = sb.toString();
}
setCookie(c);
}
@Override
public String encodeURL(String url) {
return url;
}
@Override
public String encodeRedirectURL(String url) {
return url;
}
@Override
public String encodeUrl(String url) {
return url;
}
@Override
public String encodeRedirectUrl(String url) {
return url;
}
@Override
public void sendError(int sc, String msg) throws IOException {
if (isCommitted())
throw new IllegalStateException("the response has already been committed");
setHeader(Header.KEY_CONTENT_TYPE, Header.VALUE_CONTENT_TYPE_HTML_UTF8);
setBody(msg); //todo: render custom error page
status = sc;
commit(request.connection());
}
@Override
public void sendError(int sc) throws IOException {
sendError(sc, "Error: " + sc);
}
@Override
public void sendRedirect(String location) throws IOException {
if (isCommitted())
throw new IllegalStateException("the response has already been committed");
if (location.startsWith("/"))
location = context.createAbsoluteUrl(location);
else if (!location.startsWith("http:
Path path = request.path();
if (!path.isEndsWithSlash())
path = path.subPath(0, path.length() - 1);
path = path.add(location);
location = context.createAbsoluteUrl(path.toString());
}
setRedirectTemporarily(location);
}
@Override
public void setDateHeader(String name, long date) {
header(name, dateFormatThreadLocal.get().format(new Date(date)));
}
@Override
public void addDateHeader(String name, long date) {
appendHeader(name, dateFormatThreadLocal.get().format(new Date(date)));
}
@Override
public void addHeader(String name, String value) {
appendHeader(name, value);
}
@Override
public void setIntHeader(String name, int value) {
header(name, String.valueOf(value));
}
@Override
public void addIntHeader(String name, int value) {
appendHeader(name, String.valueOf(value));
}
@Override
public void setStatus(int sc) {
status = sc;
}
@Override
public void setStatus(int sc, String sm) {
status = sc;
statusMessage = sm;
}
@Override
public Response setStatus(Status status) {
setStatus(status.code, status.message);
return this;
}
@Override
protected byte[] statusToBytes() {
if (statusMessage == null)
return ("HTTP/1.1 " + status + "\r\n").getBytes();
else
return ("HTTP/1.1 " + status + " " + statusMessage + "\r\n").getBytes();
}
@Override
public int getStatus() {
return status;
}
@Override
public String getHeader(String name) {
return header(name);
}
@Override
public Collection<String> getHeaders(String name) {
return headers(name);
}
@Override
public Collection<String> getHeaderNames() {
return headerNames();
}
@Override
public String getCharacterEncoding() {
return charset;
}
@Override
public String getContentType() {
if (charset != null && contentType != null)
return contentType + "; charset=" + charset;
return contentType;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return getOutputStream(request.connection()).getServletOutputStream();
}
@Override
public PrintWriter getWriter() throws IOException {
if (writer == null)
writer = new PrintWriter(new OutputStreamWriter(provideOut(), charset != null ? Charset.forName(charset) : StandardCharsets.UTF_8), true);
return writer;
}
protected OutputStream provideOut() throws IOException {
if (request.isAsyncStarted())
return getOutputStream();
if (buffer == null)
buffer = new ByteArrayOutputStream();
return buffer;
}
@Override
public void setCharacterEncoding(String charset) {
this.charset = charset;
}
@Override
public void setContentLength(int len) {
header(Header.KEY_CONTENT_LENGTH, len);
}
@Override
public void setContentLengthLong(long len) {
header(Header.KEY_CONTENT_LENGTH, len);
}
@Override
public void setContentType(String type) {
int i = type.indexOf("charset=");
if (i == -1) {
contentType = type;
} else {
charset = type.substring(i + 8);
contentType = type.substring(0, type.lastIndexOf(";", i));
}
}
@Override
public void setBufferSize(int size) {
}
@Override
public int getBufferSize() {
return 0;
}
@Override
public void flushBuffer() throws IOException {
if (!isCommitted())
commit(request.connection());
}
@Override
public void resetBuffer() {
if (isCommitted())
throw new IllegalStateException("the response has already been committed");
}
@Override
public void reset() {
if (isCommitted())
throw new IllegalStateException("the response has already been committed");
if (buffer == null)
return;
buffer.reset();
writer = null;
}
@Override
public ReadableData toReadableBytes() {
if (contentType != null && charset != null)
header(Header.KEY_CONTENT_TYPE, contentType + "; charset=" + charset);
else if (contentType != null)
header(Header.KEY_CONTENT_TYPE, contentType);
return super.toReadableBytes();
}
@Override
public void setLocale(Locale loc) {
throw new UnsupportedOperationException("Not implemented yet.");
}
@Override
public Locale getLocale() {
throw new UnsupportedOperationException("Not implemented yet.");
}
}
|
package com.backendless;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.SurfaceHolder;
import com.backendless.exceptions.BackendlessException;
import com.backendless.media.DisplayOrientation;
import com.backendless.media.Session;
import com.backendless.media.SessionBuilder;
import com.backendless.media.StreamProtocolType;
import com.backendless.media.StreamType;
import com.backendless.media.StreamVideoQuality;
import com.backendless.media.audio.AudioQuality;
import com.backendless.media.gl.SurfaceView;
import com.backendless.media.rtsp.RtspClient;
import com.backendless.media.video.VideoQuality;
public final class Media
{
private final static String WOWZA_SERVER_IP = "media.backendless.com";
private final static String WOWZA_SERVER_LIVE_APP_NAME = "mediaAppLive";
private final static String WOWZA_SERVER_VOD_APP_NAME = "mediaAppVod";
private final static Integer WOWZA_SERVER_PORT = 1935;
private final static String RTSP_PROTOCOL = StreamProtocolType.RTSP.getValue();
private final static String HLS_PROTOCOL = StreamProtocolType.HLS.getValue();
private static final String MEDIA_FILES_LOCATION = "/files/media/";
private static final String HLS_PLAYLIST_CONSTANT = "/playlist.m3u8";
private RtspClient rtspClient;
private Session session;
private MediaPlayer mediaPlayer;
private StreamProtocolType protocolType;
private static final Media instance = new Media();
static Media getInstance()
{
return instance;
}
public void toggleFlash()
{
checkSessionIsNull();
session.toggleFlash();
}
public StreamVideoQuality getStreamQuality()
{
checkSessionIsNull();
VideoQuality videoQuality = session.getVideoTrack().getVideoQuality();
int width = videoQuality.resX;
int height = videoQuality.resY;
int framerate = videoQuality.framerate;
int bitrate = videoQuality.bitrate;
StreamVideoQuality streamQuality = StreamVideoQuality.getFromString( width + "x" + height + ", " + framerate + " fps, " + bitrate
/ 1000 + " Kbps" );
return streamQuality;
}
public void setVideoQuality( StreamVideoQuality streamQuality )
{
checkSessionIsNull();
if( streamQuality == null )
{
return;
}
VideoQuality videoQuality = convertVideoQuality( streamQuality );
session.setVideoQuality( videoQuality );
}
private VideoQuality convertVideoQuality( StreamVideoQuality streamQuality )
{
Pattern pattern = Pattern.compile( "(\\d+)x(\\d+)\\D+(\\d+)\\D+(\\d+)" );
Matcher matcher = pattern.matcher( streamQuality.getValue() );
matcher.find();
int width = Integer.parseInt( matcher.group( 1 ) );
int height = Integer.parseInt( matcher.group( 2 ) );
int framerate = Integer.parseInt( matcher.group( 3 ) );
int bitrate = Integer.parseInt( matcher.group( 4 ) ) * 1000;
VideoQuality videoQuality = new VideoQuality( width, height, framerate, bitrate );
return videoQuality;
}
public void setAudioQuality( int sampleRate, int bitRate )
{
checkSessionIsNull();
session.setAudioQuality( new AudioQuality( sampleRate, bitRate ) );
}
public void switchCamera()
{
checkSessionIsNull();
session.switchCamera();
}
public void startPreview()
{
checkSessionIsNull();
session.startPreview();
}
public void stopPreview()
{
checkSessionIsNull();
session.stopPreview();
}
private void stopClientStream()
{
checkRtspClientIsNull();
rtspClient.stopStream();
}
public void releaseSession()
{
checkSessionIsNull();
session.release();
}
public void releaseClient()
{
checkRtspClientIsNull();
rtspClient.release();
}
public boolean isPublishing()
{
checkRtspClientIsNull();
return rtspClient.isStreaming();
}
public boolean isMediaPlayerBusy()
{
checkPlayerIsNull();
return mediaPlayer.isPlaying();
}
private void checkPlayerIsNull()
{
if( mediaPlayer == null )
{
throw new BackendlessException( "Player client is null. Method configure( .. ) must be invoked" );
}
}
private void checkSessionIsNull()
{
if( session == null )
{
throw new BackendlessException( "Session client is null. Method configure( .. ) must be invoked" );
}
}
private void checkRtspClientIsNull()
{
if( rtspClient == null )
{
throw new BackendlessException( "Streaming client is null. Method configure( .. ) must be invoked" );
}
}
/**
* <p>
* default video quality to 176x144 20fps 500Kbps<br/>
* default audio quality to 16 000 sampleRate 272000 bitRate
* </p>
*/
public void configureForPublish( Context context, SurfaceView mSurfaceView, DisplayOrientation orientation )
{
session = getSession( context, mSurfaceView, orientation.getValue() );
rtspClient = getRtspClient( context, session );
}
/**
* StreamProtocolType sets to default value - RTSP
*
* @param mSurfaceHolder
*/
public void configureForPlay( SurfaceHolder mSurfaceHolder )
{
configureForPlay( mSurfaceHolder, StreamProtocolType.RTSP );
}
public void configureForPlay( SurfaceHolder mSurfaceHolder, StreamProtocolType protocolType )
{
this.protocolType = protocolType;
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay( mSurfaceHolder );
mediaPlayer.setAudioStreamType( AudioManager.STREAM_MUSIC );
mediaPlayer.setOnPreparedListener( new OnPreparedListener() {
@Override
public void onPrepared( MediaPlayer mp )
{
mp.start();
}
} );
}
public void recordVideo( String tube, String streamName ) throws BackendlessException
{
startRtspStream( tube, streamName, StreamType.LIVE_RECORDING );
}
public void broadcastLiveVideo( String tube, String streamName ) throws BackendlessException
{
startRtspStream( tube, streamName, StreamType.LIVE );
}
public void playLiveVideo( String tube, String streamName ) throws IllegalArgumentException, SecurityException, IllegalStateException,
IOException, BackendlessException
{
playStream( tube, streamName, StreamType.RECORDING );
}
public void playOnDemandVideo( String tube, String streamName ) throws IllegalArgumentException, SecurityException,
IllegalStateException, IOException, BackendlessException
{
playStream( tube, streamName, StreamType.AVAILABLE );
}
private void startRtspStream( String tube, String streamName, StreamType streamType ) throws BackendlessException
{
checkSessionIsNull();
checkRtspClientIsNull();
if( mediaPlayer != null )
{
mediaPlayer.reset();
}
streamName = makeNameValid( streamName );
tube = makeTubeValid( tube );
String operationType = getOperationType( streamType );
String params = getConnectParams( tube, operationType, streamName );
startStream( rtspClient, streamName, params );
}
public void stopBroadcast()
{
checkRtspClientIsNull();
if( rtspClient.isStreaming() )
{
stopClientStream();
}
}
public void stopRecording()
{
checkRtspClientIsNull();
if( rtspClient.isStreaming() )
{
stopClientStream();
}
}
private String getOperationType( StreamType streamType )
{
return ( streamType == StreamType.LIVE ) ? "publishLive" : "publishRecorded";
}
private void playStream( String tube, String streamName, StreamType streamType ) throws IllegalArgumentException, SecurityException,
IllegalStateException, IOException, BackendlessException
{
checkPlayerIsNull();
if( mediaPlayer.isPlaying() )
{
throw new BackendlessException( "Other stream is playing now. You must to stop it before" );
}
streamName = makeNameValid( streamName );
tube = makeTubeValid( tube );
if( session != null )
{
session.stopPreview();
}
mediaPlayer.reset();
if( protocolType == null )
{
protocolType = StreamProtocolType.RTSP;
}
String protocol = getProtocol( protocolType );
String operationType = ( streamType == StreamType.RECORDING ) ? "playLive" : "playRecorded";
String wowzaAddress = WOWZA_SERVER_IP + ":" + WOWZA_SERVER_PORT + "/"
+ ( ( streamType == StreamType.RECORDING ) ? WOWZA_SERVER_LIVE_APP_NAME : WOWZA_SERVER_VOD_APP_NAME ) + "/_definst_/";
String params = getConnectParams( tube, operationType, streamName );
String streamPath = getStreamName( streamName, protocolType );
String url = protocol + wowzaAddress + streamPath + params;
mediaPlayer.setDataSource( url );
mediaPlayer.prepareAsync();
mediaPlayer.start();
}
private String makeTubeValid( String tube )
{
if( tube == null || tube.isEmpty() )
{
tube = "default";
}
else
{
tube = tube.trim();
}
return tube;
}
private String makeNameValid( String streamName )
{
if( streamName == null || streamName.isEmpty() )
{
streamName = "default";
}
else
{
streamName = streamName.trim().replace( '.', '_' );
}
return streamName;
}
public void stopVideoPlayback()
{
checkPlayerIsNull();
if( mediaPlayer.isPlaying() )
{
mediaPlayer.stop();
mediaPlayer.reset();
}
}
private String getStreamName( String fileName, StreamProtocolType protocol )
{
String subDir = Backendless.getApplicationId().toLowerCase() + MEDIA_FILES_LOCATION;
String hlsAdditionalParameter = ( protocol == StreamProtocolType.HLS ) ? HLS_PLAYLIST_CONSTANT : "";
return subDir + fileName + hlsAdditionalParameter;
}
private String getProtocol( StreamProtocolType streamProtocolType )
{
if( streamProtocolType.equals( StreamProtocolType.RTSP ) )
{
return RTSP_PROTOCOL;
}
if( streamProtocolType.equals( StreamProtocolType.HLS ) )
{
return HLS_PROTOCOL;
}
throw new BackendlessException( "Backendless Android SDK not supported protocol type '" + streamProtocolType + "'" );
}
private Session getSession( Context context, SurfaceView mSurfaceView, int orientation )
{
Session mSession = SessionBuilder.getInstance().setContext( context ).setAudioEncoder( SessionBuilder.AUDIO_AAC )
.setVideoEncoder( SessionBuilder.VIDEO_H264 ).setSurfaceView( mSurfaceView ).setPreviewOrientation( orientation )
.setCallback( (Session.Callback) context ).build();
return mSession;
}
private String getConnectParams( String tube, String operationType, String streamName )
{
String paramsToSend;
BackendlessUser currentUser = Backendless.UserService.CurrentUser();
Object identity = currentUser != null ? currentUser.getProperty( "user-token" ) : null;
HashMap<String, String> map = new HashMap<String, String>();
map.putAll( HeadersManager.getInstance().getHeaders() );
map.put( "identity", identity != null ? identity.toString() : map.get( "user-token" ) );
paramsToSend = "?application-id=" + map.get( "application-id" ) + "&version=" + Backendless.getVersion() + "&identity="
+ map.get( "identity" ) + "&tube=" + tube + "&operationType=" + operationType + "&streamName=" + streamName;
return paramsToSend;
}
// Connects/disconnects to the RTSP server and starts/stops the stream
private void startStream( RtspClient rtspClient, String streamName, String params ) throws BackendlessException
{
if( rtspClient.isStreaming() )
{
throw new BackendlessException( "Rtsp client is working on other stream" );
}
rtspClient.setServerAddress( WOWZA_SERVER_IP, WOWZA_SERVER_PORT );
rtspClient.setStreamPath( "/" + WOWZA_SERVER_LIVE_APP_NAME + "/" + streamName + params );
rtspClient.startStream();
}
private RtspClient getRtspClient( Context context, Session mSession )
{
// Configures the RTSP client
if( rtspClient == null )
{
rtspClient = new RtspClient();
rtspClient.setSession( mSession );
rtspClient.setCallback( (RtspClient.Callback) context );
}
return rtspClient;
}
public StreamProtocolType getProtocolType()
{
return protocolType;
}
public void setProtocolType( StreamProtocolType protocolType )
{
this.protocolType = protocolType;
}
}
|
package com.wuest.prefab.Gui;
import com.wuest.prefab.Gui.Controls.GuiTab;
import com.wuest.prefab.Gui.Controls.GuiTabTray;
import com.wuest.prefab.Structures.Gui.GuiStructure;
import com.wuest.prefab.Tuple;
import net.minecraft.client.gui.widget.button.Button;
import java.util.ArrayList;
/**
* @author WuestMan
*/
public class GuiTabScreen extends GuiStructure {
protected GuiTabTray Tabs;
public GuiTabScreen() {
super("TabScreen");
this.Tabs = new GuiTabTray();
}
/**
* Processes when this tab is clicked.
*
* @param tab The tab which was clicked.
*/
protected void tabClicked(GuiTab tab) {
}
protected GuiTab getSelectedTab() {
return this.Tabs.GetSelectedTab();
}
@Override
public void init() {
this.Tabs.GetTabs().clear();
this.children.add(this.Tabs);
}
/**
* Draws the screen and all the components in it.
*/
@Override
public void render(int mouseX, int mouseY, float partialTicks) {
// Draw the default labels and buttons.
super.render(mouseX, mouseY, partialTicks);
// Draw the tabs.
assert this.minecraft != null;
this.Tabs.DrawTabs(this.minecraft, mouseX, mouseY);
}
public void buttonClicked(Button button) {
// This does nothing on purpose.
}
@Override
protected void postButtonRender(int x, int y) {
}
/**
* Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton
*/
@Override
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
boolean returnValue = false;
if (mouseButton == 0) {
// This handles the button presses.
returnValue = super.mouseClicked(mouseX, mouseY, mouseButton);
if (returnValue) {
// Handle the tab clicking.
ArrayList<GuiTab> guiTabs = this.Tabs.GetTabs();
for (GuiTab tab : guiTabs) {
if (tab.mouseClicked(mouseX, mouseY, mouseButton)) {
assert this.minecraft != null;
tab.playDownSound(this.minecraft.getSoundHandler());
this.tabClicked(tab);
break;
}
}
}
}
return returnValue;
}
}
|
package org.griphyn.vdl.karajan;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.globus.cog.karajan.stack.LinkedStack;
import org.globus.cog.karajan.stack.VariableStack;
import org.globus.cog.karajan.util.Monitor;
import org.globus.cog.karajan.workflow.ElementTree;
import org.globus.cog.karajan.workflow.PrintStreamChannel;
import org.globus.cog.karajan.workflow.nodes.FlowElement;
import org.globus.cog.util.ArgumentParser;
import org.globus.cog.util.ArgumentParserException;
import org.griphyn.vdl.engine.Karajan;
import org.griphyn.vdl.karajan.functions.ConfigProperty;
import org.griphyn.vdl.toolkit.VDLt2VDLx;
import org.griphyn.vdl.util.VDL2Config;
import org.griphyn.vdl.util.VDL2ConfigProperties;
import org.griphyn.vdl.util.VDL2ConfigProperties.PropInfo;
public class Loader extends org.globus.cog.karajan.Loader {
private static final Logger logger = Logger.getLogger(Loader.class);
public static final String ARG_HELP = "help";
public static final String ARG_MONITOR = "monitor";
public static final String ARG_RESUME = "resume";
public static final String ARG_INSTANCE_CONFIG = "config";
public static final String ARG_TYPECHECK = "typecheck";
public static final String ARG_DRYRUN = "dryrun";
public static final String ARG_VERBOSE = "verbose";
public static final String ARG_DEBUG = "debug";
public static final String ARG_LOGFILE = "logfile";
public static final String CONST_VDL_OPERATION = "vdl:operation";
public static final String VDL_OPERATION_RUN = "run";
public static final String VDL_OPERATION_TYPECHECK = "typecheck";
public static final String VDL_OPERATION_DRYRUN = "dryrun";
public static void main(String[] argv) {
ArgumentParser ap = buildArgumentParser();
long start = System.currentTimeMillis();
String project = null;
try {
ap.parse(argv);
Map arguments = new Hashtable();
if (ap.isPresent(ARG_HELP)) {
ap.usage();
System.exit(0);
}
if (ap.isPresent(ARG_MONITOR)) {
new Monitor().start();
}
if (!ap.hasValue(ArgumentParser.DEFAULT)) {
error("No project specified");
}
project = ap.getStringValue(ArgumentParser.DEFAULT);
}
catch (ArgumentParserException e) {
System.err.println("Error parsing arguments: " + e.getMessage() + "\n");
ap.usage();
System.exit(1);
}
boolean runerror = false;
try {
if (project.endsWith(".dtm") || project.endsWith(".swift")) {
project = compile(project);
}
ElementTree tree = null;
if (project != null) {
tree = load(project);
}
else {
System.err.println("No project specified");
ap.usage();
System.exit(1);
}
tree.setName(project);
tree.getRoot().setProperty(FlowElement.FILENAME, project);
VDL2ExecutionContext ec = new VDL2ExecutionContext(tree, project);
setupLogging(ap, project, ec.getRunID());
// no order
ec.setStdout(new PrintStreamChannel(System.out, true));
if (ap.hasValue(ARG_RESUME)) {
ec.addArgument("-rlog:resume=" + ap.getStringValue(ARG_RESUME));
}
VariableStack stack = new LinkedStack(ec);
VDL2Config config = loadConfig(ap, stack);
addCommandLineProperties(config, ap);
if (ap.isPresent(ARG_DRYRUN)) {
stack.setGlobal(CONST_VDL_OPERATION, VDL_OPERATION_DRYRUN);
}
else if (ap.isPresent(ARG_TYPECHECK)) {
stack.setGlobal(CONST_VDL_OPERATION, VDL_OPERATION_TYPECHECK);
}
else {
stack.setGlobal(CONST_VDL_OPERATION, VDL_OPERATION_RUN);
}
stack.setGlobal("vds.home", System.getProperty("vds.home"));
ec.start(stack);
ec.setArguments(ap.getArguments());
ec.waitFor();
if (ec.isFailed()) {
runerror = true;
}
}
catch (Exception e) {
logger.debug("Detailed exception:", e);
error("Could not start execution.\n\t" + e.getMessage());
}
System.exit(runerror ? 2 : 0);
}
private static String compile(String project) throws Exception {
try {
File dtm = new File(project);
File dir = dtm.getParentFile();
File xml = new File(project.substring(0, project.lastIndexOf('.')) + ".xml");
File kml = new File(project.substring(0, project.lastIndexOf('.')) + ".kml");
if (dtm.lastModified() > kml.lastModified()) {
logger.info(project + ": file is out of date. Recompiling.");
InputStream stdin = System.in;
PrintStream stdout = System.out;
System.setIn(new FileInputStream(dtm));
System.setOut(new PrintStream(new FileOutputStream(xml)));
VDLt2VDLx.compile(new String[0]);
System.setIn(stdin);
System.setOut(new PrintStream(new FileOutputStream(kml)));
Karajan.main(new String[] { xml.getAbsolutePath() });
System.setOut(stdout);
}
return kml.getAbsolutePath();
}
catch (Exception e) {
throw new Exception("Failed to compile " + project, e);
}
}
private static VDL2Config loadConfig(ArgumentParser ap, VariableStack stack) throws IOException {
VDL2Config conf;
if (ap.hasValue(ARG_INSTANCE_CONFIG)) {
String configFile = ap.getStringValue(ARG_INSTANCE_CONFIG);
stack.setGlobal(ConfigProperty.INSTANCE_CONFIG_FILE, configFile);
conf = VDL2Config.getConfig(configFile);
}
else {
conf = (VDL2Config) VDL2Config.getConfig().clone();
}
stack.setGlobal(ConfigProperty.INSTANCE_CONFIG, conf);
return conf;
}
private static void addCommandLineProperties(VDL2Config config, ArgumentParser ap) {
Map desc = VDL2ConfigProperties.getPropertyDescriptions();
Iterator i = desc.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
String name = (String) e.getKey();
if (ap.isPresent(name)) {
config.setProperty(name, ap.getStringValue(name));
}
}
}
private static ArgumentParser buildArgumentParser() {
ArgumentParser ap = new ArgumentParser();
ap.setArguments(true);
ap.setExecutableName("swift");
ap.addOption(ArgumentParser.DEFAULT, "A file (.dtm or .kml) to execute", "file",
ArgumentParser.OPTIONAL);
ap.addFlag(ARG_HELP, "Display usage information");
ap.addAlias(ARG_HELP, "h");
ap.addFlag(ARG_TYPECHECK, "Does a typecheck instead of executing the workflow");
ap.addFlag(ARG_DRYRUN,
"Runs the workflow without submitting any jobs (can be used to get a graph)");
ap.addFlag(ARG_MONITOR, "Shows a graphical resource monitor");
ap.addOption(ARG_RESUME, "Resumes the execution using a log file", "file",
ArgumentParser.OPTIONAL);
ap.addOption(
ARG_INSTANCE_CONFIG,
"Indicates the VDL2 configuration file to be used for this run."
+ " Properties in this configuration file will override the default properties. "
+ "If individual command line arguments are used for properties, they will override "
+ "the contents of this file.", "file", ArgumentParser.OPTIONAL);
ap.addFlag(ARG_VERBOSE,
"Increases the level of output that Swift produces on the console to include more detail "
+ "about the execution");
ap.addAlias(ARG_VERBOSE, "v");
ap.addFlag(ARG_DEBUG,
"Increases the level of output that Swift produces on the console to include lots of "
+ "detail about the execution");
ap.addAlias(ARG_DEBUG, "d");
ap.addOption(
ARG_LOGFILE,
"Specifies a file where log messages should go to. By default Swift "
+ "uses the name of the workflow being run and a numeric index (e.g. myworkflow.1.log)",
"file", ArgumentParser.OPTIONAL);
Map desc = VDL2ConfigProperties.getPropertyDescriptions();
Iterator i = desc.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
PropInfo pi = (PropInfo) e.getValue();
ap.addOption((String) e.getKey(), pi.desc, pi.validValues, ArgumentParser.OPTIONAL);
}
return ap;
}
protected static void setupLogging(ArgumentParser ap, String project, String runID)
throws IOException {
String logfile;
if (ap.isPresent(ARG_LOGFILE)) {
logfile = ap.getStringValue(ARG_LOGFILE);
}
else {
String name;
if (project.indexOf('.') == -1) {
name = "swift";
}
else {
name = project.substring(0, project.lastIndexOf('.'));
}
File f = new File(name + "-" + runID + ".log");
FileAppender fa = (FileAppender) getAppender(FileAppender.class);
if (fa == null) {
logger.warn("Failed to configure log file name");
}
else {
fa.setFile(f.getAbsolutePath());
fa.activateOptions();
}
}
Level level = Level.WARN;
if (ap.isPresent(ARG_VERBOSE)) {
level = Level.INFO;
}
if (ap.isPresent(ARG_DEBUG)) {
level = Level.DEBUG;
}
ConsoleAppender ca = (ConsoleAppender) getAppender(ConsoleAppender.class);
if (ca == null) {
logger.warn("Failed to configure console log level");
}
else {
ca.setThreshold(level);
ca.activateOptions();
}
}
protected static Appender getAppender(Class cls) {
Logger root = Logger.getRootLogger();
Enumeration e = root.getAllAppenders();
while (e.hasMoreElements()) {
Appender a = (Appender) e.nextElement();
if (cls.isAssignableFrom(a.getClass())) {
return a;
}
}
return null;
}
}
|
package com.rehab.world;
import com.rehab.world.Phys.Vector;
public class Arena {
// Playable bounds on-screen
private double mWidth, mHeight;
// Percentage of a real second as the game's smallest unit of time
private double mUnitTime;
// Title of the level
private String mName;
// Default gravity is at Earth level
private Vector mGrav;
// Entities to keep track of (those in the level)
private Iterable<Entity> mEntities;
private Actor mPlayer;
/**
* Constructor for a basic Arena.
* @param name
* a title for the level.
* @param width
* the playable area's width.
* @param height
* the playable area's height.
*/
public Arena(String name, double width, double height) {
mName = name;
mWidth = width;
mHeight = height;
// Setup gravity Vector
double gravStrength = Physics.getPlanetGravity(Physics.EARTH_MASS, Physics.EARTH_RADIUS);
mGrav = new Vector();
mGrav.updateFrom(Phys.UNIT_SOUTH);
mGrav.changeMagnitude(gravStrength);
}
/**
* Sets the unit of time to use for Entity physics.
* @param tickRate
* a fraction of a second.
*/
public void setTime(double tickRate) { mUnitTime = 1d / tickRate; }
/**
* [INCOMPLETE] Calculates the level's current game state. This includes instance locations, health
* and damage dealing, etc. In its current form, this method should only be used to
* test various reactions and / or functions and their values in a one-shot manner.
* Once an Entity reaches the floor of the Arena (getHeight() = 0), nothing more can
* be said of what will occur.
*/
public void step() {
for (Entity e : mEntities) {
// Disable objects beyond the screen
if (isOutside(e))
disable(e);
// Apply gravity
if (e.isGravityEnabled()) {
applyGravity(e);
for (Entity other : mEntities) {
// Check collisions
if (e == other) continue;
if (e.collidesWith(other)) {
// Snap object to floor
e.moveTo(e.getX(), other.getY() + e.getHeight());
e.setEnableGravity(false);
}
}
}
// Snap the character to the surface of the floor if sinks
if (isBelow(e)) {
double h = e.getHeight();
e.moveTo(e.getX(), h);
e.setEnableGravity(false);
}
}
}
/**
* Applies the Arena's gravity vector to a given Entity.
* @param e
* the Entity to affect.
*/
private void applyGravity(Entity e) {
Vector force = new Vector(mGrav);
// Scale force by time
force.multiply(mUnitTime);
e.moveImpulse(force);
}
/**
* Checks whether or not an Entity is below the Arena's boundaries.
* @param e
* the Entity whose location must be checked.
* @return
* true if the Entity is below the Arena, false otherwise.
*/
private boolean isBelow(Entity e) {
double y = e.getY();
double height = e.getHeight();
return (y - height) < 0;
}
/**
* Checks whether or not a given Entity is beyond the Arena's boundaries.
* @param e
* the Entity to check for.
* @return
* true if the Entity is outside the Arena, false otherwise.
*/
private boolean isOutside(Entity e) {
double x = e.getX(), y = e.getY();
if (x + e.getWidth() < 0 || x > mWidth || y - e.getHeight() > mHeight || y < 0)
return true;
return false;
}
/**
* Sets the Entity to no longer be drawn, disables gravity, and unloads the
* instance with the InstanceManager.
* @param e
* the Entity to disable.
*/
private void disable(Entity e) {
e.setVisibility(false);
e.setEnableGravity(false);
// Take it out of the game
InstanceManager.getInstance().unload(e);
}
/**
* Gets the title of the arena.
* @return
* the title.
*/
public String getName() { return mName; }
/**
* Gets the magnitude of acceleration due to gravity for the particular level.
* @return
* a Vector representing gravity in meters per second squared.
*/
public Vector getGravity() { return mGrav; }
/**
* Sets the Arena's level of gravity.
* @param gravity
* the magnitude of gravity in meters per second squared.
*/
public void setGravity(double gravity) {
if (mGrav == null) mGrav = new Vector();
mGrav = new Vector();
mGrav.updateFrom(Phys.UNIT_SOUTH);
}
/**
* Sets the Entities meant to appear in the level.
* @param it
* an Iterable of Entities in the level.
*/
public void setEntities(Iterable<Entity> iter) { mEntities = iter; }
/**
* Gets the user-controlled Actor.
* @return
* the Actor representing the user.
*/
public Actor getPlayer() { return mPlayer; }
/**
* Sets the Actor to be controlled by the user.
* @param player
* the user's Actor.
*/
public void setPlayer(Actor player) { mPlayer = player; }
/**
* Gets the width of the playable area.
* @return
* the Arena's width boundary.
*/
public double getWidth() { return mWidth; }
/**
* Gets the height of the playable area.
* @return
* the Arena's height boundary.
*/
public double getHeight() { return mHeight; }
}
|
package de.braintags.netrelay;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import de.braintags.io.vertx.util.ExceptionUtil;
import de.braintags.io.vertx.util.exception.ParameterRequiredException;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.templ.ThymeleafTemplateEngine;
/**
* Some Utility methods to handle requests
*
* @author mremme
*
*/
public class RequestUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);
private RequestUtil() {
}
/**
* Encodes the text into a suitable format for UTF-8 for http requests for instance
*
* @param text
* text to be encoded
* @return the encoded result
*/
public static String encodeText(String text) {
return encodeText(text, "UTF-8");
}
/**
* Encodes the text into a suitable format for http requests for instance
*
* @param text
* text to be encoded
* @param encoding
* the encoding used
* @return the encoded result
*/
public static String encodeText(String text, String encoding) {
try {
return URLEncoder.encode(text, encoding);
} catch (UnsupportedEncodingException e) {
throw ExceptionUtil.createRuntimeException(e);
}
}
/**
* Read the value of the defined key from a request parameter
*
* @param context
* the context to be handled
* @param key
* the key to retrive from the request parameters
* @param defaultValue
* will be returned, if value is null
* @param required
* if required and value is null, an exception is thrown
* @return the value or null, if none and not required
*/
public static String readParameterAttribute(RoutingContext context, String key, String defaultValue,
boolean required) {
String value = context.request().params().get(key);
if (value == null && required) {
throw new ParameterRequiredException(key);
}
return value == null ? defaultValue : value;
}
/**
* Read the value of the defined key from a transferred form request
*
* @param context
* the context to be handled
* @param key
* the key to retrive from the form parameters
* @param defaultValue
* will be returned, if value is null
* @param required
* if required and value is null, an exception is thrown
* @return the value or null, if none and not required
*/
public static String readFormAttribute(RoutingContext context, String key, String defaultValue, boolean required) {
String value = context.request().formAttributes().get(key);
if (value == null && required) {
throw new ParameterRequiredException(key);
}
return value == null ? defaultValue : value;
}
/**
* Render a specific template
*
* @param context
* @param path
* @param contentType
* @param templateDirectory
* @param thEngine
*/
public static void renderSpecificTemplate(RoutingContext context, String path, String contentType,
String templateDirectory, ThymeleafTemplateEngine thEngine) {
String file = templateDirectory + path;
thEngine.render(context, file, res -> {
if (res.succeeded()) {
context.response().putHeader(HttpHeaders.CONTENT_TYPE, contentType).end(res.result());
} else {
context.fail(res.cause());
}
});
}
/**
* Sending a redirect to another page
*
* @param response
* @param path
*/
public static void sendRedirect(HttpServerResponse response, String path) {
sendRedirect(response, null, path);
}
/**
* The same than {@link #sendRedirect(HttpServerResponse, HttpServerRequest, String, true)}
*
* @param response
* @param request
* @param path
*/
public static void sendRedirect(HttpServerResponse response, HttpServerRequest request, String path) {
sendRedirect(response, request, path, true);
}
/**
* Sending a redirect as 302 to another page by adding query parameters of a current request
*
* @param response
* @param request
* @param path
* @param reuseArguments
* if true, the query parameters of the current request are reused
*/
public static void sendRedirect(HttpServerResponse response, HttpServerRequest request, String path,
boolean resuseArguments) {
sendRedirect(response, request, path, resuseArguments, 302);
}
/**
* Sending a redirect to another page by adding query parameters of a current request
*
* @param response
* @param request
* @param path
* @param reuseArguments
* if true, the query parameters of the current request are reused
* param code - the http code to be used
*/
public static void sendRedirect(HttpServerResponse response, HttpServerRequest request, String path,
boolean resuseArguments, int code) {
LOGGER.info("sending redirect to " + path);
response.putHeader("location", createRedirectUrl(request, path, resuseArguments));
response.setStatusCode(code);
response.end();
}
/**
* The same than {@link #createRedirectUrl(HttpServerRequest, String, true)}
*
* @param request
* @param path
* @return
*/
public static String createRedirectUrl(HttpServerRequest request, String path) {
return createRedirectUrl(request, path, true);
}
/**
* Creates a url from the given information for a redirect. If request is not null, then current query parameters are
* added to the path
*
* @param request
* @param path
* @param reuseArguments
* if true, the query parameters of the current request are reused
* @return
*/
public static String createRedirectUrl(HttpServerRequest request, String path, boolean reuseArguments) {
String tmpPath = path;
if (request != null && reuseArguments) {
String qp = request.query();
if (qp != null && qp.hashCode() != 0) {
tmpPath += (path.indexOf('?') < 0 ? "?" : "&") + qp;
}
}
return tmpPath;
}
/**
* Loads the given property from the request
*
* @param context
* @param propName
* @param required
* @param errorObject
* @return
*/
public static String loadProperty(RoutingContext context, String propName, boolean required, JsonObject errorObject) {
String value = context.request().getParam(propName);
if (required && (value == null || value.trim().isEmpty()))
errorObject.put(propName + "Error", "parameter '" + propName + " is required");
return value;
}
public static String cleanPathElement(String value, String path) {
String[] elements = path.split("/");
Buffer buffer = Buffer.buffer(path.startsWith("/") ? "/" : "");
boolean added = false;
for (String element : elements) {
if (element != null && element.hashCode() != 0 && !element.equals(value)) {
buffer.appendString(added ? "/" : "").appendString(element);
added = true;
}
}
return buffer.appendString(path.endsWith("/") ? "/" : "").toString();
}
}
|
package org.jay3d.engine.math;
public class Matrix4f {
private float[][] m;
public Matrix4f(){
m = new float[4][4];
}
public Matrix4f initIdentity(){
for(int x = 0; x < 4; x++){
for(int y = 0; y < 4; y++){
m[x][y] = 0;
}
}
return this;
}
public Matrix4f initTranslation(float x, float y, float z){
m[0][0] = 1; m[0][1] = 0; m[0][2] = 0; m[0][3] = x;
m[1][0] = 0; m[1][1] = 1; m[1][2] = 0; m[1][3] = y;
m[2][0] = 0; m[2][1] = 0; m[2][2] = 1; m[2][3] = z;
m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
return this;
}
public Matrix4f initRotation(float x, float y, float z)
{
Matrix4f rx = new Matrix4f();
Matrix4f ry = new Matrix4f();
Matrix4f rz = new Matrix4f();
x = (float)Math.toRadians(x);
y = (float)Math.toRadians(y);
z = (float)Math.toRadians(z);
rz.m[0][0] = (float)Math.cos(z); rz.m[0][1] = -(float)Math.sin(z); rz.m[0][2] = 0; rz.m[0][3] = 0;
rz.m[1][0] = (float)Math.sin(z); rz.m[1][1] = (float)Math.cos(z); rz.m[1][2] = 0; rz.m[1][3] = 0;
rz.m[2][0] = 0; rz.m[2][1] = 0; rz.m[2][2] = 1; rz.m[2][3] = 0;
rz.m[3][0] = 0; rz.m[3][1] = 0; rz.m[3][2] = 0; rz.m[3][3] = 1;
rx.m[0][0] = 1; rx.m[0][1] = 0; rx.m[0][2] = 0; rx.m[0][3] = 0;
rx.m[1][0] = 0; rx.m[1][1] = (float)Math.cos(x); rx.m[1][2] = -(float)Math.sin(x); rx.m[1][3] = 0;
rx.m[2][0] = 0; rx.m[2][1] = (float)Math.sin(x); rx.m[2][2] = (float)Math.cos(x); rx.m[2][3] = 0;
rx.m[3][0] = 0; rx.m[3][1] = 0; rx.m[3][2] = 0; rx.m[3][3] = 1;
ry.m[0][0] = (float)Math.cos(y); ry.m[0][1] = 0; ry.m[0][2] = -(float)Math.sin(y); ry.m[0][3] = 0;
ry.m[1][0] = 0; ry.m[1][1] = 1; ry.m[1][2] = 0; ry.m[1][3] = 0;
ry.m[2][0] = (float)Math.sin(y); ry.m[2][1] = 0; ry.m[2][2] = (float)Math.cos(y); ry.m[2][3] = 0;
ry.m[3][0] = 0; ry.m[3][1] = 0; ry.m[3][2] = 0; ry.m[3][3] = 1;
m = rz.mul(ry.mul(rx)).getM();
return this;
}
public Matrix4f initScale(float x, float y, float z){
m[0][0] = x; m[0][1] = 0; m[0][2] = 0; m[0][3] = 0;
m[1][0] = 0; m[1][1] = y; m[1][2] = 0; m[1][3] = 0;
m[2][0] = 0; m[2][1] = 0; m[2][2] = z; m[2][3] = 0;
m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
return this;
}
public Matrix4f mul(Matrix4f v){
Matrix4f res = new Matrix4f();
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
res.set(i, j, m[i][0] * v.get(0, j)
+ m[i][1] * v.get(1, j)
+ m[i][2] * v.get(2, j)
+ m[i][3] * v.get(3, j));
}
}
return res;
}
public float get(int x, int y){
return m[x][y];
}
public void set(int x, int y, float value){
this.m[x][y] = value;
}
public float[][] getM() {
return m;
}
public void setM(float[][] m) {
this.m = m;
}
}
|
package eu.djakarta.tsEarthquake;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class EventSet {
private List<Event> magnitudeAscending;
private List<Event> timeAscending;
public EventSet(List<Event> list) {
this.magnitudeAscending = new LinkedList<>(list);
this.magnitudeAscending.sort(new MagnitudeEventComparator());
this.timeAscending = new LinkedList<>(list);
this.timeAscending.sort(new TimeEventComparator());
}
public List<Event> magnitudeAscendingSortedList() {
return Collections.unmodifiableList(this.magnitudeAscending);
}
public List<Event> timeAscendingSortedList() {
return Collections.unmodifiableList(this.timeAscending);
}
}
|
package org.jgroups.jmx;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.ManagedOperation;
import javax.management.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Vector;
/**
*
* A DynamicMBean wrapping an annotated object instance.
*
* @author Chris Mills
* @author Vladimir Blagojevic
* @version $Id: ResourceDMBean.java,v 1.3 2008/03/06 01:03:54 vlada Exp $
* @see ManagedAttribute
* @see ManagedOperation
* @see MBean
*
*/
public class ResourceDMBean implements DynamicMBean {
private static final Class[] primitives= { int.class,
byte.class,
short.class,
long.class,
float.class,
double.class,
boolean.class,
char.class };
private final Log log=LogFactory.getLog(ResourceDMBean.class);
private static final String MBEAN_DESCRITION="Dynamic MBean Description";
private final String name;
private final Object obj;
private String description = "";
int i=0;
public ResourceDMBean(Object obj,String name) {
this.obj=obj;
this.name=name;
}
public synchronized MBeanInfo getMBeanInfo() {
try {
Vector<MBeanAttributeInfo> vctAttributes=new Vector<MBeanAttributeInfo>();
Vector<MBeanOperationInfo> vctOperations=new Vector<MBeanOperationInfo>();
//set a field to hold the description of the MBean
MBean mbean=obj.getClass().getAnnotation(MBean.class);
if(mbean.description() != null && mbean.description().trim().length() > 0) {
if(log.isDebugEnabled()) {
log.debug("@MBean description set - " + mbean.description());
}
this.description=mbean.description();
vctAttributes.add(new MBeanAttributeInfo(ResourceDMBean.MBEAN_DESCRITION,
"java.lang.String",
"@MBean description",
true,
false,
false));
}
//walk class hierarchy and find all fields
for(Class<?> clazz=obj.getClass();
clazz != null && clazz.isAnnotationPresent(MBean.class);
clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(Field field:fields) {
ManagedAttribute attr=field.getAnnotation(ManagedAttribute.class);
if(attr != null) {
if(Modifier.isFinal(field.getModifiers())) {
//field is declared final - no changes allowed
if(log.isWarnEnabled() && attr.writable()) {
log.warn(field.getName() + " declared final, so cannot be marked as writable - writable is ignored");
}
vctAttributes.add(new MBeanAttributeInfo(field.getName(),
field.getType().getCanonicalName(),
attr.description(),
attr.readable(),
false,
false));
}
else {
vctAttributes.add(new MBeanAttributeInfo(field.getName(),
field.getType().getCanonicalName(),
attr.description(),
attr.readable(),
attr.writable(),
false));
}
if(log.isInfoEnabled()) {
log.info("@Attr found for field " + field.getName());
}
}
}
}
//find all methods
Method[] methods=obj.getClass().getMethods();
for(Method method:methods) {
ManagedAttribute attr=method.getAnnotation(ManagedAttribute.class);
if(attr != null) {
if(method.getParameterTypes().length == 0 && method.getReturnType() != java.lang.Void.TYPE) {
vctAttributes.add(new MBeanAttributeInfo(method.getName() + "()",
method.getReturnType().getCanonicalName(),
attr.description(),
attr.readable(),
false,
false));
if(log.isInfoEnabled()) {
log.info("@Attr found for method " + method.getName());
}
}
else {
if(log.isWarnEnabled()) {
log.warn("Method " + method.getName()
+ " must have a valid return type and zero parameters");
}
}
}
ManagedOperation op=method.getAnnotation(ManagedOperation.class);
if(op != null) {
vctOperations.add(new MBeanOperationInfo(op.description(), method));
if(log.isInfoEnabled()) {
log.info("@Operation found for method " + method.getName());
}
}
}
MBeanAttributeInfo[] attrInfo=new MBeanAttributeInfo[vctAttributes.size()];
vctAttributes.toArray(attrInfo);
MBeanOperationInfo[] operations=new MBeanOperationInfo[vctOperations.size()];
vctOperations.toArray(operations);
return new MBeanInfo(this.name, this.description, attrInfo, null, operations, null);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
public synchronized Object getAttribute(String name) {
if(log.isDebugEnabled()) {
log.debug("getAttribute called for " + name);
}
Attribute attr=getNamedAttribute(name);
if(log.isDebugEnabled()) {
log.debug("getAttribute value found " + attr.getValue());
}
return attr.getValue();
}
public synchronized void setAttribute(Attribute attribute) {
if(log.isDebugEnabled()) {
log.debug("setAttribute called for " + attribute.getName()
+ " value "
+ attribute.getValue());
}
setNamedAttribute(attribute);
}
public synchronized AttributeList getAttributes(String[] names) {
if(log.isDebugEnabled()) {
log.debug("getAttributes called");
for(String name:names) {
log.debug("Attribute name " + name);
}
}
AttributeList al=new AttributeList();
for(String name:names) {
Attribute attr=getNamedAttribute(name);
if(attr != null) {
if(log.isDebugEnabled()) {
log.debug("Attribute " + name + " found with value " + attr.getValue());
}
al.add(attr);
}
}
return al;
}
public synchronized AttributeList setAttributes(AttributeList list) {
if(log.isDebugEnabled()) {
log.debug("setAttributes called");
}
AttributeList results=new AttributeList();
for(int i=0;i < list.size();i++) {
Attribute attr=(Attribute)list.get(i);
if(log.isDebugEnabled()) {
log.debug("Attribute name " + attr.getName() + " new value is " + attr.getValue());
}
if(setNamedAttribute(attr)) {
results.add(attr);
}
else {
if(log.isWarnEnabled()) {
log.debug("Failed to update attribute name " + attr.getName()
+ " with value "
+ attr.getValue());
}
}
}
return results;
}
public Object invoke(String name, Object[] args, String[] sig) throws MBeanException,
ReflectionException {
try {
if(log.isDebugEnabled()) {
log.debug("Invoke method called on " + name);
}
Class[] classes=new Class[sig.length];
for(int i=0;i < classes.length;i++) {
classes[i]=getClassForName(sig[i]);
}
Method method=this.obj.getClass().getMethod(name, classes);
return method.invoke(this.obj, args);
}
catch(Exception e) {
throw new MBeanException(e);
}
}
public static Class<?> getClassForName(String name) throws ClassNotFoundException {
try {
Class<?> c=Class.forName(name);
return c;
}
catch(ClassNotFoundException cnfe) {
//Could be a primative - let's check
for(int i=0;i < primitives.length;i++) {
if(name.equals(primitives[i].getName())) {
return primitives[i];
}
}
}
throw new ClassNotFoundException("Class " + name + " cannot be found");
}
private Attribute getNamedAttribute(String name) {
try {
if(name.endsWith("()")) {
Method method=this.obj.getClass().getMethod(name.substring(0, name.length() - 2),
new Class[] {});
return new Attribute(name, method.invoke(this.obj, new Object[] {}));
}
else {
if(name.equals(ResourceDMBean.MBEAN_DESCRITION)) {
return new Attribute(ResourceDMBean.MBEAN_DESCRITION, this.description);
}
else {
Field field=getFieldInHierarchy(obj.getClass(), name);
if(field != null) {
if(!field.isAccessible()) {
field.setAccessible(true);
}
return new Attribute(name, field.get(this.obj));
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
private boolean setNamedAttribute(Attribute attribute) {
try {
Field field=getFieldInHierarchy(obj.getClass(), attribute.getName());
if(field != null) {
if(!field.isAccessible()) {
field.setAccessible(true);
}
field.set(this.obj, attribute.getValue());
return true;
}
return false;
}
catch(Exception e) {
e.printStackTrace();
return false;
}
}
private Field getFieldInHierarchy(Class<?> clazz, String name) {
try {
return clazz.getDeclaredField(name);
}
catch(SecurityException e) {
return null;
}
catch(NoSuchFieldException e) {
Class<?> superClazz=clazz.getSuperclass();
if(superClazz != null) {
return getFieldInHierarchy(superClazz, name);
}
else {
return null;
}
}
}
}
|
package org.jgroups.jmx;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.DynamicMBean;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.ReflectionException;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.ManagedOperation;
import org.jgroups.annotations.Property;
import org.jgroups.util.Util;
/**
*
* A DynamicMBean wrapping an annotated object instance.
*
* @author Chris Mills
* @author Vladimir Blagojevic
* @version $Id: ResourceDMBean.java,v 1.34 2010/09/09 10:39:07 belaban Exp $
* @see ManagedAttribute
* @see ManagedOperation
* @see MBean
*
*/
public class ResourceDMBean implements DynamicMBean {
private static final Class<?>[] primitives= { int.class,
byte.class,
short.class,
long.class,
float.class,
double.class,
boolean.class,
char.class };
private static final String MBEAN_DESCRITION="Dynamic MBean Description";
private final Log log=LogFactory.getLog(ResourceDMBean.class);
private final Object obj;
private String description="";
private final MBeanAttributeInfo[] attrInfo;
private final MBeanOperationInfo[] opInfo;
private final HashMap<String,AttributeEntry> atts=new HashMap<String,AttributeEntry>();
private final List<MBeanOperationInfo> ops=new ArrayList<MBeanOperationInfo>();
public ResourceDMBean(Object instance) {
if(instance == null)
throw new NullPointerException("Cannot make an MBean wrapper for null instance");
this.obj=instance;
findDescription();
findFields();
findMethods();
attrInfo=new MBeanAttributeInfo[atts.size()];
int i=0;
MBeanAttributeInfo info=null;
for(AttributeEntry entry:atts.values()) {
info=entry.getInfo();
attrInfo[i++]=info;
}
opInfo=new MBeanOperationInfo[ops.size()];
ops.toArray(opInfo);
}
Object getObject() {
return obj;
}
private void findDescription() {
MBean mbean=getObject().getClass().getAnnotation(MBean.class);
if(mbean != null && mbean.description() != null && mbean.description().trim().length() > 0) {
description=mbean.description();
MBeanAttributeInfo info=new MBeanAttributeInfo(ResourceDMBean.MBEAN_DESCRITION,
"java.lang.String",
"MBean description",
true,
false,
false);
try {
atts.put(ResourceDMBean.MBEAN_DESCRITION,
new FieldAttributeEntry(info,getClass().getDeclaredField("description")));
}
catch(NoSuchFieldException e) {
//this should not happen unless somebody removes description field
log.warn("Could not reflect field description of this class. Was it removed?");
}
}
}
public synchronized MBeanInfo getMBeanInfo() {
return new MBeanInfo(getObject().getClass().getCanonicalName(),
description,
attrInfo,
null,
opInfo,
null);
}
public synchronized Object getAttribute(String name) {
if(name == null || name.length() == 0)
throw new NullPointerException("Invalid attribute requested " + name);
Attribute attr=getNamedAttribute(name);
return attr.getValue();
}
public synchronized void setAttribute(Attribute attribute) {
if(attribute == null || attribute.getName() == null)
throw new NullPointerException("Invalid attribute requested " + attribute);
setNamedAttribute(attribute);
}
public synchronized AttributeList getAttributes(String[] names) {
AttributeList al=new AttributeList();
for(String name:names) {
Attribute attr=getNamedAttribute(name);
if(attr != null) {
al.add(attr);
}
else {
log.warn("Did not find attribute " + name);
}
}
return al;
}
public synchronized AttributeList setAttributes(AttributeList list) {
AttributeList results=new AttributeList();
for(int i=0;i < list.size();i++) {
Attribute attr=(Attribute)list.get(i);
if(setNamedAttribute(attr)) {
results.add(attr);
}
else {
if(log.isWarnEnabled()) {
log.warn("Failed to update attribute name " + attr.getName() + " with value " + attr.getValue());
}
}
}
return results;
}
public Object invoke(String name, Object[] args, String[] sig) throws MBeanException,
ReflectionException {
try {
Class<?>[] classes=new Class[sig.length];
for(int i=0;i < classes.length;i++) {
classes[i]=getClassForName(sig[i]);
}
Method method=getObject().getClass().getMethod(name, classes);
return method.invoke(getObject(), args);
}
catch(Exception e) {
throw new MBeanException(e);
}
}
public static Class<?> getClassForName(String name) throws ClassNotFoundException {
try {
return Class.forName(name);
}
catch(ClassNotFoundException cnfe) {
//Could be a primitive - let's check
for(int i=0;i < primitives.length;i++) {
if(name.equals(primitives[i].getName())) {
return primitives[i];
}
}
}
throw new ClassNotFoundException("Class " + name + " cannot be found");
}
private void findMethods() {
//find all methods but don't include methods from Object class
List<Method> methods = new ArrayList<Method>(Arrays.asList(getObject().getClass().getMethods()));
List<Method> objectMethods = new ArrayList<Method>(Arrays.asList(Object.class.getMethods()));
methods.removeAll(objectMethods);
for(Method method:methods) {
//does method have @ManagedAttribute annotation?
if(method.isAnnotationPresent(ManagedAttribute.class) || method.isAnnotationPresent(Property.class)) {
exposeManagedAttribute(method);
}
//or @ManagedOperation
else if (method.isAnnotationPresent(ManagedOperation.class) || isMBeanAnnotationPresentWithExposeAll()){
exposeManagedOperation(method);
}
}
}
/** find all methods but don't include methods from Object class */
/*private void findMethods() {
for(Class<?> clazz=getObject().getClass();clazz != null; clazz=clazz.getSuperclass()) {
if(clazz.equals(Object.class))
break;
Method[] methods=clazz.getDeclaredMethods();
for(Method method: methods) {
//does method have @ManagedAttribute annotation?
if(method.isAnnotationPresent(ManagedAttribute.class) || method.isAnnotationPresent(Property.class)) {
exposeManagedAttribute(method);
}
//or @ManagedOperation
else if (method.isAnnotationPresent(ManagedOperation.class) || isMBeanAnnotationPresentWithExposeAll()){
exposeManagedOperation(method);
}
}
}
}*/
private void exposeManagedOperation(Method method) {
ManagedOperation op=method.getAnnotation(ManagedOperation.class);
String attName=method.getName();
if(isSetMethod(method) || isGetMethod(method)) {
attName=attName.substring(3);
}
else if(isIsMethod(method)) {
attName=attName.substring(2);
}
//expose unless we already exposed matching attribute field
boolean isAlreadyExposed=atts.containsKey(attName);
if(!isAlreadyExposed) {
ops.add(new MBeanOperationInfo(op != null? op.description() : "", method));
}
}
private void exposeManagedAttribute(Method method){
String methodName=method.getName();
if(!methodName.startsWith("get") && !methodName.startsWith("set") && !methodName.startsWith("is")) {
if(log.isWarnEnabled())
log.warn("method name " + methodName + " doesn't start with \"get\", \"set\", or \"is\""
+ ", but is annotated with @ManagedAttribute: will be ignored");
return;
}
ManagedAttribute attr = method.getAnnotation(ManagedAttribute.class);
Property prop=method.getAnnotation(Property.class);
boolean expose_prop=prop != null && prop.exposeAsManagedAttribute();
boolean expose=attr != null || expose_prop;
if(!expose)
return;
// Is name field of @ManagedAttributed used?
String attributeName=attr != null? attr.name() : null;
if(attributeName != null && attributeName.trim().length() > 0)
attributeName=attributeName.trim();
else
attributeName=null;
String descr=attr != null ? attr.description() : prop != null? prop.description() : null;
boolean writeAttribute=false;
MBeanAttributeInfo info=null;
if(isSetMethod(method)) { // setter
attributeName=(attributeName==null)?methodName.substring(3):attributeName;
info=new MBeanAttributeInfo(attributeName,
method.getParameterTypes()[0].getCanonicalName(),
descr,
true,
true,
false);
writeAttribute=true;
}
else { // getter
if(method.getParameterTypes().length == 0 && method.getReturnType() != java.lang.Void.TYPE) {
boolean hasSetter=atts.containsKey(attributeName);
//we found is method
if(methodName.startsWith("is")) {
attributeName=(attributeName==null)?methodName.substring(2):attributeName;
info=new MBeanAttributeInfo(attributeName,
method.getReturnType().getCanonicalName(),
descr,
true,
hasSetter,
true);
}
else {
// this has to be get
attributeName=(attributeName==null)?methodName.substring(3):attributeName;
info=new MBeanAttributeInfo(attributeName,
method.getReturnType().getCanonicalName(),
descr,
true,
hasSetter,
false);
}
}
else {
if(log.isWarnEnabled()) {
log.warn("Method " + method.getName() + " must have a valid return type and zero parameters");
}
//silently skip this method
return;
}
}
AttributeEntry ae=atts.get(attributeName);
//is it a read method?
if(!writeAttribute) {
//we already have annotated field as read
if(ae instanceof FieldAttributeEntry && ae.getInfo().isReadable()) {
log.warn("not adding annotated method " + method + " since we already have read attribute");
}
//we already have annotated set method
else if(ae instanceof MethodAttributeEntry) {
MethodAttributeEntry mae=(MethodAttributeEntry)ae;
if(mae.hasSetMethod()) {
atts.put(attributeName,
new MethodAttributeEntry(mae.getInfo(), mae.getSetMethod(), method));
}
} //we don't have such entry
else {
atts.put(attributeName, new MethodAttributeEntry(info, findSetter(obj.getClass(), attributeName), method));
}
} //is it a set method?
else {
if(ae instanceof FieldAttributeEntry) {
//we already have annotated field as write
if(ae.getInfo().isWritable()) {
log.warn("Not adding annotated method " + methodName + " since we already have writable attribute");
}
else {
//we already have annotated field as read
//lets make the field writable
Field f = ((FieldAttributeEntry)ae).getField();
MBeanAttributeInfo i=new MBeanAttributeInfo(ae.getInfo().getName(),
f.getType().getCanonicalName(),
descr,
true,
!Modifier.isFinal(f.getModifiers()),
false);
atts.put(attributeName,new FieldAttributeEntry(i,f));
}
}
//we already have annotated getOrIs method
else if(ae instanceof MethodAttributeEntry) {
MethodAttributeEntry mae=(MethodAttributeEntry)ae;
if(mae.hasIsOrGetMethod()) {
atts.put(attributeName,
new MethodAttributeEntry(info,
method,
mae.getIsOrGetMethod()));
}
} // we don't have such entry
else {
atts.put(attributeName, new MethodAttributeEntry(info, method, findGetter(obj.getClass(), attributeName)));
}
}
}
private static boolean isSetMethod(Method method) {
return(method.getName().startsWith("set") &&
method.getParameterTypes().length == 1 &&
method.getReturnType() == java.lang.Void.TYPE);
}
private static boolean isGetMethod(Method method) {
return(method.getParameterTypes().length == 0 &&
method.getReturnType() != java.lang.Void.TYPE &&
method.getName().startsWith("get"));
}
private static boolean isIsMethod(Method method) {
return(method.getParameterTypes().length == 0 &&
(method.getReturnType() == boolean.class || method.getReturnType() == Boolean.class) &&
method.getName().startsWith("is"));
}
public static Method findGetter(Class clazz, String name) {
try {
return clazz.getMethod("get" + name);
}
catch(NoSuchMethodException e) {
}
try {
return clazz.getMethod("is" + name);
}
catch(NoSuchMethodException ex) {
}
return null;
}
public static Method findSetter(Class clazz, String name) {
try {
return clazz.getMethod("set" + name);
}
catch(NoSuchMethodException e) {
}
return null;
}
private void findFields() {
//traverse class hierarchy and find all annotated fields
for(Class<?> clazz=getObject().getClass();clazz != null; clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(Field field:fields) {
ManagedAttribute attr=field.getAnnotation(ManagedAttribute.class);
Property prop=field.getAnnotation(Property.class);
boolean expose_prop=prop != null && prop.exposeAsManagedAttribute();
boolean expose=attr != null || expose_prop;
if(expose) {
String fieldName = Util.attributeNameToMethodName(field.getName());
String descr=attr != null? attr.description() : prop.description();
boolean writable=attr != null? attr.writable() : prop.writable();
MBeanAttributeInfo info=new MBeanAttributeInfo(fieldName,
field.getType().getCanonicalName(),
descr,
true,
!Modifier.isFinal(field.getModifiers()) && writable,
false);
atts.put(fieldName, new FieldAttributeEntry(info, field));
}
}
}
}
private Attribute getNamedAttribute(String name) {
Attribute result=null;
if(name.equals(ResourceDMBean.MBEAN_DESCRITION)) {
result=new Attribute(ResourceDMBean.MBEAN_DESCRITION, this.description);
}
else {
AttributeEntry entry=atts.get(name);
if(entry != null) {
try {
result=new Attribute(name, entry.invoke(null));
}
catch(Exception e) {
log.warn("Exception while reading value of attribute " + name, e);
}
}
else {
log.warn("Did not find queried attribute with name " + name);
}
}
return result;
}
private boolean setNamedAttribute(Attribute attribute) {
boolean result=false;
AttributeEntry entry=atts.get(attribute.getName());
if(entry != null) {
try {
entry.invoke(attribute);
result=true;
}
catch(Exception e) {
log.warn("Exception while writing value for attribute " + attribute.getName(), e);
}
}
else {
log.warn("Could not invoke set on attribute " + attribute.getName()
+ " with value "
+ attribute.getValue());
}
return result;
}
private boolean isMBeanAnnotationPresentWithExposeAll(){
Class<? extends Object> c=getObject().getClass();
return c.isAnnotationPresent(MBean.class) && c.getAnnotation(MBean.class).exposeAll();
}
private class MethodAttributeEntry implements AttributeEntry {
final MBeanAttributeInfo info;
final Method isOrGetmethod;
final Method setMethod;
public MethodAttributeEntry(final MBeanAttributeInfo info,
final Method setMethod,
final Method isOrGetMethod) {
super();
this.info=info;
this.setMethod=setMethod;
this.isOrGetmethod=isOrGetMethod;
}
public Object invoke(Attribute a) throws Exception {
if(a == null && isOrGetmethod != null)
return isOrGetmethod.invoke(getObject());
else if(a != null && setMethod != null)
return setMethod.invoke(getObject(), a.getValue());
else
return null;
}
public MBeanAttributeInfo getInfo() {
return info;
}
public boolean hasIsOrGetMethod() {
return isOrGetmethod != null;
}
public boolean hasSetMethod() {
return setMethod != null;
}
public Method getIsOrGetMethod() {
return isOrGetmethod;
}
public Method getSetMethod() {
return setMethod;
}
}
private class FieldAttributeEntry implements AttributeEntry {
private final MBeanAttributeInfo info;
private final Field field;
public FieldAttributeEntry(final MBeanAttributeInfo info,final Field field) {
super();
this.info=info;
this.field=field;
if(!field.isAccessible()) {
field.setAccessible(true);
}
}
public Field getField(){
return field;
}
public Object invoke(Attribute a) throws Exception {
if(a == null) {
return field.get(getObject());
}
else {
field.set(getObject(), a.getValue());
return null;
}
}
public MBeanAttributeInfo getInfo() {
return info;
}
}
private interface AttributeEntry {
public Object invoke(Attribute a) throws Exception;
public MBeanAttributeInfo getInfo();
}
}
|
package foodtruck.schedule;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngineManager;
import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormatter;
import foodtruck.model.Location;
import foodtruck.model.StaticConfig;
import foodtruck.schedule.custom.AmanecerTacosMatcher;
import foodtruck.schedule.custom.BeaverMatcher;
import foodtruck.schedule.custom.BobChaMatcher;
import foodtruck.schedule.custom.CajunConMatcher;
import foodtruck.schedule.custom.LaJefaMatcher;
import foodtruck.schedule.custom.PierogiWagonMatcher;
import foodtruck.schedule.custom.RoostMatcher;
import foodtruck.util.MilitaryTimeOnlyFormatter;
/**
* @author aviolette@gmail.com
* @since Jul 19, 2011
*/
public class ScheduleModule extends AbstractModule {
private static final Logger log = Logger.getLogger(ScheduleModule.class.getName());
@Override
protected void configure() {
bind(AddressExtractor.class).to(JavascriptAddressExtractor.class);
bind(ScheduleStrategy.class).to(GoogleCalendarV3Consumer.class);
bind(ScheduleCacher.class).to(MemcacheScheduleCacher.class);
Multibinder<SpecialMatcher> binder = Multibinder.newSetBinder(binder(), SpecialMatcher.class);
binder.addBinding().to(BeaverMatcher.class);
binder.addBinding().to(LaJefaMatcher.class);
binder.addBinding().to(RoostMatcher.class);
binder.addBinding().to(BobChaMatcher.class);
binder.addBinding().to(PierogiWagonMatcher.class);
binder.addBinding().to(AmanecerTacosMatcher.class);
binder.addBinding().to(CajunConMatcher.class);
}
@Provides @Singleton
public ImmutableList<Spot> provideCommonSpots() {
return ImmutableList.of(
new Spot("600w", "600 West Chicago Avenue, Chicago, IL"),
new Spot("wabash/vanburen", "Wabash and Van Buren, Chicago, IL"),
new Spot("wacker/adams", "Wacker and Adams, Chicago, IL"),
new Spot("clark/adams", "Clark and Adams, Chicago, IL"),
new Spot("harrison/michigan", "Michigan and Harrison, Chicago, IL"),
new Spot("lasalle/adams", "Lasalle and Adams, Chicago, IL"),
new Spot("clark/monroe", "Clark and Monroe, Chicago, IL"),
new Spot("wabash/jackson", "Wabash and Jackson, Chicago, IL"),
new Spot("michigan/monroe", "Michigan and Monroe, Chicago, IL"),
new Spot("uchicago", "University of Chicago"),
new Spot("uofc", "University of Chicago"),
new Spot("58th/ellis", "University of Chicago"));
}
@Provides @Singleton
public MemcacheService provideMemcacheService() {
MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
return syncCache;
}
@Provides
public ScriptEngineManager provideScriptEngineManager() {
return new ScriptEngineManager();
}
@Provides @Named("center")
public Location providesMapCenter(StaticConfig config) {
return config.getCenter();
}
@Provides @DefaultStartTime @Singleton
public LocalTime provideDefaultStartTime(@MilitaryTimeOnlyFormatter DateTimeFormatter formatter) {
try {
LocalTime localTime = formatter.parseLocalTime(System.getProperty("foodtrucklocator.lunchtime", "11:30"));
log.info("Lunch time is at: " + localTime);
return localTime;
} catch (Exception e) {
log.severe(e.getMessage());
}
return new LocalTime(11, 30);
}
}
|
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Global;
import org.jgroups.PhysicalAddress;
import org.jgroups.annotations.LocalAddress;
import org.jgroups.annotations.Property;
import org.jgroups.blocks.cs.Receiver;
import org.jgroups.conf.AttributeType;
import java.net.InetAddress;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* Shared base class for TCP protocols
* @author Scott Marlow
* @author Bela Ban
*/
public abstract class BasicTCP extends TP implements Receiver {
@Property(description="Reaper interval in msec. Default is 0 (no reaping)",type=AttributeType.TIME)
protected long reaper_interval; // time in msecs between connection reaps
@Property(description="Max time connection can be idle before being reaped (in ms)",type=AttributeType.TIME)
protected long conn_expire_time; // max time a conn can be idle before being reaped
@Property(description="Receiver buffer size in bytes",type=AttributeType.BYTES)
protected int recv_buf_size;
@Property(description="Send buffer size in bytes",type=AttributeType.BYTES)
protected int send_buf_size;
@Property(description="Max time allowed for a socket creation in connection table",type=AttributeType.TIME)
protected int sock_conn_timeout=2000; // max time in millis for a socket creation in connection table
@Property(description="Max time to block on reading of peer address",type=AttributeType.TIME)
protected int peer_addr_read_timeout=1000; // max time to block on reading of peer address
@Property(description="The max number of bytes a message can have. If greater, an exception will be " +
"thrown. 0 disables this", type=AttributeType.BYTES)
protected int max_length;
@Property(description="Should TCP no delay flag be turned on")
protected boolean tcp_nodelay=true; // should be true by default as message bundling makes delaying packets moot
@Property(description="SO_LINGER in seconds. Default of -1 disables it")
protected int linger=-1; // SO_LINGER (number of seconds, -1 disables it)
// protected boolean reuse_addr;
@LocalAddress
@Property(name="client_bind_addr",
description="The address of a local network interface which should be used by client sockets to bind to. " +
"The following special values are also recognized: GLOBAL, SITE_LOCAL, LINK_LOCAL and NON_LOOPBACK",
systemProperty={Global.TCP_CLIENT_BIND_ADDR},writable=false)
protected InetAddress client_bind_addr;
@Property(description="The local port a client socket should bind to. If 0, an ephemeral port will be picked.")
protected int client_bind_port;
@Property(description="If true, client sockets will not explicitly bind to bind_addr but will defer to the native socket")
protected boolean defer_client_bind_addr;
@Property(description="Log a stack trace when a connection is closed")
protected boolean log_details=true;
protected BasicTCP() {
super();
}
public boolean supportsMulticasting() {return false;}
public long getReaperInterval() {return reaper_interval;}
public BasicTCP setReaperInterval(long interval) {this.reaper_interval=interval; return this;}
public BasicTCP reaperInterval(long interval) {this.reaper_interval=interval; return this;}
public long getConnExpireTime() {return conn_expire_time;}
public BasicTCP setConnExpireTime(long time) {this.conn_expire_time=time; return this;}
public int getRecvBufSize() {return recv_buf_size;}
public BasicTCP setRecvBufSize(int r) {this.recv_buf_size=r; return this;}
public int getSendBufSize() {return send_buf_size;}
public BasicTCP setSendBufSize(int s) {this.send_buf_size=s; return this;}
public int getSockConnTimeout() {return sock_conn_timeout;}
public BasicTCP setSockConnTimeout(int s) {this.sock_conn_timeout=s; return this;}
public int getMaxLength() {return max_length;}
public BasicTCP setMaxLength(int len) {max_length=len; return this;}
public int getPeerAddrReadTimeout() {return peer_addr_read_timeout;}
public BasicTCP setPeerAddrReadTimeout(int p) {this.peer_addr_read_timeout=p; return this;}
public boolean tcpNodelay() {return tcp_nodelay;}
public BasicTCP tcpNodelay(boolean t) {this.tcp_nodelay=t; return this;}
public int getLinger() {return linger;}
public BasicTCP setLinger(int l) {this.linger=l; return this;}
public InetAddress getClientBindAddr() {return client_bind_addr;}
public BasicTCP setClientBindAddr(InetAddress c) {this.client_bind_addr=c; return this;}
public int getClientBindPort() {return client_bind_port;}
public BasicTCP setClientBindPort(int c) {this.client_bind_port=c; return this;}
public boolean deferClientBindAddr() {return defer_client_bind_addr;}
public BasicTCP deferClientBindAddr(boolean d) {this.defer_client_bind_addr=d; return this;}
public boolean logDetails() {return log_details;}
public BasicTCP logDetails(boolean l) {log_details=l; return this;}
public void init() throws Exception {
super.init();
if(bind_port <= 0) {
Discovery discovery_prot=stack.findProtocol(Discovery.class);
if(discovery_prot != null && !discovery_prot.isDynamic())
throw new IllegalArgumentException("bind_port cannot be set to " + bind_port +
", as no dynamic discovery protocol (e.g. MPING or TCPGOSSIP) has been detected.");
}
if(reaper_interval > 0 || conn_expire_time > 0) {
if(conn_expire_time == 0 && reaper_interval > 0) {
log.warn("reaper interval (%d) set, but not conn_expire_time, disabling reaping", reaper_interval);
reaper_interval=0;
}
else if(conn_expire_time > 0 && reaper_interval == 0) {
reaper_interval=conn_expire_time / 2;
log.warn("conn_expire_time (%d) is set but reaper_interval is 0; setting it to %d", conn_expire_time, reaper_interval);
}
}
}
public void sendUnicast(PhysicalAddress dest, byte[] data, int offset, int length) throws Exception {
send(dest, data, offset, length);
}
public String getInfo() {
return String.format("connections: %s\n", printConnections());
}
public abstract String printConnections();
public abstract void send(Address dest, byte[] data, int offset, int length) throws Exception;
public abstract void retainAll(Collection<Address> members);
@Override
public Object down(Event evt) {
Object ret=super.down(evt);
if(evt.getType() == Event.VIEW_CHANGE) {
Set<Address> physical_mbrs=new HashSet<>();
for(Address addr: members) {
PhysicalAddress physical_addr=getPhysicalAddressFromCache(addr);
if(physical_addr != null)
physical_mbrs.add(physical_addr);
}
retainAll(physical_mbrs); // remove all connections which are not members
}
return ret;
}
}
|
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.Property;
import org.jgroups.stack.Protocol;
import org.jgroups.util.BoundedList;
import org.jgroups.util.Util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Set;
/**
* Shared base class for tcpip protocols
* @author Scott Marlow
*/
public abstract class BasicTCP extends TP {
@Property(description="Should unicast messages to suspected members be dropped. Default is false")
boolean skip_suspected_members=true;
@Property(description="If cannot send a message to P (on an exception), should SUSPECT message be raised. Default is false")
boolean suspect_on_send_failure=false;
@ManagedAttribute(description="Reaper interval", writable=true)
@Property(description="Reaper interval in msec. Default is 0 (no reaping)")
protected long reaper_interval=0; // time in msecs between connection reaps
@ManagedAttribute(description="Connection expiration time", writable=true)
@Property(description="Max time connection can be idle before being reaped")
protected long conn_expire_time=0; // max time a conn can be idle before being reaped
@Property(description="Should separate send queues be used for each connection. Default is true")
boolean use_send_queues=true;
@Property(description="Max number of messages in a send queue. Default is 10000 messages")
int send_queue_size=10000;
@Property(description="Receiver buffer size in bytes. Default is 150000 bytes")
int recv_buf_size=150000;
@Property(description="Send buffer size in bytes. Default is 150000 bytes")
int send_buf_size=150000;
@Property(description="Max time allowed for a socket creation in ConnectionTable. Default is 2000 msec")
int sock_conn_timeout=2000; // max time in millis for a socket creation in ConnectionTable
@Property(description="Max time to block on reading of peer address. Default is 1000 msec")
int peer_addr_read_timeout=1000; // max time to block on reading of peer address
@Property(description="Should TCP no delay flag be turned on. Default is false")
boolean tcp_nodelay=false;
@Property(description="SO_LINGER in msec. Default of -1 disables it")
int linger=-1; // SO_LINGER (number of ms, -1 disables it)
/**
* List the maintains the currently suspected members. This is used so we
* don't send too many SUSPECT events up the stack (one per message !)
*/
final BoundedList<Address> suspected_mbrs=new BoundedList<Address>(20);
protected InetAddress external_addr=null; // the IP address which is broadcast to other group members
protected BasicTCP() {
super();
}
public long getReaperInterval() {return reaper_interval;}
public void setReaperInterval(long reaper_interval) {this.reaper_interval=reaper_interval;}
public long getConnExpireTime() {return conn_expire_time;}
public void setConnExpireTime(long conn_expire_time) {this.conn_expire_time=conn_expire_time;}
@Property(name="external_addr", description="Use \"external_addr\" if you have hosts on different networks, behind " +
"firewalls. On each firewall, set up a port forwarding rule (sometimes called \"virtual server\") to " +
"the local IP (e.g. 192.168.1.100) of the host then on each host, set \"external_addr\" TCP transport " +
"parameter to the external (public IP) address of the firewall. ")
public void setExternalAddress(String addr) throws UnknownHostException {
external_addr=InetAddress.getByName(addr);
}
public void init() throws Exception {
super.init();
Util.checkBufferSize(getName() + ".recv_buf_size", recv_buf_size);
Util.checkBufferSize(getName() + ".send_buf_size", send_buf_size);
if(!isSingleton() && bind_port <= 0) {
Protocol dynamic_discovery_prot=stack.findProtocol("MPING");
if(dynamic_discovery_prot == null)
dynamic_discovery_prot=stack.findProtocol("TCPGOSSIP");
if(dynamic_discovery_prot != null) {
if(log.isDebugEnabled())
log.debug("dynamic discovery is present (" + dynamic_discovery_prot + "), so start_port=" + bind_port + " is okay");
}
else {
throw new IllegalArgumentException("start_port cannot be set to " + bind_port +
", as no dynamic discovery protocol (e.g. MPING or TCPGOSSIP) has been detected.");
}
}
}
public void sendToAllMembers(byte[] data, int offset, int length) throws Exception {
Set<Address> mbrs;
synchronized(members) {
mbrs=(Set<Address>)members.clone();
}
for(Address dest: mbrs) {
sendToSingleMember(dest, data, offset, length);
}
}
public void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception {
if(log.isTraceEnabled()) log.trace("dest=" + dest + " (" + length + " bytes)");
if(skip_suspected_members) {
if(suspected_mbrs.contains(dest)) {
if(log.isTraceEnabled())
log.trace("will not send unicast message to " + dest + " as it is currently suspected");
return;
}
}
try {
send(dest, data, offset, length);
}
catch(Exception e) {
if(log.isTraceEnabled())
log.trace("failure sending message to " + dest, e);
if(suspect_on_send_failure && members.contains(dest)) {
if(!suspected_mbrs.contains(dest)) {
suspected_mbrs.add(dest);
up_prot.up(new Event(Event.SUSPECT, dest));
}
}
}
}
public String getInfo() {
StringBuilder sb=new StringBuilder();
sb.append("connections: ").append(printConnections()).append("\n");
return sb.toString();
}
public void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast) {
if(multicast)
msg.setDest(null);
else
msg.setDest(dest);
}
public void postUnmarshallingList(Message msg, Address dest, boolean multicast) {
postUnmarshalling(msg, dest, null, multicast);
}
public abstract String printConnections();
public abstract void send(Address dest, byte[] data, int offset, int length) throws Exception;
public abstract void retainAll(Collection<Address> members);
/** ConnectionTable.Receiver interface */
public void receive(Address sender, byte[] data, int offset, int length) {
receive(local_addr, sender, data, offset, length);
}
protected Object handleDownEvent(Event evt) {
Object ret=super.handleDownEvent(evt);
if(evt.getType() == Event.VIEW_CHANGE) {
suspected_mbrs.clear();
retainAll(members); // remove all connections from the ConnectionTable which are not members
}
else if(evt.getType() == Event.UNSUSPECT) {
Address suspected_mbr=(Address)evt.getArg();
suspected_mbrs.remove(suspected_mbr);
}
return ret;
}
}
|
package main.java.gui.application;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.rmi.RemoteException;
import main.java.data.Data;
import main.java.game.ExceptionForbiddenAction;
import main.java.game.ExceptionGameHasNotStarted;
import main.java.game.ExceptionNoPreviousGameToReach;
import main.java.game.ExceptionNotEnoughTilesInDeck;
import main.java.game.ExceptionNotYourTurn;
import main.java.game.ExceptionTwoManyTilesToDraw;
import main.java.gui.components.Button;
import main.java.gui.components.Panel;
import main.java.player.PlayerIHM;
@SuppressWarnings("serial")
public class BottomPlayerPanel extends Panel {
// Properties
BottomPlayerCardsPanel cardsPanel;
Panel buttonsPanel;
boolean canBeginTrip = false;
String playerName;
int numberOfCardPlayed;
PlayerIHM player;
Button validateButton;
Button beginTripButton;
Button resetButton;
// Constructors
public BottomPlayerPanel() {
setupBottomPanel();
setupBottomPlayerCardsPanel();
setupBottomPlayerButtonsPanel();
}
protected void setupBottomPanel() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(0, 150));
//this.setBackground(Color.WHITE);
}
protected void setupBottomPlayerCardsPanel() {
this.cardsPanel = new BottomPlayerCardsPanel();
this.add(cardsPanel, BorderLayout.CENTER);
}
protected void setupBottomPlayerButtonsPanel() {
this.buttonsPanel = new Panel();
this.buttonsPanel.setLayout(null);
this.buttonsPanel.setBackground(Color.WHITE);
this.buttonsPanel.setPreferredSize(new Dimension(175, 150));
beginTripButton = new Button("Commencer le voyage", null);
validateButton = new Button("Valider", null);
resetButton = new Button("Annuler le dernier coup", null);
beginTripButton.setEnabled(false);
//validateButton.setEnabled(false);
resetButton.setEnabled(false);
beginTripButton.addAction(this, "beginTrip");
validateButton.addAction(this, "validate");
resetButton.addAction(this, "reset");
beginTripButton.setBounds(0, 15, 165, 35);
validateButton.setBounds(0, 55, 165, 35);
resetButton.setBounds(0, 95, 165, 35);
buttonsPanel.add(beginTripButton);
buttonsPanel.add(validateButton);
buttonsPanel.add(resetButton);
this.add(buttonsPanel, BorderLayout.EAST);
}
public void validate() {
System.out.println("validate");
try {
//StreetCar.player.drawTile(2);
StreetCar.player.drawTile(StreetCar.player.getGameData().getPlayerRemainingTilesToDraw(playerName));
} catch (RemoteException e1) {
e1.printStackTrace();
} catch (ExceptionGameHasNotStarted e1) {
e1.printStackTrace();
} catch (ExceptionNotYourTurn e1) {
e1.printStackTrace();
} catch (ExceptionNotEnoughTilesInDeck e1) {
e1.printStackTrace();
} catch (ExceptionTwoManyTilesToDraw e1) {
e1.printStackTrace();
} catch (ExceptionForbiddenAction e1) {
e1.printStackTrace();
}
try {
StreetCar.player.validate();
} catch (RemoteException e) {
e.printStackTrace();
} catch (ExceptionGameHasNotStarted e) {
e.printStackTrace();
} catch (ExceptionNotYourTurn e) {
e.printStackTrace();
} catch (ExceptionForbiddenAction e) {
e.printStackTrace();
}
}
public void reset() {
try {
player.rollBack();
} catch (RemoteException e) {
e.printStackTrace();
} catch (ExceptionForbiddenAction e) {
e.printStackTrace();
} catch (ExceptionNotYourTurn e) {
e.printStackTrace();
} catch (ExceptionNoPreviousGameToReach e) {
e.printStackTrace();
}
}
// TODO delete this?
public void beginTrip() {
System.out.println("REQUESTING TO BEGIN TRIP");
if(canBeginTrip)
{
Point p = player.getGameData().getPlayerTerminusPosition(playerName)[0];
}
else System.out.println("CANT BEGIN TRIP");
}
protected void checkBeginTripButton() {
/* TODO
if (!canBeginTrip) {
beginTripButton.setEnabled(false);
} else {
beginTripButton.setEnabled(true);
}
*/
beginTripButton.setEnabled(true);
}
protected void checkValidateButton(Data data) {
Boolean enabled;
try {
enabled = !data.hasRemainingAction(this.playerName);
} catch (Exception e) {
enabled = false;
}
validateButton.setEnabled(enabled);
}
protected void checkResetButton(Data data) {
/*numberOfCardPlayed = 5 - data.getHandSize(playerName);
if (numberOfCardPlayed != 0) {
resetButton.setEnabled(true);
} else {
resetButton.setEnabled(false);
}*/
resetButton.setEnabled(!data.isStartOfTurn(playerName));
}
protected void paintComponent(Graphics g) {
/*super.paintComponent(g);
g.drawRect(20, 20, 50, 50); //avatar
g.drawRect(20, 80, 50, 50); //card1
g.drawRect(80, 80, 50, 50); //card2
g.drawRect(140, 80, 50, 50); //card3
g.drawRect(200, 80, 50, 50); //card4
g.drawRect(260, 80, 50, 50); //card5
g.drawRect(350, 80, 50, 50); //station1
g.drawRect(410, 80, 50, 50); //station2*/
}
public void refreshGame(PlayerIHM player, Data data) {
this.player = player;
player = StreetCar.player;
try {
playerName = player.getPlayerName();
canBeginTrip = data.isTrackCompleted(playerName);
checkBeginTripButton();
System.out.println("BEGIN TRIP BUTTON : " + canBeginTrip);
checkValidateButton(data);
checkResetButton(data);
if (data.isPlayerTurn(playerName)) {
cardsPanel.setBackground(new Color(0xC9ECEE));
buttonsPanel.setBackground(new Color(0xC9ECEE));
} else {
cardsPanel.setBackground(new Color(0xFFEDDE));
buttonsPanel.setBackground(new Color(0xFFEDDE));
}
cardsPanel.refreshGame(player, data);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
|
package org.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.ManagedOperation;
import org.jgroups.annotations.Property;
import org.jgroups.stack.Protocol;
import org.jgroups.util.*;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import java.util.stream.Stream;
/**
* Reliable unicast protocol using a combination of positive and negative acks. See docs/design/UNICAST3.txt for details.
* @author Bela Ban
* @since 3.3
*/
@MBean(description="Reliable unicast layer")
public class UNICAST3 extends Protocol implements AgeOutCache.Handler<Address> {
protected static final long DEFAULT_FIRST_SEQNO=Global.DEFAULT_FIRST_UNICAST_SEQNO;
@Property(description="Time (in milliseconds) after which an idle incoming or outgoing connection is closed. The " +
"connection will get re-established when used again. 0 disables connection reaping")
protected long conn_expiry_timeout=(long) 60000 * 2;
@Property(description="Time (in ms) until a connection marked to be closed will get removed. 0 disables this")
protected long conn_close_timeout=240_000; // 4 mins == TIME_WAIT timeout (= 2 * MSL)
@Property(description="Number of rows of the matrix in the retransmission table (only for experts)",writable=false)
protected int xmit_table_num_rows=100;
@Property(description="Number of elements of a row of the matrix in the retransmission table; " +
"gets rounded to the next power of 2 (only for experts). The capacity of the matrix is xmit_table_num_rows * xmit_table_msgs_per_row",writable=false)
protected int xmit_table_msgs_per_row=1024;
@Property(description="Resize factor of the matrix in the retransmission table (only for experts)",writable=false)
protected double xmit_table_resize_factor=1.2;
@Property(description="Number of milliseconds after which the matrix in the retransmission table " +
"is compacted (only for experts)",writable=false)
protected long xmit_table_max_compaction_time= (long) 10 * 60 * 1000;
// @Property(description="Max time (in ms) after which a connection to a non-member is closed")
protected long max_retransmit_time=60 * 1000L;
@Property(description="Interval (in milliseconds) at which messages in the send windows are resent")
protected long xmit_interval=500;
@Property(description="If true, trashes warnings about retransmission messages not found in the xmit_table (used for testing)")
protected boolean log_not_found_msgs=true;
@Property(description="Send an ack immediately when a batch of ack_threshold (or more) messages is received. " +
"Otherwise send delayed acks. If 1, ack single messages (similar to UNICAST)")
protected int ack_threshold=5;
@Property(description="Min time (in ms) to elapse for successive SEND_FIRST_SEQNO messages to be sent to the same sender")
protected long sync_min_interval=2000;
@Property(description="Max number of messages to ask for in a retransmit request. 0 disables this and uses " +
"the max bundle size in the transport")
protected int max_xmit_req_size;
protected long num_msgs_sent=0, num_msgs_received=0;
protected long num_acks_sent=0, num_acks_received=0, num_xmits=0;
@ManagedAttribute(description="Number of retransmit requests received")
protected final LongAdder xmit_reqs_received=new LongAdder();
@ManagedAttribute(description="Number of retransmit requests sent")
protected final LongAdder xmit_reqs_sent=new LongAdder();
@ManagedAttribute(description="Number of retransmit responses sent")
protected final LongAdder xmit_rsps_sent=new LongAdder();
protected final AverageMinMax avg_delivery_batch_size=new AverageMinMax();
@ManagedAttribute(description="True if sending a message can block at the transport level")
protected boolean sends_can_block=true;
@ManagedAttribute(description="tracing is enabled or disabled for the given log",writable=true)
protected boolean is_trace=log.isTraceEnabled();
protected final ConcurrentMap<Address, SenderEntry> send_table=Util.createConcurrentMap();
protected final ConcurrentMap<Address, ReceiverEntry> recv_table=Util.createConcurrentMap();
protected final ReentrantLock recv_table_lock=new ReentrantLock();
protected final Map<Address,Long> xmit_task_map=new HashMap<>();
/** RetransmitTask running every xmit_interval ms */
protected Future<?> xmit_task;
protected volatile List<Address> members=new ArrayList<>(11);
protected Address local_addr;
protected TimeScheduler timer; // used for retransmissions
protected volatile boolean running=false;
protected short last_conn_id;
protected AgeOutCache<Address> cache;
protected TimeService time_service; // for aging out of receiver and send entries
protected final AtomicInteger timestamper=new AtomicInteger(0); // timestamping of ACKs / SEND_FIRST-SEQNOs
/** Keep track of when a SEND_FIRST_SEQNO message was sent to a given sender */
protected ExpiryCache<Address> last_sync_sent=null;
protected static final Message DUMMY_OOB_MSG=new Message().setFlag(Message.Flag.OOB);
protected final Predicate<Message> drop_oob_and_dont_loopback_msgs_filter= msg ->
msg != null && msg != DUMMY_OOB_MSG
&& (!msg.isFlagSet(Message.Flag.OOB) || msg.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED))
&& !(msg.isTransientFlagSet(Message.TransientFlag.DONT_LOOPBACK) && local_addr != null && local_addr.equals(msg.src()));
protected static final Predicate<Message> dont_loopback_filter=
msg -> msg != null && msg.isTransientFlagSet(Message.TransientFlag.DONT_LOOPBACK);
protected static final BiConsumer<MessageBatch,Message> BATCH_ACCUMULATOR=MessageBatch::add;
@ManagedAttribute
public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";}
@ManagedAttribute(description="Returns the number of outgoing (send) connections")
public int getNumSendConnections() {
return send_table.size();
}
@ManagedAttribute(description="Returns the number of incoming (receive) connections")
public int getNumReceiveConnections() {
return recv_table.size();
}
@ManagedAttribute(description="Returns the total number of outgoing (send) and incoming (receive) connections")
public int getNumConnections() {
return getNumReceiveConnections() + getNumSendConnections();
}
@ManagedAttribute(description="Next seqno issued by the timestamper")
public int getTimestamper() {return timestamper.get();}
@ManagedAttribute(description="Average batch size of messages removed from the table and delivered to the application")
public String getAvgBatchDeliverySize() {
return avg_delivery_batch_size != null? avg_delivery_batch_size.toString() : "n/a";
}
public <T extends Protocol> T setLevel(String level) {
T retval= super.setLevel(level);
is_trace=log.isTraceEnabled();
return retval;
}
@ManagedOperation
public String printConnections() {
StringBuilder sb=new StringBuilder();
if(!send_table.isEmpty()) {
sb.append("\nsend connections:\n");
for(Map.Entry<Address,SenderEntry> entry: send_table.entrySet()) {
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
}
if(!recv_table.isEmpty()) {
sb.append("\nreceive connections:\n");
for(Map.Entry<Address,ReceiverEntry> entry: recv_table.entrySet()) {
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
}
return sb.toString();
}
@ManagedAttribute
public long getNumMessagesSent() {return num_msgs_sent;}
@ManagedAttribute
public long getNumMessagesReceived() {return num_msgs_received;}
@ManagedAttribute
public long getNumAcksSent() {return num_acks_sent;}
@ManagedAttribute
public long getNumAcksReceived() {return num_acks_received;}
@ManagedAttribute
public long getNumXmits() {return num_xmits;}
public long getMaxRetransmitTime() {return max_retransmit_time;}
@Property(description="Max number of milliseconds we try to retransmit a message to any given member. After that, " +
"the connection is removed. Any new connection to that member will start with seqno #1 again. 0 disables this")
public void setMaxRetransmitTime(long max_retransmit_time) {
this.max_retransmit_time=max_retransmit_time;
if(cache != null && max_retransmit_time > 0)
cache.setTimeout(max_retransmit_time);
}
@ManagedAttribute(description="Is the retransmit task running")
public boolean isXmitTaskRunning() {return xmit_task != null && !xmit_task.isDone();}
@ManagedAttribute
public int getAgeOutCacheSize() {
return cache != null? cache.size() : 0;
}
@ManagedOperation
public String printAgeOutCache() {
return cache != null? cache.toString() : "n/a";
}
public AgeOutCache<Address> getAgeOutCache() {
return cache;
}
/** Used for testing only */
public boolean hasSendConnectionTo(Address dest) {
Entry entry=send_table.get(dest);
return entry != null && entry.state() == State.OPEN;
}
/** The number of messages in all Entry.sent_msgs tables (haven't received an ACK yet) */
@ManagedAttribute
public int getNumUnackedMessages() {
return accumulate(Table::size, send_table.values());
}
@ManagedAttribute(description="Total number of undelivered messages in all receive windows")
public int getXmitTableUndeliveredMessages() {
return accumulate(Table::size, recv_table.values());
}
@ManagedAttribute(description="Total number of missing messages in all receive windows")
public int getXmitTableMissingMessages() {
return accumulate(Table::getNumMissing, recv_table.values());
}
@ManagedAttribute(description="Total number of deliverable messages in all receive windows")
public int getXmitTableDeliverableMessages() {
return accumulate(Table::getNumDeliverable, recv_table.values());
}
@ManagedAttribute(description="Number of compactions in all (receive and send) windows")
public int getXmitTableNumCompactions() {
return accumulate(Table::getNumCompactions, recv_table.values(), send_table.values());
}
@ManagedAttribute(description="Number of moves in all (receive and send) windows")
public int getXmitTableNumMoves() {
return accumulate(Table::getNumMoves, recv_table.values(), send_table.values());
}
@ManagedAttribute(description="Number of resizes in all (receive and send) windows")
public int getXmitTableNumResizes() {
return accumulate(Table::getNumResizes, recv_table.values(), send_table.values());
}
@ManagedAttribute(description="Number of purges in all (receive and send) windows")
public int getXmitTableNumPurges() {
return accumulate(Table::getNumPurges, recv_table.values(), send_table.values());
}
@ManagedOperation(description="Prints the contents of the receive windows for all members")
public String printReceiveWindowMessages() {
StringBuilder ret=new StringBuilder(local_addr + ":\n");
for(Map.Entry<Address,ReceiverEntry> entry: recv_table.entrySet()) {
Address addr=entry.getKey();
Table<Message> buf=entry.getValue().msgs;
ret.append(addr).append(": ").append(buf.toString()).append('\n');
}
return ret.toString();
}
@ManagedOperation(description="Prints the contents of the send windows for all members")
public String printSendWindowMessages() {
StringBuilder ret=new StringBuilder(local_addr + ":\n");
for(Map.Entry<Address,SenderEntry> entry: send_table.entrySet()) {
Address addr=entry.getKey();
Table<Message> buf=entry.getValue().msgs;
ret.append(addr).append(": ").append(buf.toString()).append('\n');
}
return ret.toString();
}
public void resetStats() {
num_msgs_sent=num_msgs_received=num_acks_sent=num_acks_received=num_xmits=0;
avg_delivery_batch_size.clear();
Stream.of(xmit_reqs_received, xmit_reqs_sent, xmit_rsps_sent).forEach(LongAdder::reset);
}
public void init() throws Exception {
super.init();
TP transport=getTransport();
sends_can_block=transport instanceof TCP; // UDP and TCP_NIO2 won't block
time_service=transport.getTimeService();
if(time_service == null)
throw new IllegalStateException("time service from transport is null");
last_sync_sent=new ExpiryCache<>(sync_min_interval);
// max bundle size (minus overhead) divided by <long size> times bits per long
// Example: for 8000 missing messages, SeqnoList has a serialized size of 1012 bytes, for 64000 messages, the
// serialized size is 8012 bytes. Therefore, for a serialized size of 64000 bytes, we can retransmit a max of
// 8 * 64000 = 512'000 seqnos
// see SeqnoListTest.testSerialization3()
int estimated_max_msgs_in_xmit_req=(transport.getMaxBundleSize() -50) * Global.LONG_SIZE;
int old_max_xmit_size=max_xmit_req_size;
if(max_xmit_req_size <= 0)
max_xmit_req_size=estimated_max_msgs_in_xmit_req;
else
max_xmit_req_size=Math.min(max_xmit_req_size, estimated_max_msgs_in_xmit_req);
if(old_max_xmit_size != max_xmit_req_size)
log.trace("%s: set max_xmit_req_size from %d to %d", local_addr, old_max_xmit_size, max_xmit_req_size);
boolean regular_pool_enabled=(boolean)transport.getValue("thread_pool_enabled");
if(!regular_pool_enabled)
log.info("the thread pool is disabled; %s could be removed (JGRP-2069)", getClass().getSimpleName());
}
public void start() throws Exception {
timer=getTransport().getTimer();
if(timer == null)
throw new Exception("timer is null");
if(max_retransmit_time > 0)
cache=new AgeOutCache<>(timer, max_retransmit_time, this);
running=true;
startRetransmitTask();
}
public void stop() {
sendPendingAcks();
running=false;
stopRetransmitTask();
xmit_task_map.clear();
removeAllConnections();
}
public Object up(Message msg) {
if(msg.getDest() == null || msg.isFlagSet(Message.Flag.NO_RELIABILITY)) // only handle unicast messages
return up_prot.up(msg); // pass up
UnicastHeader3 hdr=msg.getHeader(this.id);
if(hdr == null)
return up_prot.up(msg);
Address sender=msg.getSrc();
switch(hdr.type) {
case UnicastHeader3.DATA: // received regular message
if(is_trace)
log.trace("%s <-- DATA(%s: #%d, conn_id=%d%s)", local_addr, sender, hdr.seqno, hdr.conn_id, hdr.first? ", first" : "");
if(Objects.equals(local_addr, sender))
handleDataReceivedFromSelf(sender, hdr.seqno, msg);
else
handleDataReceived(sender, hdr.seqno, hdr.conn_id, hdr.first, msg);
break; // we pass the deliverable message up in handleDataReceived()
default:
handleUpEvent(sender, msg, hdr);
break;
}
return null;
}
protected void handleUpEvent(Address sender, Message msg, UnicastHeader3 hdr) {
try {
switch(hdr.type) {
case UnicastHeader3.DATA: // received regular message
throw new IllegalStateException("header of type DATA is not supposed to be handled by this method");
case UnicastHeader3.ACK: // received ACK for previously sent message
handleAckReceived(sender, hdr.seqno, hdr.conn_id, hdr.timestamp());
break;
case UnicastHeader3.SEND_FIRST_SEQNO:
handleResendingOfFirstMessage(sender, hdr.timestamp());
break;
case UnicastHeader3.XMIT_REQ: // received ACK for previously sent message
handleXmitRequest(sender, Util.streamableFromBuffer(SeqnoList.class, msg.getRawBuffer(), msg.getOffset(), msg.getLength()));
break;
case UnicastHeader3.CLOSE:
log.trace(local_addr + "%s <-- CLOSE(%s: conn-id=%s)", local_addr, sender, hdr.conn_id);
ReceiverEntry entry=recv_table.get(sender);
if(entry != null && entry.connId() == hdr.conn_id) {
recv_table.remove(sender, entry);
log.trace("%s: removed receive connection for %s", local_addr, sender);
}
break;
default:
log.error(Util.getMessage("TypeNotKnown"), local_addr, hdr.type);
break;
}
}
catch(Throwable t) { // we cannot let an exception terminate the processing of this batch
log.error(Util.getMessage("FailedHandlingEvent"), local_addr, t);
}
}
public void up(MessageBatch batch) {
if(batch.dest() == null) { // not a unicast batch
up_prot.up(batch);
return;
}
if(local_addr == null || local_addr.equals(batch.sender())) {
Entry entry=local_addr != null? send_table.get(local_addr) : null;
if(entry != null)
handleBatchFromSelf(batch, entry);
return;
}
int size=batch.size();
Map<Short,List<LongTuple<Message>>> msgs=new LinkedHashMap<>();
ReceiverEntry entry=recv_table.get(batch.sender());
for(Iterator<Message> it=batch.iterator(); it.hasNext();) {
Message msg=it.next();
UnicastHeader3 hdr;
if(msg == null || msg.isFlagSet(Message.Flag.NO_RELIABILITY) || (hdr=msg.getHeader(id)) == null)
continue;
it.remove(); // remove the message from the batch, so it won't be passed up the stack
if(hdr.type != UnicastHeader3.DATA) {
handleUpEvent(msg.getSrc(), msg, hdr);
continue;
}
List<LongTuple<Message>> list=msgs.computeIfAbsent(hdr.conn_id, k -> new ArrayList<>(size));
list.add(new LongTuple<>(hdr.seqno(), msg));
if(hdr.first)
entry=getReceiverEntry(batch.sender(), hdr.seqno(), hdr.first, hdr.connId());
}
if(!msgs.isEmpty()) {
if(entry == null)
sendRequestForFirstSeqno(batch.sender());
else {
if(msgs.keySet().retainAll(Collections.singletonList(entry.connId()))) // remove all conn-ids that don't match
sendRequestForFirstSeqno(batch.sender());
List<LongTuple<Message>> list=msgs.get(entry.connId());
if(list != null && !list.isEmpty())
handleBatchReceived(entry, batch.sender(), list, batch.mode() == MessageBatch.Mode.OOB);
}
}
if(!batch.isEmpty())
up_prot.up(batch);
}
protected void handleBatchFromSelf(MessageBatch batch, Entry entry) {
List<LongTuple<Message>> list=new ArrayList<>(batch.size());
for(Iterator<Message> it=batch.iterator(); it.hasNext();) {
Message msg=it.next();
UnicastHeader3 hdr;
if(msg == null || msg.isFlagSet(Message.Flag.NO_RELIABILITY) || (hdr=msg.getHeader(id)) == null)
continue;
it.remove(); // remove the message from the batch, so it won't be passed up the stack
if(hdr.type != UnicastHeader3.DATA) {
handleUpEvent(msg.getSrc(), msg, hdr);
continue;
}
if(entry.conn_id != hdr.conn_id) {
it.remove();
continue;
}
list.add(new LongTuple<>(hdr.seqno(), msg));
}
if(!list.isEmpty()) {
if(is_trace)
log.trace("%s <-- DATA(%s: %s)", local_addr, batch.sender(), printMessageList(list));
int len=list.size();
Table<Message> win=entry.msgs;
update(entry, len);
if(batch.mode() == MessageBatch.Mode.OOB) {
MessageBatch oob_batch=new MessageBatch(local_addr, batch.sender(), batch.clusterName(), batch.multicast(), MessageBatch.Mode.OOB, len);
for(LongTuple<Message> tuple: list) {
long seq=tuple.getVal1();
Message msg=win.get(seq); // we *have* to get the message, because loopback means we didn't add it to win !
if(msg != null && msg.isFlagSet(Message.Flag.OOB) && msg.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED))
oob_batch.add(msg);
}
deliverBatch(oob_batch);
}
removeAndDeliver(win, batch.sender());
}
if(!batch.isEmpty())
up_prot.up(batch);
}
public Object down(Event evt) {
switch (evt.getType()) {
case Event.VIEW_CHANGE: // remove connections to peers that are not members anymore !
View view=evt.getArg();
List<Address> new_members=view.getMembers();
Set<Address> non_members=new HashSet<>(send_table.keySet());
non_members.addAll(recv_table.keySet());
members=new_members;
non_members.removeAll(new_members);
if(cache != null)
cache.removeAll(new_members);
if(!non_members.isEmpty()) {
log.trace("%s: closing connections of non members %s", local_addr, non_members);
non_members.forEach(this::closeConnection);
}
if(!new_members.isEmpty()) {
for(Address mbr: new_members) {
Entry e=send_table.get(mbr);
if(e != null && e.state() == State.CLOSING)
e.state(State.OPEN);
e=recv_table.get(mbr);
if(e != null && e.state() == State.CLOSING)
e.state(State.OPEN);
}
}
xmit_task_map.keySet().retainAll(new_members);
last_sync_sent.removeExpiredElements();
break;
case Event.SET_LOCAL_ADDRESS:
local_addr=evt.getArg();
break;
}
return down_prot.down(evt); // Pass on to the layer below us
}
public Object down(Message msg) {
Address dst=msg.getDest();
/* only handle unicast messages */
if (dst == null || msg.isFlagSet(Message.Flag.NO_RELIABILITY))
return down_prot.down(msg);
if(!running) {
log.trace("%s: discarded message as start() has not yet been called, message: %s", local_addr, msg);
return null;
}
if(msg.src() == null)
msg.src(local_addr); // this needs to be done so we can check whether the message sender is the local_addr
SenderEntry entry=getSenderEntry(dst);
boolean dont_loopback_set=msg.isTransientFlagSet(Message.TransientFlag.DONT_LOOPBACK)
&& dst.equals(local_addr);
short send_conn_id=entry.connId();
long seqno=entry.sent_msgs_seqno.getAndIncrement();
long sleep=10;
do {
try {
msg.putHeader(this.id,UnicastHeader3.createDataHeader(seqno,send_conn_id,seqno == DEFAULT_FIRST_SEQNO));
// add *including* UnicastHeader, adds to retransmitter
entry.msgs.add(seqno, msg, dont_loopback_set? dont_loopback_filter : null);
if(conn_expiry_timeout > 0)
entry.update();
if(dont_loopback_set)
entry.msgs.purge(entry.msgs.getHighestDeliverable());
break;
}
catch(Throwable t) {
if(running) {
Util.sleep(sleep);
sleep=Math.min(5000, sleep*2);
}
}
}
while(running);
if(is_trace) {
StringBuilder sb=new StringBuilder();
sb.append(local_addr).append(" --> DATA(").append(dst).append(": #").append(seqno).
append(", conn_id=").append(send_conn_id);
if(seqno == DEFAULT_FIRST_SEQNO) sb.append(", first");
sb.append(')');
log.trace(sb);
}
num_msgs_sent++;
return down_prot.down(msg);
}
/**
* Removes and resets from connection table (which is already locked). Returns true if member was found,
* otherwise false. This method is public only so it can be invoked by unit testing, but should not be used !
*/
public void closeConnection(Address mbr) {
closeSendConnection(mbr);
closeReceiveConnection(mbr);
}
public void closeSendConnection(Address mbr) {
SenderEntry entry=send_table.get(mbr);
if(entry != null)
entry.state(State.CLOSING);
}
public void closeReceiveConnection(Address mbr) {
ReceiverEntry entry=recv_table.get(mbr);
if(entry != null)
entry.state(State.CLOSING);
}
protected void removeSendConnection(Address mbr) {
SenderEntry entry=send_table.remove(mbr);
if(entry != null) {
entry.state(State.CLOSED);
if(members.contains(mbr))
sendClose(mbr, entry.connId());
}
}
protected void removeReceiveConnection(Address mbr) {
sendPendingAcks();
ReceiverEntry entry=recv_table.remove(mbr);
if(entry != null)
entry.state(State.CLOSED);
}
/**
* This method is public only so it can be invoked by unit testing, but should not otherwise be used !
*/
@ManagedOperation(description="Trashes all connections to other nodes. This is only used for testing")
public void removeAllConnections() {
send_table.clear();
recv_table.clear();
}
/** Sends a retransmit request to the given sender */
protected void retransmit(SeqnoList missing, Address sender) {
Message xmit_msg=new Message(sender).setBuffer(Util.streamableToBuffer(missing))
.setFlag(Message.Flag.OOB, Message.Flag.INTERNAL).putHeader(id, UnicastHeader3.createXmitReqHeader());
if(is_trace)
log.trace("%s: sending XMIT_REQ (%s) to %s", local_addr, missing, sender);
down_prot.down(xmit_msg);
xmit_reqs_sent.add(missing.size());
}
/** Called by the sender to resend messages for which no ACK has been received yet */
protected void retransmit(Message msg) {
if(is_trace) {
UnicastHeader3 hdr=msg.getHeader(id);
long seqno=hdr != null? hdr.seqno : -1;
log.trace("%s --> XMIT(%s: #%d)", local_addr, msg.getDest(), seqno);
}
down_prot.down(msg);
num_xmits++;
}
/**
* Called by AgeOutCache, to removed expired connections
* @param key
*/
public void expired(Address key) {
if(key != null) {
log.debug("%s: removing connection to %s because it expired", local_addr, key);
closeConnection(key);
}
}
/**
* Check whether the hashtable contains an entry e for {@code sender} (create if not). If
* e.received_msgs is null and {@code first} is true: create a new AckReceiverWindow(seqno) and
* add message. Set e.received_msgs to the new window. Else just add the message.
*/
protected void handleDataReceived(final Address sender, long seqno, short conn_id, boolean first, final Message msg) {
ReceiverEntry entry=getReceiverEntry(sender, seqno, first, conn_id);
if(entry == null)
return;
update(entry, 1);
boolean oob=msg.isFlagSet(Message.Flag.OOB);
final Table<Message> win=entry.msgs;
boolean added=win.add(seqno, oob? DUMMY_OOB_MSG : msg); // adding the same dummy OOB msg saves space (we won't remove it)
if(ack_threshold <= 1)
sendAck(sender, win.getHighestDeliverable(), entry.connId());
else
entry.sendAck(true); // will be sent delayed (on the next xmit_interval)
// An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering !
if(oob) {
if(added)
deliverMessage(msg, sender, seqno);
if(msg.isFlagSet(Message.Flag.INTERNAL)) {
processInternalMessage(win, sender);
return;
}
}
removeAndDeliver(win, sender);
}
/** Called when the sender of a message is the local member. In this case, we don't need to add the message
* to the table as the sender already did that */
protected void handleDataReceivedFromSelf(final Address sender, long seqno, Message msg) {
Entry entry=send_table.get(sender);
if(entry == null || entry.state() == State.CLOSED) {
log.warn("%s: entry not found for %s; dropping message", local_addr, sender);
return;
}
update(entry, 1);
final Table<Message> win=entry.msgs;
// An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering !
if(msg.isFlagSet(Message.Flag.OOB)) {
msg=win.get(seqno); // we *have* to get a message, because loopback means we didn't add it to win !
if(msg != null && msg.isFlagSet(Message.Flag.OOB) && msg.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED))
deliverMessage(msg, sender, seqno);
if(msg != null && msg.isFlagSet(Message.Flag.INTERNAL)) {
processInternalMessage(win, sender);
return;
}
}
removeAndDeliver(win, sender);
}
protected void processInternalMessage(final Table<Message> win, final Address sender) {
if(!win.isEmpty() && win.getAdders().get() == 0) // just a quick&dirty check, can also be incorrect
getTransport().submitToThreadPool(() -> removeAndDeliver(win, sender), true);
}
protected void handleBatchReceived(final ReceiverEntry entry, Address sender, List<LongTuple<Message>> msgs, boolean oob) {
if(is_trace)
log.trace("%s <-- DATA(%s: %s)", local_addr, sender, printMessageList(msgs));
int batch_size=msgs.size();
Table<Message> win=entry.msgs;
// adds all messages to the table, removing messages from 'msgs' which could not be added (already present)
boolean added=win.add(msgs, oob, oob? DUMMY_OOB_MSG : null);
update(entry, batch_size);
if(batch_size >= ack_threshold)
sendAck(sender, win.getHighestDeliverable(), entry.connId());
else
entry.sendAck(true);
if(added && oob) {
MessageBatch oob_batch=new MessageBatch(local_addr, sender, null, false, MessageBatch.Mode.OOB, msgs.size());
for(LongTuple<Message> tuple: msgs)
oob_batch.add(tuple.getVal2());
deliverBatch(oob_batch);
}
removeAndDeliver(win, sender);
}
protected void removeAndDeliver(Table<Message> win, Address sender) {
AtomicInteger adders=win.getAdders();
if(adders.getAndIncrement() != 0)
return;
final MessageBatch batch=new MessageBatch(win.getNumDeliverable())
.dest(local_addr).sender(sender).multicast(false);
Supplier<MessageBatch> batch_creator=() -> batch;
do {
try {
batch.reset(); // sets index to 0: important as batch delivery may not remove messages from batch!
win.removeMany(true, 0, drop_oob_and_dont_loopback_msgs_filter,
batch_creator, BATCH_ACCUMULATOR);
}
catch(Throwable t) {
log.error("failed removing messages from table for " + sender, t);
}
if(!batch.isEmpty()) {
// batch is guaranteed to NOT contain any OOB messages as the drop_oob_msgs_filter above removed them
if(stats)
avg_delivery_batch_size.add(batch.size());
deliverBatch(batch); // catches Throwable
}
}
while(adders.decrementAndGet() != 0);
}
protected String printMessageList(List<LongTuple<Message>> list) {
StringBuilder sb=new StringBuilder();
int size=list.size();
Message first=size > 0? list.get(0).getVal2() : null, second=size > 1? list.get(size-1).getVal2() : first;
UnicastHeader3 hdr;
if(first != null) {
hdr=first.getHeader(id);
if(hdr != null)
sb.append("#" + hdr.seqno);
}
if(second != null) {
hdr=second.getHeader(id);
if(hdr != null)
sb.append(" - #" + hdr.seqno);
}
return sb.toString();
}
protected ReceiverEntry getReceiverEntry(Address sender, long seqno, boolean first, short conn_id) {
ReceiverEntry entry=recv_table.get(sender);
if(entry != null && entry.connId() == conn_id)
return entry;
recv_table_lock.lock();
try {
entry=recv_table.get(sender);
if(first) {
if(entry == null) {
entry=createReceiverEntry(sender,seqno,conn_id);
}
else { // entry != null && win != null
if(conn_id != entry.connId()) {
log.trace("%s: conn_id=%d != %d; resetting receiver window", local_addr, conn_id, entry.connId());
recv_table.remove(sender);
entry=createReceiverEntry(sender,seqno,conn_id);
}
}
}
else { // entry == null && win == null OR entry != null && win == null OR entry != null && win != null
if(entry == null || entry.connId() != conn_id) {
recv_table_lock.unlock();
sendRequestForFirstSeqno(sender); // drops the message and returns (see below)
return null;
}
}
return entry;
}
finally {
if(recv_table_lock.isHeldByCurrentThread())
recv_table_lock.unlock();
}
}
protected SenderEntry getSenderEntry(Address dst) {
SenderEntry entry=send_table.get(dst);
if(entry == null || entry.state() == State.CLOSED) {
if(entry != null)
send_table.remove(dst, entry);
entry=new SenderEntry(getNewConnectionId());
SenderEntry existing=send_table.putIfAbsent(dst, entry);
if(existing != null)
entry=existing;
else {
log.trace("%s: created sender window for %s (conn-id=%s)", local_addr, dst, entry.connId());
if(cache != null && !members.contains(dst))
cache.add(dst);
}
}
if(entry.state() == State.CLOSING)
entry.state(State.OPEN);
return entry;
}
protected ReceiverEntry createReceiverEntry(Address sender, long seqno, short conn_id) {
Table<Message> table=new Table<>(xmit_table_num_rows, xmit_table_msgs_per_row, seqno-1,
xmit_table_resize_factor, xmit_table_max_compaction_time);
ReceiverEntry entry=new ReceiverEntry(table, conn_id);
ReceiverEntry entry2=recv_table.putIfAbsent(sender, entry);
if(entry2 != null)
return entry2;
log.trace("%s: created receiver window for %s at seqno=#%d for conn-id=%d", local_addr, sender, seqno, conn_id);
return entry;
}
/** Add the ACK to hashtable.sender.sent_msgs */
protected void handleAckReceived(Address sender, long seqno, short conn_id, int timestamp) {
if(is_trace)
log.trace("%s <-- ACK(%s: #%d, conn-id=%d, ts=%d)", local_addr, sender, seqno, conn_id, timestamp);
SenderEntry entry=send_table.get(sender);
if(entry != null && entry.connId() != conn_id) {
log.trace("%s: my conn_id (%d) != received conn_id (%d); discarding ACK", local_addr, entry.connId(), conn_id);
return;
}
Table<Message> win=entry != null? entry.msgs : null;
if(win != null && entry.updateLastTimestamp(timestamp)) {
win.purge(seqno, true); // removes all messages <= seqno (forced purge)
num_acks_received++;
}
}
/**
* We need to resend the first message with our conn_id
* @param sender
*/
protected void handleResendingOfFirstMessage(Address sender, int timestamp) {
log.trace("%s <-- SEND_FIRST_SEQNO(%s)", local_addr, sender);
SenderEntry entry=send_table.get(sender);
Table<Message> win=entry != null? entry.msgs : null;
if(win == null) {
log.warn(Util.getMessage("SenderNotFound"), local_addr, sender);
return;
}
if(!entry.updateLastTimestamp(timestamp))
return;
Message rsp=win.get(win.getLow() +1);
if(rsp != null) {
// We need to copy the UnicastHeader and put it back into the message because Message.copy() doesn't copy
// the headers and therefore we'd modify the original message in the sender retransmission window
Message copy=rsp.copy();
UnicastHeader3 hdr=copy.getHeader(this.id);
UnicastHeader3 newhdr=hdr.copy();
newhdr.first=true;
copy.putHeader(this.id, newhdr);
down_prot.down(copy);
}
}
protected void handleXmitRequest(Address sender, SeqnoList missing) {
if(is_trace)
log.trace("%s <-- XMIT(%s: #%s)", local_addr, sender, missing);
SenderEntry entry=send_table.get(sender);
xmit_reqs_received.add(missing.size());
Table<Message> win=entry != null? entry.msgs : null;
if(win != null) {
for(long seqno: missing) {
Message msg=win.get(seqno);
if(msg == null) {
if(log.isWarnEnabled() && log_not_found_msgs && !local_addr.equals(sender) && seqno > win.getLow())
log.warn(Util.getMessage("MessageNotFound"), local_addr, sender, seqno);
continue;
}
down_prot.down(msg);
xmit_rsps_sent.increment();
}
}
}
protected void deliverMessage(final Message msg, final Address sender, final long seqno) {
if(is_trace)
log.trace("%s: delivering %s#%s", local_addr, sender, seqno);
try {
up_prot.up(msg);
}
catch(Throwable t) {
log.warn(Util.getMessage("FailedToDeliverMsg"), local_addr, msg.isFlagSet(Message.Flag.OOB) ?
"OOB message" : "message", msg, t);
}
}
protected void deliverBatch(MessageBatch batch) {
try {
if(batch.isEmpty())
return;
if(is_trace) {
Message first=batch.first(), last=batch.last();
StringBuilder sb=new StringBuilder(local_addr + ": delivering");
if(first != null && last != null) {
UnicastHeader3 hdr1=first.getHeader(id), hdr2=last.getHeader(id);
sb.append(" #").append(hdr1.seqno).append(" - #").append(hdr2.seqno);
}
sb.append(" (" + batch.size()).append(" messages)");
log.trace(sb);
}
up_prot.up(batch);
}
catch(Throwable t) {
log.warn(Util.getMessage("FailedToDeliverMsg"), local_addr, "batch", batch, t);
}
}
protected long getTimestamp() {
return time_service.timestamp();
}
protected void startRetransmitTask() {
if(xmit_task == null || xmit_task.isDone())
xmit_task=timer.scheduleWithFixedDelay(new RetransmitTask(), 0, xmit_interval, TimeUnit.MILLISECONDS, sends_can_block);
}
protected void stopRetransmitTask() {
if(xmit_task != null) {
xmit_task.cancel(true);
xmit_task=null;
}
}
protected void sendAck(Address dst, long seqno, short conn_id) {
if(!running) // if we are disconnected, then don't send any acks which throw exceptions on shutdown
return;
Message ack=new Message(dst).setFlag(Message.Flag.INTERNAL).
putHeader(this.id, UnicastHeader3.createAckHeader(seqno, conn_id, timestamper.incrementAndGet()));
if(is_trace)
log.trace("%s --> ACK(%s: #%d)", local_addr, dst, seqno);
try {
down_prot.down(ack);
num_acks_sent++;
}
catch(Throwable t) {
log.error(Util.getMessage("FailedSendingAck"), local_addr, seqno, dst, t);
}
}
protected synchronized short getNewConnectionId() {
short retval=last_conn_id;
if(last_conn_id >= Short.MAX_VALUE || last_conn_id < 0)
last_conn_id=0;
else
last_conn_id++;
return retval;
}
protected void sendRequestForFirstSeqno(Address dest) {
if(last_sync_sent.addIfAbsentOrExpired(dest)) {
Message msg=new Message(dest).setFlag(Message.Flag.OOB)
.putHeader(this.id, UnicastHeader3.createSendFirstSeqnoHeader(timestamper.incrementAndGet()));
log.trace("%s --> SEND_FIRST_SEQNO(%s)", local_addr, dest);
down_prot.down(msg);
}
}
public void sendClose(Address dest, short conn_id) {
Message msg=new Message(dest).setFlag(Message.Flag.INTERNAL).putHeader(id, UnicastHeader3.createCloseHeader(conn_id));
log.trace("%s --> CLOSE(%s, conn-id=%d)", local_addr, dest, conn_id);
down_prot.down(msg);
}
@ManagedOperation(description="Closes connections that have been idle for more than conn_expiry_timeout ms")
public void closeIdleConnections() {
// close expired connections in send_table
for(Map.Entry<Address,SenderEntry> entry: send_table.entrySet()) {
SenderEntry val=entry.getValue();
if(val.state() != State.OPEN) // only look at open connections
continue;
long age=val.age();
if(age >= conn_expiry_timeout) {
log.debug("%s: closing expired connection for %s (%d ms old) in send_table",
local_addr, entry.getKey(), age);
closeSendConnection(entry.getKey());
}
}
// close expired connections in recv_table
for(Map.Entry<Address,ReceiverEntry> entry: recv_table.entrySet()) {
ReceiverEntry val=entry.getValue();
if(val.state() != State.OPEN) // only look at open connections
continue;
long age=val.age();
if(age >= conn_expiry_timeout) {
log.debug("%s: closing expired connection for %s (%d ms old) in recv_table",
local_addr, entry.getKey(), age);
closeReceiveConnection(entry.getKey());
}
}
}
@ManagedOperation(description="Removes connections that have been closed for more than conn_close_timeout ms")
public int removeExpiredConnections() {
int num_removed=0;
// remove expired connections from send_table
for(Map.Entry<Address,SenderEntry> entry: send_table.entrySet()) {
SenderEntry val=entry.getValue();
if(val.state() == State.OPEN) // only look at closing or closed connections
continue;
long age=val.age();
if(age >= conn_close_timeout) {
log.debug("%s: removing expired connection for %s (%d ms old) from send_table",
local_addr, entry.getKey(), age);
removeSendConnection(entry.getKey());
num_removed++;
}
}
// remove expired connections from recv_table
for(Map.Entry<Address,ReceiverEntry> entry: recv_table.entrySet()) {
ReceiverEntry val=entry.getValue();
if(val.state() == State.OPEN) // only look at closing or closed connections
continue;
long age=val.age();
if(age >= conn_close_timeout) {
log.debug("%s: removing expired connection for %s (%d ms old) from recv_table",
local_addr, entry.getKey(), age);
removeReceiveConnection(entry.getKey());
num_removed++;
}
}
return num_removed;
}
/**
* Removes send- and/or receive-connections whose state is not OPEN (CLOSING or CLOSED).
* @param remove_send_connections If true, send connections whose state is !OPEN are destroyed and removed
* @param remove_receive_connections If true, receive connections with state !OPEN are destroyed and removed
* @return The number of connections which were removed
*/
@ManagedOperation(description="Removes send- and/or receive-connections whose state is not OPEN (CLOSING or CLOSED)")
public int removeConnections(boolean remove_send_connections, boolean remove_receive_connections) {
int num_removed=0;
if(remove_send_connections) {
for(Map.Entry<Address,SenderEntry> entry: send_table.entrySet()) {
SenderEntry val=entry.getValue();
if(val.state() != State.OPEN) { // only look at closing or closed connections
log.debug("%s: removing connection for %s (%d ms old, state=%s) from send_table",
local_addr, entry.getKey(), val.age(), val.state());
removeSendConnection(entry.getKey());
num_removed++;
}
}
}
if(remove_receive_connections) {
for(Map.Entry<Address,ReceiverEntry> entry: recv_table.entrySet()) {
ReceiverEntry val=entry.getValue();
if(val.state() != State.OPEN) { // only look at closing or closed connections
log.debug("%s: removing expired connection for %s (%d ms old, state=%s) from recv_table",
local_addr, entry.getKey(), val.age(), val.state());
removeReceiveConnection(entry.getKey());
num_removed++;
}
}
}
return num_removed;
}
protected void update(Entry entry, int num_received) {
if(conn_expiry_timeout > 0)
entry.update();
if(entry.state() == State.CLOSING)
entry.state(State.OPEN);
num_msgs_received+=num_received;
}
/** Compares 2 timestamps, handles numeric overflow */
protected static int compare(int ts1, int ts2) {
int diff=ts1 - ts2;
return diff < 0? -1 : diff > 0? 1 : 0;
}
@SafeVarargs
protected static int accumulate(ToIntFunction<Table> func, Collection<? extends Entry> ... entries) {
return Stream.of(entries).flatMap(Collection::stream)
.map(entry -> entry.msgs).filter(Objects::nonNull)
.mapToInt(func::applyAsInt).sum();
}
protected enum State {OPEN, CLOSING, CLOSED}
protected abstract class Entry {
protected final Table<Message> msgs; // stores sent or received messages
protected final short conn_id;
protected final AtomicLong timestamp=new AtomicLong(0);
protected volatile State state=State.OPEN;
protected Entry(short conn_id, Table<Message> msgs) {
this.conn_id=conn_id;
this.msgs=msgs;
update();
}
short connId() {return conn_id;}
void update() {timestamp.set(getTimestamp());}
State state() {return state;}
Entry state(State state) {if(this.state != state) {this.state=state; update();} return this;}
/** Returns the age of the entry in ms */
long age() {return TimeUnit.MILLISECONDS.convert(getTimestamp() - timestamp.longValue(), TimeUnit.NANOSECONDS);}
}
protected final class SenderEntry extends Entry {
final AtomicLong sent_msgs_seqno=new AtomicLong(DEFAULT_FIRST_SEQNO); // seqno for msgs sent by us
protected final long[] watermark={0,0}; // the highest acked and highest sent seqno
protected int last_timestamp; // to prevent out-of-order ACKs from a receiver
public SenderEntry(short send_conn_id) {
super(send_conn_id, new Table<>(xmit_table_num_rows, xmit_table_msgs_per_row, 0,
xmit_table_resize_factor, xmit_table_max_compaction_time));
}
long[] watermark() {return watermark;}
SenderEntry watermark(long ha, long hs) {watermark[0]=ha; watermark[1]=hs; return this;}
/** Updates last_timestamp. Returns true of the update was in order (ts > last_timestamp) */
protected synchronized boolean updateLastTimestamp(int ts) {
if(last_timestamp == 0) {
last_timestamp=ts;
return true;
}
boolean success=compare(ts, last_timestamp) > 0; // ts has to be > last_timestamp
if(success)
last_timestamp=ts;
return success;
}
public String toString() {
StringBuilder sb=new StringBuilder();
if(msgs != null)
sb.append(msgs).append(", ");
sb.append("send_conn_id=" + conn_id).append(" (" + age()/1000 + " secs old) - " + state);
if(last_timestamp != 0)
sb.append(", last-ts: ").append(last_timestamp);
return sb.toString();
}
}
protected final class ReceiverEntry extends Entry {
protected volatile boolean send_ack;
public ReceiverEntry(Table<Message> received_msgs, short recv_conn_id) {
super(recv_conn_id, received_msgs);
}
ReceiverEntry sendAck(boolean flag) {send_ack=flag; return this;}
boolean sendAck() {boolean retval=send_ack; send_ack=false; return retval;}
public String toString() {
StringBuilder sb=new StringBuilder();
if(msgs != null)
sb.append(msgs).append(", ");
sb.append("recv_conn_id=" + conn_id)
.append(" (" + age() / 1000 + " secs old) - " + state);
if(send_ack)
sb.append(" [ack pending]");
return sb.toString();
}
}
/**
* Retransmitter task which periodically (every xmit_interval ms):
* <ul>
* <li>If any of the receiver windows have the ack flag set, clears the flag and sends an ack for the
* highest delivered seqno to the sender</li>
* <li>Checks all receiver windows for missing messages and asks senders for retransmission</li>
* <li>For all sender windows, checks if highest acked (HA) < highest sent (HS). If not, and HA/HS is the same
* as on the last retransmission run, send the highest sent message again</li>
* </ul>
*/
protected class RetransmitTask implements Runnable {
public void run() {
triggerXmit();
}
public String toString() {
return UNICAST3.class.getSimpleName() + ": RetransmitTask (interval=" + xmit_interval + " ms)";
}
}
@ManagedOperation(description="Triggers the retransmission task")
public void triggerXmit() {
SeqnoList missing;
for(Map.Entry<Address,ReceiverEntry> entry: recv_table.entrySet()) {
Address target=entry.getKey(); // target to send retransmit requests to
ReceiverEntry val=entry.getValue();
Table<Message> win=val != null? val.msgs : null;
// receiver: send ack for received messages if needed
if(win != null && val.sendAck()) // sendAck() resets send_ack to false
sendAck(target, win.getHighestDeliverable(), val.connId());
// receiver: retransmit missing messages (getNumMissing() is fast)
if(win != null && win.getNumMissing() > 0 && (missing=win.getMissing(max_xmit_req_size)) != null) {
long highest=missing.getLast();
Long prev_seqno=xmit_task_map.get(target);
if(prev_seqno == null)
xmit_task_map.put(target, highest); // no retransmission
else {
missing.removeHigherThan(prev_seqno); // we only retransmit the 'previous batch'
if(highest > prev_seqno)
xmit_task_map.put(target, highest);
if(!missing.isEmpty())
retransmit(missing, target);
}
}
else if(!xmit_task_map.isEmpty())
xmit_task_map.remove(target); // no current gaps for target
}
// sender: only send the *highest sent* message if HA < HS and HA/HS didn't change from the prev run
for(SenderEntry val: send_table.values()) {
Table<Message> win=val != null? val.msgs : null;
if(win != null) {
long highest_acked=win.getHighestDelivered(); // highest delivered == highest ack (sender win)
long highest_sent=win.getHighestReceived(); // we use table as a *sender* win, so it's highest *sent*...
if(highest_acked < highest_sent && val.watermark[0] == highest_acked && val.watermark[1] == highest_sent) {
// highest acked and sent hasn't moved up - let's resend the HS
Message highest_sent_msg=win.get(highest_sent);
if(highest_sent_msg != null)
retransmit(highest_sent_msg);
}
else
val.watermark(highest_acked, highest_sent);
}
}
// close idle connections
if(conn_expiry_timeout > 0)
closeIdleConnections();
if(conn_close_timeout > 0)
removeExpiredConnections();
}
@ManagedOperation(description="Sends ACKs immediately for entries which are marked as pending (ACK hasn't been sent yet)")
public void sendPendingAcks() {
for(Map.Entry<Address,ReceiverEntry> entry: recv_table.entrySet()) {
Address target=entry.getKey(); // target to send retransmit requests to
ReceiverEntry val=entry.getValue();
Table<Message> win=val != null? val.msgs : null;
// receiver: send ack for received messages if needed
if(win != null && val.sendAck())// sendAck() resets send_ack to false
sendAck(target, win.getHighestDeliverable(), val.connId());
}
}
}
|
package gui.scripting;
import com.jfoenix.controls.JFXButton;
import gui.game.GameGUI;
import gui.scripting.enumerations.Conditional;
import gui.scripting.enumerations.ScriptingTypes;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ScriptingController {
@FXML
private BehaviorList behaviorList;
@FXML
private AnchorPane choicesPane;
@FXML
private JFXButton add, subtract, submit, deleteWord;
@FXML
private VBox conditionals, data, operators, commands;
/**
* Handles click events for choice buttons. Attempts to add the selected item to the selected behavior
* in the list.
*/
private EventHandler choiceButtonClick = new EventHandler() {
/**
* @param event Click event to be handled
*/
@Override
public void handle(Event event) {
try {
// Get the last selected behavior from the list
Behavior behavior = (Behavior) behaviorList.getToggleGroup().getSelectedToggle();
if (behavior.isSelected()) {
ChoiceButton currentButton = (ChoiceButton) event.getTarget();
ScriptButton buttonToAdd = new ScriptButton(currentButton.getText());
// Copy the style of the clicked button to the newly generated ScriptButton
buttonToAdd.setStyle(currentButton.getStyle());
behavior.getChildren().add(buttonToAdd);
List<ScriptButton> currentScript =
behavior.getChildren().stream()
.filter(b -> b instanceof ScriptButton)
.map(b -> (ScriptButton) b)
.collect(Collectors.toList());
List<String> allowables = getAllowableText(currentScript);
enableButtons(allowables);
} else {
alertNoneSelected();
}
} catch (Exception ex) {
alertNoneSelected();
}
}
};
/**
* Handles click events for the deleteWord button. Removes the last word in the selected behavior
*/
private EventHandler removeLastWordClick = new EventHandler() {
/**
* @param event Click event to be handled
*/
@Override
public void handle(Event event) {
// Remove the last word in the selected behavior
try {
Behavior behavior = (Behavior) behaviorList.getToggleGroup().getSelectedToggle();
if (behavior.isSelected()) {
ScriptButton lastButton = (ScriptButton) behavior.getChildren().get(behavior.getChildren().size() - 1);
behavior.getChildren().remove(lastButton);
List<ScriptButton> currentScript =
behavior.getChildren().stream()
.filter(b -> b instanceof ScriptButton)
.map(b -> (ScriptButton) b)
.collect(Collectors.toList());
List<String> allowables = getAllowableText(currentScript);
enableButtons(allowables);
} else {
alertNoneSelected();
}
} catch (Exception ex) {
alertNoneSelected();
}
}
};
/**
* Get all button text that is valid at current state
*
* @param currentScript Script buttons that are active in the current Behavior
* @return Returns a list of all Strings that are valid adds to the current Behavior
*/
private List<String> getAllowableText(List<ScriptButton> currentScript) {
if (currentScript.isEmpty()) {
// enforce 'if'
return (Collections.singletonList("If"));
}
ScriptButton lastButton = currentScript.get(currentScript.size() - 1);
String lastButtonText = lastButton.getText().trim();
// enforce data
if (ScriptingTypes.OPERATOR.list().contains(lastButtonText) || lastButtonText.equals(Conditional.IF.text()) || lastButtonText.equals(Conditional.AND.text())) {
return ScriptingTypes.DATA.list();
}
// enforce operator
else if (ScriptingTypes.DATA.list().contains(lastButtonText) && (currentScript.size() % 4) - 2 == 0) {
return ScriptingTypes.OPERATOR.list();
}
// enforce and or then
else if (ScriptingTypes.DATA.list().contains(lastButtonText)) {
return Arrays.asList(Conditional.AND.text(), Conditional.THEN.text());
}
// enforce command
else if (lastButtonText.equals(Conditional.THEN.text())) {
return ScriptingTypes.COMMAND.list();
}
// disable all
else {
return Collections.emptyList();
}
}
public BehaviorList getBehaviorList() {
return behaviorList;
}
public ScriptingController() {
}
/**
* Set all event handlers upon initializing ScriptingGUI
*/
@FXML
private void initialize() {
// Assign each ChoiceButton in choicesPane the choiceButtonClick event handler
for (Node component : choicesPane.getChildren()) {
if (component instanceof VBox) {
for (Node subComponent : ((VBox) component).getChildren()) {
if (subComponent instanceof ChoiceButton) {
((ChoiceButton) subComponent).setOnAction(choiceButtonClick);
}
}
}
}
// Assign add button an action to create a new behavior in the list when clicked
add.setOnAction((ActionEvent event) -> {
List<Node> allBehaviors = behaviorList.getChildren().filtered(n -> n instanceof Behavior);
// Check if all behaviors in the list are complete
if (canAddBehaviors(allBehaviors)) {
Behavior behavior = new Behavior();
behavior.getStyleClass().add("behavior");
behavior.setToggleGroup(behaviorList.getToggleGroup());
behavior.setOnMouseClicked((mouseEvent) -> {
if (behavior.isSelected()) {
System.out.println("Unselected!");
behavior.setSelected(false);
} else {
System.out.println("Selected!");
behavior.setSelected(true);
}
List<ScriptButton> currentScript =
behavior.getChildren().stream()
.filter(b -> b instanceof ScriptButton)
.map(b -> (ScriptButton) b)
.collect(Collectors.toList());
List<String> allowables = getAllowableText(currentScript);
enableButtons(allowables);
});
behaviorList.getChildren().add(behavior);
} else {
// Incomplete behaviors exist, show prompt
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Unfinished Behavior!");
alert.setHeaderText("You have incomplete scripts.");
alert.setContentText("You must complete all scripts in your behavior list prior to adding another!");
alert.showAndWait();
}
});
// Assign subtract button an action to remove the selected behavior when clicked
subtract.setOnAction((ActionEvent event) -> {
try {
Behavior behavior = (Behavior) behaviorList.getToggleGroup().getSelectedToggle();
if (behavior.isSelected()) {
behaviorList.getChildren().remove(behavior);
} else {
alertNoneSelected();
}
} catch (Exception ex) {
// Do Nothing
alertNoneSelected();
}
});
// Add Event listener to deleteWord button to delete last word in the selected behavior
deleteWord.setOnAction(removeLastWordClick);
// Assign submit button an action to instantiate the GameGUI, as well as to pass all necessary scripting objects
submit.setOnAction((ActionEvent event) -> {
System.out.println("You clicked Submit!");
try {
new GameGUI();
} catch (Exception e) {
e.printStackTrace();
}
submit.getScene().getWindow().hide();
});
}
private boolean canAddBehaviors(List<Node> allBehaviors) {
for (Node node : allBehaviors) {
Behavior asBehavior = (Behavior) node;
if (!isCompleteBehavior(asBehavior)) {
return false;
}
}
return true;
}
/**
* Shows an informational alert stating that the selected action could not be completed since no behavior has been
* selected
*/
private void alertNoneSelected() {
// Nothing is selected, show prompt
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("No Behavior Selected");
alert.setHeaderText("No Behavior Selected");
alert.setContentText("Please select a behavior from your list of behaviors prior to performing an action." +
" If you have not yet created a behavior, select the green 'plus' button " +
"to do so.");
alert.showAndWait();
}
/**
* @param behavior Behavior to be checked for completeness
* @return Returns true if behavior is well formed
*/
private boolean isCompleteBehavior(Behavior behavior) {
if (behavior.getChildren().size() == 0) {
return false;
}
ScriptButton lastButton = (ScriptButton) behavior.getChildren().get(behavior.getChildren().size() - 1);
// We can do this since validity is enforced along the way
return ScriptingTypes.COMMAND.list().contains(lastButton.getText());
}
/**
* Enable all buttons in validButtons, disable the rest that appear in the choicesPane
*
* @param validText List of valid Strings at current point
*/
private void enableButtons(List<String> validText) {
List<Node> allButtons = Stream.of(conditionals.getChildren(),
commands.getChildren(),
operators.getChildren(),
data.getChildren())
.flatMap(Collection::stream)
.collect(Collectors.toList());
allButtons.forEach(b -> {
if (b instanceof ChoiceButton) {
if (validText.contains(((ChoiceButton) b).getText().trim())) {
b.setDisable(false);
} else {
b.setDisable(true);
}
}
});
}
}
|
package org.jgroups.stack;
import org.jgroups.Event;
import org.jgroups.Global;
import org.jgroups.annotations.DeprecatedProperty;
import org.jgroups.annotations.Property;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.conf.PropertyHelper;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.TP;
import org.jgroups.stack.ProtocolStack.ProtocolStackFactory;
import org.jgroups.util.StackType;
import org.jgroups.util.Tuple;
import org.jgroups.util.Util;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.*;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
/**
* The task if this class is to setup and configure the protocol stack. A string describing
* the desired setup, which is both the layering and the configuration of each layer, is
* given to the configurator which creates and configures the protocol stack and returns
* a reference to the top layer (Protocol).<p>
* Future functionality will include the capability to dynamically modify the layering
* of the protocol stack and the properties of each layer.
* @author Bela Ban
* @author Richard Achmatowicz
* @version $Id: Configurator.java,v 1.80 2010/05/05 12:41:17 belaban Exp $
*/
public class Configurator implements ProtocolStackFactory {
protected static final Log log=LogFactory.getLog(Configurator.class);
private final ProtocolStack stack;
public Configurator() {
stack = null;
}
public Configurator(ProtocolStack protocolStack) {
stack=protocolStack;
}
public Protocol setupProtocolStack() throws Exception{
return setupProtocolStack(stack.getSetupString(), stack);
}
public Protocol setupProtocolStack(ProtocolStack copySource)throws Exception{
Vector<Protocol> protocols=copySource.copyProtocols(stack);
Collections.reverse(protocols);
return connectProtocols(protocols);
}
private static Protocol setupProtocolStack(String configuration, ProtocolStack st) throws Exception {
Vector<ProtocolConfiguration> protocol_configs=parseConfigurations(configuration);
Vector<Protocol> protocols=createProtocols(protocol_configs, st);
if(protocols == null)
return null;
// basic protocol sanity check
sanityCheck(protocols);
// check InetAddress related features of stack
Map<String, Map<String,InetAddressInfo>> inetAddressMap = createInetAddressMap(protocol_configs, protocols) ;
Collection<InetAddress> addrs=getAddresses(inetAddressMap);
StackType ip_version=Util.getIpStackType(); // 0 = n/a, 4 = IPv4, 6 = IPv6
if(!addrs.isEmpty()) {
// 1. If an addr is IPv6 and we have an IPv4 stack --> FAIL
// 2. If an address is an IPv4 class D (multicast) address and the stack is IPv6: FAIL
// Else pass
for(InetAddress addr: addrs) {
if(addr instanceof Inet6Address && ip_version == StackType.IPv4)
throw new IllegalArgumentException("found IPv6 address " + addr + " in an IPv4 stack");
if(addr instanceof Inet4Address && addr.isMulticastAddress() && ip_version == StackType.IPv6)
throw new Exception("found IPv4 multicast address " + addr + " in an IPv6 stack");
}
}
if(ip_version == StackType.Unknown) {
ip_version=StackType.IPv6;
log.info("found neither an IPv4 nor an IPv6 stack, and no addresses were found to pick a stack, " +
"defaulting to IPv" + ip_version);
}
// process default values
setDefaultValues(protocol_configs, protocols, ip_version) ;
return connectProtocols(protocols);
}
/**
* Creates a new protocol given the protocol specification. Initializes the properties and starts the
* up and down handler threads.
* @param prot_spec The specification of the protocol. Same convention as for specifying a protocol stack.
* An exception will be thrown if the class cannot be created. Example:
* <pre>"VERIFY_SUSPECT(timeout=1500)"</pre> Note that no colons (:) have to be
* specified
* @param stack The protocol stack
* @return Protocol The newly created protocol
* @exception Exception Will be thrown when the new protocol cannot be created
*/
public static Protocol createProtocol(String prot_spec, ProtocolStack stack) throws Exception {
ProtocolConfiguration config;
Protocol prot;
if(prot_spec == null) throw new Exception("Configurator.createProtocol(): prot_spec is null");
// parse the configuration for this protocol
config=new ProtocolConfiguration(prot_spec);
// create an instance of the protocol class and configure it
prot=config.createLayer(stack);
prot.init();
return prot;
}
/**
* Creates a protocol stack by iterating through the protocol list and connecting
* adjacent layers. The list starts with the topmost layer and has the bottommost
* layer at the tail.
* @param protocol_list List of Protocol elements (from top to bottom)
* @return Protocol stack
*/
private static Protocol connectProtocols(Vector<Protocol> protocol_list) {
Protocol current_layer=null, next_layer=null;
for(int i=0; i < protocol_list.size(); i++) {
current_layer=protocol_list.elementAt(i);
if(i + 1 >= protocol_list.size())
break;
next_layer=protocol_list.elementAt(i + 1);
next_layer.setDownProtocol(current_layer);
current_layer.setUpProtocol(next_layer);
if(current_layer instanceof TP) {
TP transport = (TP)current_layer;
if(transport.isSingleton()) {
ConcurrentMap<String, Protocol> up_prots=transport.getUpProtocols();
String key;
synchronized(up_prots) {
while(true) {
key=Global.DUMMY + System.currentTimeMillis();
if(up_prots.containsKey(key))
continue;
up_prots.put(key, next_layer);
break;
}
}
current_layer.setUpProtocol(null);
}
}
}
return current_layer;
}
/**
* Get a string of the form "P1(config_str1):P2:P3(config_str3)" and return
* ProtocolConfigurations for it. That means, parse "P1(config_str1)", "P2" and
* "P3(config_str3)"
* @param config_str Configuration string
* @return Vector of strings
*/
private static Vector<String> parseProtocols(String config_str) throws IOException {
Vector<String> retval=new Vector<String>();
PushbackReader reader=new PushbackReader(new StringReader(config_str));
int ch;
StringBuilder sb;
boolean running=true;
while(running) {
String protocol_name=readWord(reader);
sb=new StringBuilder();
sb.append(protocol_name);
ch=read(reader);
if(ch == -1) {
retval.add(sb.toString());
break;
}
if(ch == ':') { // no attrs defined
retval.add(sb.toString());
continue;
}
if(ch == '(') { // more attrs defined
reader.unread(ch);
String attrs=readUntil(reader, ')');
sb.append(attrs);
retval.add(sb.toString());
}
else {
retval.add(sb.toString());
}
while(true) {
ch=read(reader);
if(ch == ':') {
break;
}
if(ch == -1) {
running=false;
break;
}
}
}
reader.close();
return retval;
}
private static int read(Reader reader) throws IOException {
int ch=-1;
while((ch=reader.read()) != -1) {
if(!Character.isWhitespace(ch))
return ch;
}
return ch;
}
/**
* Return a number of ProtocolConfigurations in a vector
* @param configuration protocol-stack configuration string
* @return Vector of ProtocolConfigurations
*/
public static Vector<ProtocolConfiguration> parseConfigurations(String configuration) throws Exception {
Vector<ProtocolConfiguration> retval=new Vector<ProtocolConfiguration>();
Vector<String> protocol_string=parseProtocols(configuration);
if(protocol_string == null)
return null;
for(String component_string:protocol_string) {
retval.addElement(new ProtocolConfiguration(component_string));
}
return retval;
}
public static String printConfigurations(Collection<ProtocolConfiguration> configs) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(ProtocolConfiguration config: configs) {
if(first)
first=false;
else
sb.append(":");
sb.append(config.getProtocolName());
if(!config.getProperties().isEmpty()) {
sb.append('(').append(config.propertiesToString()).append(')');
}
}
return sb.toString();
}
private static String readUntil(Reader reader, char c) throws IOException {
StringBuilder sb=new StringBuilder();
int ch;
while((ch=read(reader)) != -1) {
sb.append((char)ch);
if(ch == c)
break;
}
return sb.toString();
}
private static String readWord(PushbackReader reader) throws IOException {
StringBuilder sb=new StringBuilder();
int ch;
while((ch=read(reader)) != -1) {
if(Character.isLetterOrDigit(ch) || ch == '_' || ch == '.' || ch == '$') {
sb.append((char)ch);
}
else {
reader.unread(ch);
break;
}
}
return sb.toString();
}
/**
* Takes vector of ProtocolConfigurations, iterates through it, creates Protocol for
* each ProtocolConfiguration and returns all Protocols in a vector.
* @param protocol_configs Vector of ProtocolConfigurations
* @param stack The protocol stack
* @return Vector of Protocols
*/
private static Vector<Protocol> createProtocols(Vector<ProtocolConfiguration> protocol_configs, final ProtocolStack stack) throws Exception {
Vector<Protocol> retval=new Vector<Protocol>();
ProtocolConfiguration protocol_config;
Protocol layer;
String singleton_name;
for(int i=0; i < protocol_configs.size(); i++) {
protocol_config=protocol_configs.elementAt(i);
singleton_name=protocol_config.getProperties().get(Global.SINGLETON_NAME);
if(singleton_name != null && singleton_name.trim().length() > 0) {
Map<String,Tuple<TP, ProtocolStack.RefCounter>> singleton_transports=ProtocolStack.getSingletonTransports();
synchronized(singleton_transports) {
if(i > 0) { // crude way to check whether protocol is a transport
throw new IllegalArgumentException("Property 'singleton_name' can only be used in a transport" +
" protocol (was used in " + protocol_config.getProtocolName() + ")");
}
Tuple<TP, ProtocolStack.RefCounter> val=singleton_transports.get(singleton_name);
layer=val != null? val.getVal1() : null;
if(layer != null) {
retval.add(layer);
}
else {
layer=protocol_config.createLayer(stack);
if(layer == null)
return null;
singleton_transports.put(singleton_name, new Tuple<TP, ProtocolStack.RefCounter>((TP)layer,new ProtocolStack.RefCounter((short)0,(short)0)));
retval.addElement(layer);
}
}
continue;
}
layer=protocol_config.createLayer(stack);
if(layer == null)
return null;
retval.addElement(layer);
}
return retval;
}
/**
Throws an exception if sanity check fails. Possible sanity check is uniqueness of all protocol names
*/
public static void sanityCheck(Vector<Protocol> protocols) throws Exception {
Vector<String> names=new Vector<String>();
Protocol prot;
String name;
Vector<ProtocolReq> req_list=new Vector<ProtocolReq>();
// Checks for unique names
for(int i=0; i < protocols.size(); i++) {
prot=protocols.elementAt(i);
name=prot.getName();
for(int j=0; j < names.size(); j++) {
if(name.equals(names.elementAt(j))) {
throw new Exception("Configurator.sanityCheck(): protocol name " + name +
" has been used more than once; protocol names have to be unique !");
}
}
names.addElement(name);
}
// check for unique IDs
Set<Short> ids=new HashSet<Short>();
for(Protocol protocol: protocols) {
short id=protocol.getId();
if(id > 0 && ids.add(id) == false)
throw new Exception("Protocol ID " + id + " (name=" + protocol.getName() +
") is duplicate; protocol IDs have to be unique");
}
// Checks whether all requirements of all layers are met
for(Protocol p:protocols){
req_list.add(new ProtocolReq(p));
}
for(ProtocolReq pr:req_list){
for(Integer evt_type:pr.up_reqs) {
if(!providesDownServices(req_list, evt_type)) {
throw new Exception("Configurator.sanityCheck(): event " +
Event.type2String(evt_type) + " is required by " +
pr.name + ", but not provided by any of the layers above");
}
}
for(Integer evt_type:pr.down_reqs) {
if(!providesUpServices(req_list, evt_type)) {
throw new Exception("Configurator.sanityCheck(): event " +
Event.type2String(evt_type) + " is required by " +
pr.name + ", but not provided by any of the layers above");
}
}
}
}
/**
* Returns all inet addresses found
*/
public static Collection<InetAddress> getAddresses(Map<String, Map<String, InetAddressInfo>> inetAddressMap) throws Exception {
Set<InetAddress> addrs=new HashSet<InetAddress>();
for(Map.Entry<String, Map<String, InetAddressInfo>> inetAddressMapEntry : inetAddressMap.entrySet()) {
Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMapEntry.getValue();
for(Map.Entry<String, InetAddressInfo> protocolInetAddressMapEntry : protocolInetAddressMap.entrySet()) {
InetAddressInfo inetAddressInfo=protocolInetAddressMapEntry.getValue();
// add InetAddressInfo to sets based on IP version
List<InetAddress> addresses=inetAddressInfo.getInetAddresses();
for(InetAddress address : addresses) {
if(address == null)
throw new RuntimeException("This address should not be null! - something is wrong");
addrs.add(address);
}
}
}
return addrs;
}
public static StackType determineIpVersionFromAddresses(Collection<InetAddress> addrs) throws Exception {
Set<InetAddress> ipv4_addrs= new HashSet<InetAddress>() ;
Set<InetAddress> ipv6_addrs= new HashSet<InetAddress>() ;
for(InetAddress address: addrs) {
if (address instanceof Inet4Address)
ipv4_addrs.add(address) ;
else
ipv6_addrs.add(address) ;
}
if(log.isTraceEnabled())
log.trace("all addrs=" + addrs + ", IPv4 addrs=" + ipv4_addrs + ", IPv6 addrs=" + ipv6_addrs);
// the user supplied 1 or more IP address inputs. Check if we have a consistent set
if (!addrs.isEmpty()) {
if (!ipv4_addrs.isEmpty() && !ipv6_addrs.isEmpty()) {
throw new RuntimeException("all addresses have to be either IPv4 or IPv6: IPv4 addresses=" +
ipv4_addrs + ", IPv6 addresses=" + ipv6_addrs);
}
return !ipv6_addrs.isEmpty()? StackType.IPv6 : StackType.IPv4;
}
return StackType.Unknown;
}
/*
* A method which does the following:
* - discovers all Fields or Methods within the protocol stack which set
* InetAddress, IpAddress, InetSocketAddress (and Lists of such) for which the user *has*
* specified a default value.
* - stores the resulting set of Fields and Methods in a map of the form:
* Protocol -> Property -> InetAddressInfo
* where InetAddressInfo instances encapsulate the InetAddress related information
* of the Fields and Methods.
*/
public static Map<String, Map<String,InetAddressInfo>> createInetAddressMap(Vector<ProtocolConfiguration> protocol_configs,
Vector<Protocol> protocols) throws Exception {
// Map protocol -> Map<String, InetAddressInfo>, where the latter is protocol specific
Map<String, Map<String,InetAddressInfo>> inetAddressMap = new HashMap<String, Map<String, InetAddressInfo>>() ;
// collect InetAddressInfo
for (int i = 0; i < protocol_configs.size(); i++) {
ProtocolConfiguration protocol_config = protocol_configs.get(i) ;
Protocol protocol = protocols.get(i) ;
String protocolName = protocol.getName();
// regenerate the Properties which were destroyed during basic property processing
Map<String,String> properties = protocol_config.getOriginalProperties();
// create an InetAddressInfo structure for them
// Method[] methods=protocol.getClass().getMethods();
Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(protocol.getClass(), Property.class);
for(int j = 0; j < methods.length; j++) {
if (methods[j].isAnnotationPresent(Property.class) && isSetPropertyMethod(methods[j])) {
String propertyName = PropertyHelper.getPropertyName(methods[j]) ;
String propertyValue = properties.get(propertyName);
// if there is a systemProperty attribute defined in the annotation, set the property value from the system property
String tmp=grabSystemProp(methods[j].getAnnotation(Property.class));
if(tmp != null)
propertyValue=tmp;
if (propertyValue != null && InetAddressInfo.isInetAddressRelated(methods[j])) {
Object converted = null ;
try {
converted=PropertyHelper.getConvertedValue(protocol, methods[j], properties, propertyValue, false);
}
catch(Exception e) {
throw new Exception("String value could not be converted for method " + propertyName + " in "
+ protocolName + " with default value " + propertyValue + ".Exception is " +e, e);
}
InetAddressInfo inetinfo = new InetAddressInfo(protocol, methods[j], properties, propertyValue, converted) ;
Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMap.get(protocolName);
if(protocolInetAddressMap == null) {
protocolInetAddressMap = new HashMap<String,InetAddressInfo>() ;
inetAddressMap.put(protocolName, protocolInetAddressMap) ;
}
protocolInetAddressMap.put(propertyName, inetinfo) ;
}
}
}
//traverse class hierarchy and find all annotated fields and add them to the list if annotated
for(Class<?> clazz=protocol.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(int j = 0; j < fields.length; j++ ) {
if (fields[j].isAnnotationPresent(Property.class)) {
String propertyName = PropertyHelper.getPropertyName(fields[j], properties) ;
String propertyValue = properties.get(propertyName) ;
// if there is a systemProperty attribute defined in the annotation, set the property value from the system property
String tmp=grabSystemProp(fields[j].getAnnotation(Property.class));
if(tmp != null)
propertyValue=tmp;
if ((propertyValue != null || !PropertyHelper.usesDefaultConverter(fields[j]))
&& InetAddressInfo.isInetAddressRelated(protocol, fields[j])) {
Object converted = null ;
try {
converted=PropertyHelper.getConvertedValue(protocol, fields[j], properties, propertyValue, false);
}
catch(Exception e) {
throw new Exception("String value could not be converted for method " + propertyName + " in "
+ protocolName + " with default value " + propertyValue + ".Exception is " +e, e);
}
InetAddressInfo inetinfo = new InetAddressInfo(protocol, fields[j], properties, propertyValue, converted) ;
Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMap.get(protocolName);
if(protocolInetAddressMap == null) {
protocolInetAddressMap = new HashMap<String,InetAddressInfo>() ;
inetAddressMap.put(protocolName, protocolInetAddressMap) ;
}
protocolInetAddressMap.put(propertyName, inetinfo) ;
}// recompute
}
}
}
}
return inetAddressMap ;
}
/*
* Method which processes @Property.default() values, associated with the annotation
* using the defaultValue= attribute. This method does the following:
* - locate all properties which have no user value assigned
* - if the defaultValue attribute is not "", generate a value for the field using the
* property converter for that property and assign it to the field
*/
public static void setDefaultValues(Vector<ProtocolConfiguration> protocol_configs, Vector<Protocol> protocols,
StackType ip_version) throws Exception {
InetAddress default_ip_address=Util.getFirstNonLoopbackAddress(ip_version);
if(default_ip_address == null) {
log.warn("unable to find an address other than loopback for IP version " + ip_version);
default_ip_address=Util.getLocalhost(ip_version);
}
for(int i=0; i < protocol_configs.size(); i++) {
ProtocolConfiguration protocol_config=protocol_configs.get(i);
Protocol protocol=protocols.get(i);
String protocolName=protocol.getName();
// regenerate the Properties which were destroyed during basic property processing
Map<String,String> properties=protocol_config.getOriginalProperties();
Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(protocol.getClass(), Property.class);
for(int j=0; j < methods.length; j++) {
if(isSetPropertyMethod(methods[j])) {
String propertyName=PropertyHelper.getPropertyName(methods[j]);
Object propertyValue=getValueFromProtocol(protocol, propertyName);
if(propertyValue == null) { // if propertyValue is null, check if there is a we can use
Property annotation=methods[j].getAnnotation(Property.class);
// get the default value for the method- check for InetAddress types
String defaultValue=null;
if(InetAddressInfo.isInetAddressRelated(methods[j])) {
defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6();
if(defaultValue != null && defaultValue.length() > 0) {
Object converted=null;
try {
if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS))
converted=default_ip_address;
else
converted=PropertyHelper.getConvertedValue(protocol, methods[j], properties, defaultValue, true);
methods[j].invoke(protocol, converted);
}
catch(Exception e) {
throw new Exception("default could not be assigned for method " + propertyName + " in "
+ protocolName + " with default " + defaultValue, e);
}
if(log.isDebugEnabled())
log.debug("set property " + protocolName + "." + propertyName + " to default value " + converted);
}
}
}
}
}
//traverse class hierarchy and find all annotated fields and add them to the list if annotated
Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), Property.class);
for(int j=0; j < fields.length; j++) {
String propertyName=PropertyHelper.getPropertyName(fields[j], properties);
Object propertyValue=getValueFromProtocol(protocol, fields[j]);
if(propertyValue == null) {
// add to collection of @Properties with no user specified value
Property annotation=fields[j].getAnnotation(Property.class);
// get the default value for the field - check for InetAddress types
String defaultValue=null;
if(InetAddressInfo.isInetAddressRelated(protocol, fields[j])) {
defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6();
if(defaultValue != null && defaultValue.length() > 0) {
// condition for invoking converter
if(defaultValue != null || !PropertyHelper.usesDefaultConverter(fields[j])) {
Object converted=null;
try {
if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS))
converted=default_ip_address;
else
converted=PropertyHelper.getConvertedValue(protocol, fields[j], properties, defaultValue, true);
if(converted != null)
setField(fields[j], protocol, converted);
}
catch(Exception e) {
throw new Exception("default could not be assigned for field " + propertyName + " in "
+ protocolName + " with default value " + defaultValue, e);
}
if(log.isDebugEnabled())
log.debug("set property " + protocolName + "." + propertyName + " to default value " + converted);
}
}
}
}
}
}
}
public static Object getValueFromProtocol(Protocol protocol, Field field) throws IllegalAccessException {
if(protocol == null || field == null) return null;
if(!Modifier.isPublic(field.getModifiers()))
field.setAccessible(true);
return field.get(protocol);
}
public static Object getValueFromProtocol(Protocol protocol, String field_name) throws IllegalAccessException {
if(protocol == null || field_name == null) return null;
Field field=Util.getField(protocol.getClass(), field_name);
return field != null? getValueFromProtocol(protocol, field) : null;
}
/** Check whether any of the protocols 'below' provide evt_type */
static boolean providesUpServices(Vector<ProtocolReq> req_list, int evt_type) {
for (ProtocolReq pr:req_list){
if(pr.providesUpService(evt_type))
return true;
}
return false;
}
/** Checks whether any of the protocols 'above' provide evt_type */
static boolean providesDownServices(Vector<ProtocolReq> req_list, int evt_type) {
for (ProtocolReq pr:req_list){
if(pr.providesDownService(evt_type))
return true;
}
return false;
}
/**
* This method creates a list of all properties (Field or Method) in dependency order,
* where dependencies are specified using the dependsUpon specifier of the Property annotation.
* In particular, it does the following:
* (i) creates a master list of properties
* (ii) checks that all dependency references are present
* (iii) creates a copy of the master list in dependency order
*/
static AccessibleObject[] computePropertyDependencies(Object obj, Map<String,String> properties) {
// List of Fields and Methods of the protocol annotated with @Property
List<AccessibleObject> unorderedFieldsAndMethods = new LinkedList<AccessibleObject>() ;
List<AccessibleObject> orderedFieldsAndMethods = new LinkedList<AccessibleObject>() ;
// Maps property name to property object
Map<String, AccessibleObject> propertiesInventory = new HashMap<String, AccessibleObject>() ;
// get the methods for this class and add them to the list if annotated with @Property
Method[] methods=obj.getClass().getMethods();
for(int i = 0; i < methods.length; i++) {
if (methods[i].isAnnotationPresent(Property.class) && isSetPropertyMethod(methods[i])) {
String propertyName = PropertyHelper.getPropertyName(methods[i]) ;
unorderedFieldsAndMethods.add(methods[i]) ;
propertiesInventory.put(propertyName, methods[i]) ;
}
}
//traverse class hierarchy and find all annotated fields and add them to the list if annotated
for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(int i = 0; i < fields.length; i++ ) {
if (fields[i].isAnnotationPresent(Property.class)) {
String propertyName = PropertyHelper.getPropertyName(fields[i], properties) ;
unorderedFieldsAndMethods.add(fields[i]) ;
// may need to change this based on name parameter of Property
propertiesInventory.put(propertyName, fields[i]) ;
}
}
}
// at this stage, we have all Fields and Methods annotated with @Property
checkDependencyReferencesPresent(unorderedFieldsAndMethods, propertiesInventory) ;
// order the fields and methods by dependency
orderedFieldsAndMethods = orderFieldsAndMethodsByDependency(unorderedFieldsAndMethods, propertiesInventory) ;
// convert to array of Objects
AccessibleObject[] result = new AccessibleObject[orderedFieldsAndMethods.size()] ;
for(int i = 0; i < orderedFieldsAndMethods.size(); i++) {
result[i] = orderedFieldsAndMethods.get(i) ;
}
return result ;
}
static List<AccessibleObject> orderFieldsAndMethodsByDependency(List<AccessibleObject> unorderedList,
Map<String, AccessibleObject> propertiesMap) {
// Stack to detect cycle in depends relation
Stack<AccessibleObject> stack = new Stack<AccessibleObject>() ;
// the result list
List<AccessibleObject> orderedList = new LinkedList<AccessibleObject>() ;
// add the elements from the unordered list to the ordered list
// any dependencies will be checked and added first, in recursive manner
for(int i = 0; i < unorderedList.size(); i++) {
AccessibleObject obj = unorderedList.get(i) ;
addPropertyToDependencyList(orderedList, propertiesMap, stack, obj) ;
}
return orderedList ;
}
/**
* DFS of dependency graph formed by Property annotations and dependsUpon parameter
* This is used to create a list of Properties in dependency order
*/
static void addPropertyToDependencyList(List<AccessibleObject> orderedList, Map<String, AccessibleObject> props, Stack<AccessibleObject> stack, AccessibleObject obj) {
if (orderedList.contains(obj))
return ;
if (stack.search(obj) > 0) {
throw new RuntimeException("Deadlock in @Property dependency processing") ;
}
// record the fact that we are processing obj
stack.push(obj) ;
// process dependencies for this object before adding it to the list
Property annotation = obj.getAnnotation(Property.class) ;
String dependsClause = annotation.dependsUpon() ;
StringTokenizer st = new StringTokenizer(dependsClause, ",") ;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
AccessibleObject dep = props.get(token) ;
// if null, throw exception
addPropertyToDependencyList(orderedList, props, stack, dep) ;
}
// indicate we're done with processing dependencies
stack.pop() ;
// we can now add in dependency order
orderedList.add(obj) ;
}
/*
* Checks that for every dependency referred, there is a matching property
*/
static void checkDependencyReferencesPresent(List<AccessibleObject> objects, Map<String, AccessibleObject> props) {
// iterate overall properties marked by @Property
for(int i = 0; i < objects.size(); i++) {
// get the Property annotation
AccessibleObject ao = objects.get(i) ;
Property annotation = ao.getAnnotation(Property.class) ;
if (annotation == null) {
throw new IllegalArgumentException("@Property annotation is required for checking dependencies;" +
" annotation is missing for Field/Method " + ao.toString()) ;
}
String dependsClause = annotation.dependsUpon() ;
if (dependsClause.trim().length() == 0)
continue ;
// split dependsUpon specifier into tokens; trim each token; search for token in list
StringTokenizer st = new StringTokenizer(dependsClause, ",") ;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim() ;
// check that the string representing a property name is in the list
boolean found = false ;
Set<String> keyset = props.keySet();
for (Iterator<String> iter = keyset.iterator(); iter.hasNext();) {
if (iter.next().equals(token)) {
found = true ;
break ;
}
}
if (!found) {
throw new IllegalArgumentException("@Property annotation " + annotation.name() +
" has an unresolved dependsUpon property: " + token) ;
}
}
}
}
public static void resolveAndInvokePropertyMethods(Object obj, Map<String,String> props) throws Exception {
Method[] methods=obj.getClass().getMethods();
for(Method method: methods) {
resolveAndInvokePropertyMethod(obj, method, props) ;
}
}
public static void resolveAndInvokePropertyMethod(Object obj, Method method, Map<String,String> props) throws Exception {
String methodName=method.getName();
Property annotation=method.getAnnotation(Property.class);
if(annotation != null && isSetPropertyMethod(method)) {
String propertyName=PropertyHelper.getPropertyName(method) ;
String propertyValue=props.get(propertyName);
// if there is a systemProperty attribute defined in the annotation, set the property value from the system property
String tmp=grabSystemProp(method.getAnnotation(Property.class));
if(tmp != null)
propertyValue=tmp;
if(propertyName != null && propertyValue != null) {
String deprecated_msg=annotation.deprecatedMessage();
if(deprecated_msg != null && deprecated_msg.length() > 0) {
log.warn(method.getDeclaringClass().getSimpleName() + "." + methodName + ": " + deprecated_msg);
}
}
if(propertyValue != null) {
Object converted=null;
try {
converted=PropertyHelper.getConvertedValue(obj, method, props, propertyValue, true);
method.invoke(obj, converted);
}
catch(Exception e) {
String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName();
throw new Exception("Could not assign property " + propertyName + " in "
+ name + ", method is " + methodName + ", converted value is " + converted, e);
}
}
props.remove(propertyName);
}
}
public static void resolveAndAssignFields(Object obj, Map<String,String> props) throws Exception {
//traverse class hierarchy and find all annotated fields
for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(Field field: fields) {
resolveAndAssignField(obj, field, props) ;
}
}
}
public static void resolveAndAssignField(Object obj, Field field, Map<String,String> props) throws Exception {
Property annotation=field.getAnnotation(Property.class);
if(annotation != null) {
String propertyName = PropertyHelper.getPropertyName(field, props) ;
String propertyValue=props.get(propertyName);
// if there is a systemProperty attribute defined in the annotation, set the property value from the system property
String tmp=grabSystemProp(field.getAnnotation(Property.class));
if(tmp != null)
propertyValue=tmp;
if(propertyName != null && propertyValue != null) {
String deprecated_msg=annotation.deprecatedMessage();
if(deprecated_msg != null && deprecated_msg.length() > 0) {
log.warn(field.getDeclaringClass().getSimpleName() + "." + field.getName() + ": " + deprecated_msg);
}
}
if(propertyValue != null || !PropertyHelper.usesDefaultConverter(field)){
Object converted=null;
try {
converted=PropertyHelper.getConvertedValue(obj, field, props, propertyValue, true);
if(converted != null)
setField(field, obj, converted);
}
catch(Exception e) {
String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName();
throw new Exception("Property assignment of " + propertyName + " in "
+ name + " with original property value " + propertyValue + " and converted to " + converted
+ " could not be assigned. Exception is " +e, e);
}
}
props.remove(propertyName);
}
}
public static void removeDeprecatedProperties(Object obj, Map<String,String> props) throws Exception {
//traverse class hierarchy and find all deprecated properties
for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
if(clazz.isAnnotationPresent(DeprecatedProperty.class)) {
DeprecatedProperty declaredAnnotation=clazz.getAnnotation(DeprecatedProperty.class);
String[] deprecatedProperties=declaredAnnotation.names();
for(String propertyName : deprecatedProperties) {
String propertyValue=props.get(propertyName);
if(propertyValue != null) {
if(log.isWarnEnabled()) {
String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName();
log.warn(name + " property " + propertyName + " was deprecated and is ignored");
}
props.remove(propertyName);
}
}
}
}
}
public static boolean isSetPropertyMethod(Method method) {
return (method.getName().startsWith("set") &&
method.getReturnType() == java.lang.Void.TYPE &&
method.getParameterTypes().length == 1);
}
public static void setField(Field field, Object target, Object value) {
if(!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
}
try {
field.set(target, value);
}
catch(IllegalAccessException iae) {
throw new IllegalArgumentException("Could not set field " + field, iae);
}
}
public static Object getField(Field field, Object target) {
if(!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
}
try {
return field.get(target);
}
catch(IllegalAccessException iae) {
throw new IllegalArgumentException("Could not get field " + field, iae);
}
}
private static String grabSystemProp(Property annotation) {
String[] system_property_names=annotation.systemProperty();
String retval=null;
for(String system_property_name: system_property_names) {
if(system_property_name != null && system_property_name.length() > 0) {
if(system_property_name.equals(Global.BIND_ADDR) || system_property_name.equals(Global.BIND_ADDR_OLD))
if(Util.isBindAddressPropertyIgnored())
continue;
try {
retval=System.getProperty(system_property_name);
if(retval != null)
return retval;
}
catch(SecurityException ex) {
log.error("failed getting system property for " + system_property_name, ex);
}
}
}
return retval;
}
private static class ProtocolReq {
final Vector<Integer> up_reqs=new Vector<Integer>();
final Vector<Integer> down_reqs=new Vector<Integer>();
final Vector<Integer> up_provides=new Vector<Integer>();
final Vector<Integer> down_provides=new Vector<Integer>();
final String name;
ProtocolReq(Protocol p) {
this.name=p.getName();
if(p.requiredUpServices() != null) {
up_reqs.addAll(p.requiredUpServices());
}
if(p.requiredDownServices() != null) {
down_reqs.addAll(p.requiredDownServices());
}
if(p.providedUpServices() != null) {
up_provides.addAll(p.providedUpServices());
}
if(p.providedDownServices() != null) {
down_provides.addAll(p.providedDownServices());
}
}
boolean providesUpService(int evt_type) {
for(Integer type:up_provides) {
if(type == evt_type)
return true;
}
return false;
}
boolean providesDownService(int evt_type) {
for(Integer type:down_provides) {
if(type == evt_type)
return true;
}
return false;
}
public String toString() {
StringBuilder ret=new StringBuilder();
ret.append('\n' + name + ':');
if(!up_reqs.isEmpty())
ret.append("\nRequires from above: " + printUpReqs());
if(!down_reqs.isEmpty())
ret.append("\nRequires from below: " + printDownReqs());
if(!up_provides.isEmpty())
ret.append("\nProvides to above: " + printUpProvides());
if(!down_provides.isEmpty())
ret.append("\nProvides to below: ").append(printDownProvides());
return ret.toString();
}
String printUpReqs() {
StringBuilder ret;
ret=new StringBuilder("[");
for(Integer type:up_reqs) {
ret.append(Event.type2String(type) + ' ');
}
return ret.toString() + ']';
}
String printDownReqs() {
StringBuilder ret=new StringBuilder("[");
for(Integer type:down_reqs) {
ret.append(Event.type2String(type) + ' ');
}
return ret.toString() + ']';
}
String printUpProvides() {
StringBuilder ret=new StringBuilder("[");
for(Integer type:up_provides) {
ret.append(Event.type2String(type) + ' ');
}
return ret.toString() + ']';
}
String printDownProvides() {
StringBuilder ret=new StringBuilder("[");
for(Integer type:down_provides) {
ret.append(Event.type2String(type) + ' ');
}
return ret.toString() + ']';
}
}
/**
* Parses and encapsulates the specification for 1 protocol of the protocol stack, e.g.
* <code>UNICAST(timeout=5000)</code>
*/
public static class ProtocolConfiguration {
private final String protocol_name;
private String properties_str;
private final Map<String,String> properties=new HashMap<String,String>();
private static final String protocol_prefix="org.jgroups.protocols";
/**
* Creates a new ProtocolConfiguration.
* @param config_str The configuration specification for the protocol, e.g.
* <pre>VERIFY_SUSPECT(timeout=1500)</pre>
*/
public ProtocolConfiguration(String config_str) throws Exception {
int index=config_str.indexOf('('); // e.g. "UDP(in_port=3333)"
int end_index=config_str.lastIndexOf(')');
if(index == -1) {
protocol_name=config_str;
properties_str="";
}
else {
if(end_index == -1) {
throw new Exception("Configurator.ProtocolConfiguration(): closing ')' " +
"not found in " + config_str + ": properties cannot be set !");
}
else {
properties_str=config_str.substring(index + 1, end_index);
protocol_name=config_str.substring(0, index);
}
}
parsePropertiesString(properties_str, properties) ;
}
public String getProtocolName() {
return protocol_name;
}
public Map<String, String> getProperties() {
return properties;
}
public Map<String, String> getOriginalProperties() throws Exception {
Map<String,String> props = new HashMap<String,String>();
parsePropertiesString(properties_str, props) ;
return props ;
}
private void parsePropertiesString(String properties_str, Map<String, String> properties) throws Exception {
int index = 0 ;
/* "in_port=5555;out_port=6666" */
if(properties_str.length() > 0) {
String[] components=properties_str.split(";");
for(String property : components) {
String name, value;
index=property.indexOf('=');
if(index == -1) {
throw new Exception("Configurator.ProtocolConfiguration(): '=' not found in " + property
+ " of " + protocol_name);
}
name=property.substring(0, index);
value=property.substring(index + 1, property.length());
properties.put(name, value);
}
}
}
public void substituteVariables() {
for(Iterator<Map.Entry<String,String>> it=properties.entrySet().iterator(); it.hasNext();) {
Map.Entry<String,String> entry=it.next();
String key=entry.getKey();
String val=entry.getValue();
String tmp=Util.substituteVariable(val);
if(!val.equals(tmp)) {
properties.put(key,tmp);
}
else {
if(tmp.contains("${")) {
if(log.isWarnEnabled())
log.warn("variable \"" + val + "\" in " + protocol_name + " could not be substituted; " +
key + " is removed from properties");
it.remove();
}
}
}
properties_str=propertiesToString();
}
private Protocol createLayer(ProtocolStack prot_stack) throws Exception {
Protocol retval=null;
if(protocol_name == null)
return null;
String defaultProtocolName=protocol_prefix + '.' + protocol_name;
Class<?> clazz=null;
try {
clazz=Util.loadClass(defaultProtocolName, this.getClass());
}
catch(ClassNotFoundException e) {
}
if(clazz == null) {
try {
clazz=Util.loadClass(protocol_name, this.getClass());
}
catch(ClassNotFoundException e) {
}
if(clazz == null) {
throw new Exception("unable to load class for protocol " + protocol_name +
" (either as an absolute - " + protocol_name + " - or relative - " +
defaultProtocolName + " - package name)!");
}
}
try {
retval=(Protocol)clazz.newInstance();
if(retval == null)
throw new Exception("creation of instance for protocol " + protocol_name + "failed !");
retval.setProtocolStack(prot_stack);
removeDeprecatedProperties(retval, properties);
// before processing Field and Method based properties, take dependencies specified
// with @Property.dependsUpon into account
AccessibleObject[] dependencyOrderedFieldsAndMethods = computePropertyDependencies(retval, properties) ;
for(AccessibleObject ordered: dependencyOrderedFieldsAndMethods) {
if (ordered instanceof Field) {
resolveAndAssignField(retval, (Field)ordered, properties) ;
}
else if (ordered instanceof Method) {
resolveAndInvokePropertyMethod(retval, (Method)ordered, properties) ;
}
}
List<Object> additional_objects=retval.getConfigurableObjects();
if(additional_objects != null && !additional_objects.isEmpty()) {
for(Object obj: additional_objects) {
resolveAndAssignFields(obj, properties);
resolveAndInvokePropertyMethods(obj, properties);
}
}
if(!properties.isEmpty()) {
throw new IllegalArgumentException("the following properties in " + protocol_name
+ " are not recognized: " + properties);
}
}
catch(InstantiationException inst_ex) {
log.error("an instance of " + protocol_name + " could not be created. Please check that it implements" +
" interface Protocol and that is has a public empty constructor !");
throw inst_ex;
}
return retval;
}
public String toString() {
StringBuilder retval=new StringBuilder();
if(protocol_name == null)
retval.append("<unknown>");
else
retval.append(protocol_name);
if(properties != null)
retval.append("(" + Util.print(properties) + ')');
return retval.toString();
}
public String propertiesToString() {
return Util.printMapWithDelimiter(properties, ";");
}
}
public static class InetAddressInfo {
Protocol protocol ;
AccessibleObject fieldOrMethod ;
Map<String,String> properties ;
String propertyName ;
String stringValue ;
Object convertedValue ;
boolean isField ;
boolean isParameterized ; // is the associated type parametrized? (e.g. Collection<String>)
Object baseType ; // what is the base type (e.g. Collection)
InetAddressInfo(Protocol protocol, AccessibleObject fieldOrMethod, Map<String,String> properties, String stringValue,
Object convertedValue) {
// check input values
if (protocol == null) {
throw new IllegalArgumentException("Protocol for Field/Method must be non-null") ;
}
if (fieldOrMethod instanceof Field) {
isField = true ;
} else if (fieldOrMethod instanceof Method) {
isField = false ;
} else
throw new IllegalArgumentException("AccesibleObject is neither Field nor Method") ;
if (properties == null) {
throw new IllegalArgumentException("Properties for Field/Method must be non-null") ;
}
// set the values passed by the user - need to check for null
this.protocol = protocol ;
this.fieldOrMethod = fieldOrMethod ;
this.properties = properties ;
this.stringValue = stringValue ;
this.convertedValue = convertedValue ;
// set the property name
Property annotation=fieldOrMethod.getAnnotation(Property.class);
if (isField())
propertyName=PropertyHelper.getPropertyName((Field)fieldOrMethod, properties) ;
else
propertyName=PropertyHelper.getPropertyName((Method)fieldOrMethod) ;
// is variable type parameterized
this.isParameterized = false ;
if (isField())
this.isParameterized = hasParameterizedType((Field)fieldOrMethod) ;
else
this.isParameterized = hasParameterizedType((Method)fieldOrMethod) ;
// if parameterized, what is the base type?
this.baseType = null ;
if (isField() && isParameterized) {
// the Field has a single type
ParameterizedType fpt = (ParameterizedType)((Field)fieldOrMethod).getGenericType() ;
this.baseType = fpt.getActualTypeArguments()[0] ;
}
else if (!isField() && isParameterized) {
// the Method has several parameters (and so types)
Type[] types = (Type[])((Method)fieldOrMethod).getGenericParameterTypes();
ParameterizedType mpt = (ParameterizedType) types[0] ;
this.baseType = mpt.getActualTypeArguments()[0] ;
}
}
// Protocol getProtocol() {return protocol ;}
Object getProtocol() {return protocol ;}
AccessibleObject getFieldOrMethod() {return fieldOrMethod ;}
boolean isField() { return isField ; }
String getStringValue() {return stringValue ;}
String getPropertyName() {return propertyName ;}
Map<String,String> getProperties() {return properties ;}
Object getConvertedValue() {return convertedValue ;}
boolean isParameterized() {return isParameterized ;}
Object getBaseType() { return baseType ;}
static boolean hasParameterizedType(Field f) {
if (f == null) {
throw new IllegalArgumentException("Field argument is null") ;
}
Type type = f.getGenericType();
return (type instanceof ParameterizedType) ;
}
static boolean hasParameterizedType(Method m) throws IllegalArgumentException {
if (m == null) {
throw new IllegalArgumentException("Method argument is null") ;
}
Type[] types = m.getGenericParameterTypes() ;
return (types[0] instanceof ParameterizedType) ;
}
static boolean isInetAddressRelated(Protocol prot, Field f) {
if (hasParameterizedType(f)) {
// check for List<InetAddress>, List<InetSocketAddress>, List<IpAddress>
ParameterizedType fieldtype = (ParameterizedType) f.getGenericType() ;
// check that this parameterized type satisfies our constraints
try {
parameterizedTypeSanityCheck(fieldtype) ;
}
catch(IllegalArgumentException e) {
// because this Method's parameter fails the sanity check, its probably not an InetAddress related structure
return false ;
}
Class<?> listType = (Class<?>) fieldtype.getActualTypeArguments()[0] ;
return isInetAddressOrCompatibleType(listType) ;
}
else {
// check if the non-parameterized type is InetAddress, InetSocketAddress or IpAddress
Class<?> fieldtype = f.getType() ;
return isInetAddressOrCompatibleType(fieldtype) ;
}
}
/*
* Checks if this method's single parameter represents of of the following:
* an InetAddress, IpAddress or InetSocketAddress or one of
* List<InetAddress>, List<IpAddress> or List<InetSocketAddress>
*/
static boolean isInetAddressRelated(Method m) {
if (hasParameterizedType(m)) {
Type[] types = m.getGenericParameterTypes();
ParameterizedType methodParamType = (ParameterizedType)types[0] ;
// check that this parameterized type satisfies our constraints
try {
parameterizedTypeSanityCheck(methodParamType) ;
}
catch(IllegalArgumentException e) {
if(log.isErrorEnabled()) {
log.error("Method " + m.getName() + " failed paramaterizedTypeSanityCheck()") ;
}
// because this Method's parameter fails the sanity check, its probably not
// an InetAddress related structure
return false ;
}
Class<?> listType = (Class<?>) methodParamType.getActualTypeArguments()[0] ;
return isInetAddressOrCompatibleType(listType) ;
}
else {
Class<?> methodParamType = m.getParameterTypes()[0] ;
return isInetAddressOrCompatibleType(methodParamType) ;
}
}
static boolean isInetAddressOrCompatibleType(Class<?> c) {
return c.equals(InetAddress.class) || c.equals(InetSocketAddress.class) || c.equals(IpAddress.class) ;
}
/*
* Check if the parameterized type represents one of:
* List<InetAddress>, List<IpAddress>, List<InetSocketAddress>
*/
static void parameterizedTypeSanityCheck(ParameterizedType pt) throws IllegalArgumentException {
Type rawType = pt.getRawType() ;
Type[] actualTypes = pt.getActualTypeArguments() ;
// constraints on use of parameterized types with @Property
if (!(rawType instanceof Class<?> && rawType.equals(List.class))) {
throw new IllegalArgumentException("Invalid parameterized type definition - parameterized type must be a List") ;
}
// check for non-parameterized type in List
if (!(actualTypes[0] instanceof Class<?>)) {
throw new IllegalArgumentException("Invalid parameterized type - List must not contain a parameterized type") ;
}
}
/*
* Converts the computedValue to a list of InetAddresses.
* Because computedValues may be null, we need to return
* a zero length list in some cases.
*/
public List<InetAddress> getInetAddresses() {
List<InetAddress> addresses = new ArrayList<InetAddress>() ;
if (getConvertedValue() == null)
return addresses ;
// if we take only an InetAddress argument
if (!isParameterized()) {
addresses.add(getInetAddress(getConvertedValue())) ;
return addresses ;
}
// if we take a List<InetAddress> or similar
else {
List<?> values = (List<?>) getConvertedValue() ;
if (values.isEmpty())
return addresses ;
for (int i = 0; i < values.size(); i++) {
addresses.add(getInetAddress(values.get(i))) ;
}
return addresses ;
}
}
private static InetAddress getInetAddress(Object obj) throws IllegalArgumentException {
if (obj == null)
throw new IllegalArgumentException("Input argument must represent a non-null IP address") ;
if (obj instanceof InetAddress)
return (InetAddress) obj ;
else if (obj instanceof IpAddress)
return ((IpAddress) obj).getIpAddress() ;
else if (obj instanceof InetSocketAddress)
return ((InetSocketAddress) obj).getAddress() ;
else {
if (log.isWarnEnabled())
log.warn("Input argument does not represent one of InetAddress...: class=" + obj.getClass().getName()) ;
throw new IllegalArgumentException("Input argument does not represent one of InetAddress. IpAddress not InetSocketAddress") ;
}
}
public String toString() {
StringBuilder sb = new StringBuilder() ;
sb.append("InetAddressInfo(") ;
sb.append("protocol=" + protocol.getName()) ;
sb.append(", propertyName=" + getPropertyName()) ;
sb.append(", string value=" + getStringValue()) ;
sb.append(", parameterized=" + isParameterized()) ;
if (isParameterized())
sb.append(", baseType=" + getBaseType()) ;
sb.append(")") ;
return sb.toString();
}
}
}
|
package org.jgroups.stack;
import org.jgroups.Event;
import org.jgroups.Global;
import org.jgroups.annotations.DeprecatedProperty;
import org.jgroups.annotations.Property;
import org.jgroups.conf.PropertyHelper;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.TP;
import org.jgroups.stack.ProtocolStack.ProtocolStackFactory;
import org.jgroups.util.StackType;
import org.jgroups.util.Tuple;
import org.jgroups.util.Util;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.*;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
/**
* The task if this class is to setup and configure the protocol stack. A string describing
* the desired setup, which is both the layering and the configuration of each layer, is
* given to the configurator which creates and configures the protocol stack and returns
* a reference to the top layer (Protocol).<p>
* Future functionality will include the capability to dynamically modify the layering
* of the protocol stack and the properties of each layer.
* @author Bela Ban
* @author Richard Achmatowicz
* @version $Id: Configurator.java,v 1.83 2010/09/15 15:42:48 belaban Exp $
*/
public class Configurator implements ProtocolStackFactory {
protected static final Log log=LogFactory.getLog(Configurator.class);
private final ProtocolStack stack;
public Configurator() {
stack = null;
}
public Configurator(ProtocolStack protocolStack) {
stack=protocolStack;
}
public Protocol setupProtocolStack() throws Exception{
return setupProtocolStack(stack.getSetupString(), stack);
}
public Protocol setupProtocolStack(ProtocolStack copySource)throws Exception{
Vector<Protocol> protocols=copySource.copyProtocols(stack);
Collections.reverse(protocols);
return connectProtocols(protocols);
}
private static Protocol setupProtocolStack(String configuration, ProtocolStack st) throws Exception {
Vector<ProtocolConfiguration> protocol_configs=parseConfigurations(configuration);
Vector<Protocol> protocols=createProtocols(protocol_configs, st);
if(protocols == null)
return null;
// basic protocol sanity check
sanityCheck(protocols);
// check InetAddress related features of stack
Map<String, Map<String,InetAddressInfo>> inetAddressMap = createInetAddressMap(protocol_configs, protocols) ;
Collection<InetAddress> addrs=getAddresses(inetAddressMap);
StackType ip_version=Util.getIpStackType(); // 0 = n/a, 4 = IPv4, 6 = IPv6
if(!addrs.isEmpty()) {
// 1. If an addr is IPv6 and we have an IPv4 stack --> FAIL
// 2. If an address is an IPv4 class D (multicast) address and the stack is IPv6: FAIL
// Else pass
for(InetAddress addr: addrs) {
if(addr instanceof Inet6Address && ip_version == StackType.IPv4)
throw new IllegalArgumentException("found IPv6 address " + addr + " in an IPv4 stack");
if(addr instanceof Inet4Address && addr.isMulticastAddress() && ip_version == StackType.IPv6)
throw new Exception("found IPv4 multicast address " + addr + " in an IPv6 stack");
}
}
// process default values
setDefaultValues(protocol_configs, protocols, ip_version) ;
return connectProtocols(protocols);
}
/**
* Creates a new protocol given the protocol specification. Initializes the properties and starts the
* up and down handler threads.
* @param prot_spec The specification of the protocol. Same convention as for specifying a protocol stack.
* An exception will be thrown if the class cannot be created. Example:
* <pre>"VERIFY_SUSPECT(timeout=1500)"</pre> Note that no colons (:) have to be
* specified
* @param stack The protocol stack
* @return Protocol The newly created protocol
* @exception Exception Will be thrown when the new protocol cannot be created
*/
public static Protocol createProtocol(String prot_spec, ProtocolStack stack) throws Exception {
ProtocolConfiguration config;
Protocol prot;
if(prot_spec == null) throw new Exception("Configurator.createProtocol(): prot_spec is null");
// parse the configuration for this protocol
config=new ProtocolConfiguration(prot_spec);
// create an instance of the protocol class and configure it
prot=createLayer(stack, config);
prot.init();
return prot;
}
/**
* Creates a protocol stack by iterating through the protocol list and connecting
* adjacent layers. The list starts with the topmost layer and has the bottommost
* layer at the tail.
* @param protocol_list List of Protocol elements (from top to bottom)
* @return Protocol stack
*/
private static Protocol connectProtocols(Vector<Protocol> protocol_list) {
Protocol current_layer=null, next_layer=null;
for(int i=0; i < protocol_list.size(); i++) {
current_layer=protocol_list.elementAt(i);
if(i + 1 >= protocol_list.size())
break;
next_layer=protocol_list.elementAt(i + 1);
next_layer.setDownProtocol(current_layer);
current_layer.setUpProtocol(next_layer);
if(current_layer instanceof TP) {
TP transport = (TP)current_layer;
if(transport.isSingleton()) {
ConcurrentMap<String, Protocol> up_prots=transport.getUpProtocols();
String key;
synchronized(up_prots) {
while(true) {
key=Global.DUMMY + System.currentTimeMillis();
if(up_prots.containsKey(key))
continue;
up_prots.put(key, next_layer);
break;
}
}
current_layer.setUpProtocol(null);
}
}
}
return current_layer;
}
/**
* Get a string of the form "P1(config_str1):P2:P3(config_str3)" and return
* ProtocolConfigurations for it. That means, parse "P1(config_str1)", "P2" and
* "P3(config_str3)"
* @param config_str Configuration string
* @return Vector of strings
*/
private static Vector<String> parseProtocols(String config_str) throws IOException {
Vector<String> retval=new Vector<String>();
PushbackReader reader=new PushbackReader(new StringReader(config_str));
int ch;
StringBuilder sb;
boolean running=true;
while(running) {
String protocol_name=readWord(reader);
sb=new StringBuilder();
sb.append(protocol_name);
ch=read(reader);
if(ch == -1) {
retval.add(sb.toString());
break;
}
if(ch == ':') { // no attrs defined
retval.add(sb.toString());
continue;
}
if(ch == '(') { // more attrs defined
reader.unread(ch);
String attrs=readUntil(reader, ')');
sb.append(attrs);
retval.add(sb.toString());
}
else {
retval.add(sb.toString());
}
while(true) {
ch=read(reader);
if(ch == ':') {
break;
}
if(ch == -1) {
running=false;
break;
}
}
}
reader.close();
return retval;
}
private static int read(Reader reader) throws IOException {
int ch=-1;
while((ch=reader.read()) != -1) {
if(!Character.isWhitespace(ch))
return ch;
}
return ch;
}
/**
* Return a number of ProtocolConfigurations in a vector
* @param configuration protocol-stack configuration string
* @return Vector of ProtocolConfigurations
*/
public static Vector<ProtocolConfiguration> parseConfigurations(String configuration) throws Exception {
Vector<ProtocolConfiguration> retval=new Vector<ProtocolConfiguration>();
Vector<String> protocol_string=parseProtocols(configuration);
if(protocol_string == null)
return null;
for(String component_string:protocol_string) {
retval.addElement(new ProtocolConfiguration(component_string));
}
return retval;
}
public static String printConfigurations(Collection<ProtocolConfiguration> configs) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(ProtocolConfiguration config: configs) {
if(first)
first=false;
else
sb.append(":");
sb.append(config.getProtocolName());
if(!config.getProperties().isEmpty()) {
sb.append('(').append(config.propertiesToString()).append(')');
}
}
return sb.toString();
}
private static String readUntil(Reader reader, char c) throws IOException {
StringBuilder sb=new StringBuilder();
int ch;
while((ch=read(reader)) != -1) {
sb.append((char)ch);
if(ch == c)
break;
}
return sb.toString();
}
private static String readWord(PushbackReader reader) throws IOException {
StringBuilder sb=new StringBuilder();
int ch;
while((ch=read(reader)) != -1) {
if(Character.isLetterOrDigit(ch) || ch == '_' || ch == '.' || ch == '$') {
sb.append((char)ch);
}
else {
reader.unread(ch);
break;
}
}
return sb.toString();
}
/**
* Takes vector of ProtocolConfigurations, iterates through it, creates Protocol for
* each ProtocolConfiguration and returns all Protocols in a vector.
* @param protocol_configs Vector of ProtocolConfigurations
* @param stack The protocol stack
* @return Vector of Protocols
*/
private static Vector<Protocol> createProtocols(Vector<ProtocolConfiguration> protocol_configs, final ProtocolStack stack) throws Exception {
Vector<Protocol> retval=new Vector<Protocol>();
ProtocolConfiguration protocol_config;
Protocol layer;
String singleton_name;
for(int i=0; i < protocol_configs.size(); i++) {
protocol_config=protocol_configs.elementAt(i);
singleton_name=protocol_config.getProperties().get(Global.SINGLETON_NAME);
if(singleton_name != null && singleton_name.trim().length() > 0) {
Map<String,Tuple<TP, ProtocolStack.RefCounter>> singleton_transports=ProtocolStack.getSingletonTransports();
synchronized(singleton_transports) {
if(i > 0) { // crude way to check whether protocol is a transport
throw new IllegalArgumentException("Property 'singleton_name' can only be used in a transport" +
" protocol (was used in " + protocol_config.getProtocolName() + ")");
}
Tuple<TP, ProtocolStack.RefCounter> val=singleton_transports.get(singleton_name);
layer=val != null? val.getVal1() : null;
if(layer != null) {
retval.add(layer);
}
else {
layer=createLayer(stack, protocol_config);
if(layer == null)
return null;
singleton_transports.put(singleton_name, new Tuple<TP, ProtocolStack.RefCounter>((TP)layer,new ProtocolStack.RefCounter((short)0,(short)0)));
retval.addElement(layer);
}
}
continue;
}
layer=createLayer(stack, protocol_config);
if(layer == null)
return null;
retval.addElement(layer);
}
return retval;
}
protected static Protocol createLayer(ProtocolStack stack, ProtocolConfiguration config) throws Exception {
String protocol_name=config.getProtocolName();
Map<String, String> properties=config.getProperties();
Protocol retval=null;
if(protocol_name == null || properties == null)
return null;
String defaultProtocolName=ProtocolConfiguration.protocol_prefix + '.' + protocol_name;
Class<?> clazz=null;
try {
clazz=Util.loadClass(defaultProtocolName, stack.getClass());
}
catch(ClassNotFoundException e) {
}
if(clazz == null) {
try {
clazz=Util.loadClass(protocol_name, stack.getClass());
}
catch(ClassNotFoundException e) {
}
if(clazz == null) {
throw new Exception("unable to load class for protocol " + protocol_name +
" (either as an absolute - " + protocol_name + " - or relative - " +
defaultProtocolName + " - package name)!");
}
}
try {
retval=(Protocol)clazz.newInstance();
if(retval == null)
throw new Exception("creation of instance for protocol " + protocol_name + "failed !");
retval.setProtocolStack(stack);
removeDeprecatedProperties(retval, properties);
// before processing Field and Method based properties, take dependencies specified
// with @Property.dependsUpon into account
AccessibleObject[] dependencyOrderedFieldsAndMethods = computePropertyDependencies(retval, properties) ;
for(AccessibleObject ordered: dependencyOrderedFieldsAndMethods) {
if (ordered instanceof Field) {
resolveAndAssignField(retval, (Field)ordered, properties) ;
}
else if (ordered instanceof Method) {
resolveAndInvokePropertyMethod(retval, (Method)ordered, properties) ;
}
}
List<Object> additional_objects=retval.getConfigurableObjects();
if(additional_objects != null && !additional_objects.isEmpty()) {
for(Object obj: additional_objects) {
resolveAndAssignFields(obj, properties);
resolveAndInvokePropertyMethods(obj, properties);
}
}
if(!properties.isEmpty()) {
throw new IllegalArgumentException("the following properties in " + protocol_name
+ " are not recognized: " + properties);
}
}
catch(InstantiationException inst_ex) {
log.error("an instance of " + protocol_name + " could not be created. Please check that it implements" +
" interface Protocol and that is has a public empty constructor !");
throw inst_ex;
}
return retval;
}
/**
Throws an exception if sanity check fails. Possible sanity check is uniqueness of all protocol names
*/
public static void sanityCheck(Vector<Protocol> protocols) throws Exception {
Vector<String> names=new Vector<String>();
Protocol prot;
String name;
Vector<ProtocolReq> req_list=new Vector<ProtocolReq>();
// Checks for unique names
for(int i=0; i < protocols.size(); i++) {
prot=protocols.elementAt(i);
name=prot.getName();
for(int j=0; j < names.size(); j++) {
if(name.equals(names.elementAt(j))) {
throw new Exception("Configurator.sanityCheck(): protocol name " + name +
" has been used more than once; protocol names have to be unique !");
}
}
names.addElement(name);
}
// check for unique IDs
Set<Short> ids=new HashSet<Short>();
for(Protocol protocol: protocols) {
short id=protocol.getId();
if(id > 0 && ids.add(id) == false)
throw new Exception("Protocol ID " + id + " (name=" + protocol.getName() +
") is duplicate; protocol IDs have to be unique");
}
// Checks whether all requirements of all layers are met
for(Protocol p:protocols){
req_list.add(new ProtocolReq(p));
}
for(ProtocolReq pr:req_list){
for(Integer evt_type:pr.up_reqs) {
if(!providesDownServices(req_list, evt_type)) {
throw new Exception("Configurator.sanityCheck(): event " +
Event.type2String(evt_type) + " is required by " +
pr.name + ", but not provided by any of the layers above");
}
}
for(Integer evt_type:pr.down_reqs) {
if(!providesUpServices(req_list, evt_type)) {
throw new Exception("Configurator.sanityCheck(): event " +
Event.type2String(evt_type) + " is required by " +
pr.name + ", but not provided by any of the layers above");
}
}
}
}
/**
* Returns all inet addresses found
*/
public static Collection<InetAddress> getAddresses(Map<String, Map<String, InetAddressInfo>> inetAddressMap) throws Exception {
Set<InetAddress> addrs=new HashSet<InetAddress>();
for(Map.Entry<String, Map<String, InetAddressInfo>> inetAddressMapEntry : inetAddressMap.entrySet()) {
Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMapEntry.getValue();
for(Map.Entry<String, InetAddressInfo> protocolInetAddressMapEntry : protocolInetAddressMap.entrySet()) {
InetAddressInfo inetAddressInfo=protocolInetAddressMapEntry.getValue();
// add InetAddressInfo to sets based on IP version
List<InetAddress> addresses=inetAddressInfo.getInetAddresses();
for(InetAddress address : addresses) {
if(address == null)
throw new RuntimeException("This address should not be null! - something is wrong");
addrs.add(address);
}
}
}
return addrs;
}
public static StackType determineIpVersionFromAddresses(Collection<InetAddress> addrs) throws Exception {
Set<InetAddress> ipv4_addrs= new HashSet<InetAddress>() ;
Set<InetAddress> ipv6_addrs= new HashSet<InetAddress>() ;
for(InetAddress address: addrs) {
if (address instanceof Inet4Address)
ipv4_addrs.add(address) ;
else
ipv6_addrs.add(address) ;
}
if(log.isTraceEnabled())
log.trace("all addrs=" + addrs + ", IPv4 addrs=" + ipv4_addrs + ", IPv6 addrs=" + ipv6_addrs);
// the user supplied 1 or more IP address inputs. Check if we have a consistent set
if (!addrs.isEmpty()) {
if (!ipv4_addrs.isEmpty() && !ipv6_addrs.isEmpty()) {
throw new RuntimeException("all addresses have to be either IPv4 or IPv6: IPv4 addresses=" +
ipv4_addrs + ", IPv6 addresses=" + ipv6_addrs);
}
return !ipv6_addrs.isEmpty()? StackType.IPv6 : StackType.IPv4;
}
return StackType.Unknown;
}
/*
* A method which does the following:
* - discovers all Fields or Methods within the protocol stack which set
* InetAddress, IpAddress, InetSocketAddress (and Lists of such) for which the user *has*
* specified a default value.
* - stores the resulting set of Fields and Methods in a map of the form:
* Protocol -> Property -> InetAddressInfo
* where InetAddressInfo instances encapsulate the InetAddress related information
* of the Fields and Methods.
*/
public static Map<String, Map<String,InetAddressInfo>> createInetAddressMap(Vector<ProtocolConfiguration> protocol_configs,
Vector<Protocol> protocols) throws Exception {
// Map protocol -> Map<String, InetAddressInfo>, where the latter is protocol specific
Map<String, Map<String,InetAddressInfo>> inetAddressMap = new HashMap<String, Map<String, InetAddressInfo>>() ;
// collect InetAddressInfo
for (int i = 0; i < protocol_configs.size(); i++) {
ProtocolConfiguration protocol_config = protocol_configs.get(i) ;
Protocol protocol = protocols.get(i) ;
String protocolName = protocol.getName();
// regenerate the Properties which were destroyed during basic property processing
Map<String,String> properties = protocol_config.getOriginalProperties();
// create an InetAddressInfo structure for them
// Method[] methods=protocol.getClass().getMethods();
Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(protocol.getClass(), Property.class);
for(int j = 0; j < methods.length; j++) {
if (methods[j].isAnnotationPresent(Property.class) && isSetPropertyMethod(methods[j])) {
String propertyName = PropertyHelper.getPropertyName(methods[j]) ;
String propertyValue = properties.get(propertyName);
// if there is a systemProperty attribute defined in the annotation, set the property value from the system property
String tmp=grabSystemProp(methods[j].getAnnotation(Property.class));
if(tmp != null)
propertyValue=tmp;
if (propertyValue != null && InetAddressInfo.isInetAddressRelated(methods[j])) {
Object converted = null ;
try {
converted=PropertyHelper.getConvertedValue(protocol, methods[j], properties, propertyValue, false);
}
catch(Exception e) {
throw new Exception("String value could not be converted for method " + propertyName + " in "
+ protocolName + " with default value " + propertyValue + ".Exception is " +e, e);
}
InetAddressInfo inetinfo = new InetAddressInfo(protocol, methods[j], properties, propertyValue, converted) ;
Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMap.get(protocolName);
if(protocolInetAddressMap == null) {
protocolInetAddressMap = new HashMap<String,InetAddressInfo>() ;
inetAddressMap.put(protocolName, protocolInetAddressMap) ;
}
protocolInetAddressMap.put(propertyName, inetinfo) ;
}
}
}
//traverse class hierarchy and find all annotated fields and add them to the list if annotated
for(Class<?> clazz=protocol.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(int j = 0; j < fields.length; j++ ) {
if (fields[j].isAnnotationPresent(Property.class)) {
String propertyName = PropertyHelper.getPropertyName(fields[j], properties) ;
String propertyValue = properties.get(propertyName) ;
// if there is a systemProperty attribute defined in the annotation, set the property value from the system property
String tmp=grabSystemProp(fields[j].getAnnotation(Property.class));
if(tmp != null)
propertyValue=tmp;
if ((propertyValue != null || !PropertyHelper.usesDefaultConverter(fields[j]))
&& InetAddressInfo.isInetAddressRelated(protocol, fields[j])) {
Object converted = null ;
try {
converted=PropertyHelper.getConvertedValue(protocol, fields[j], properties, propertyValue, false);
}
catch(Exception e) {
throw new Exception("String value could not be converted for method " + propertyName + " in "
+ protocolName + " with default value " + propertyValue + ".Exception is " +e, e);
}
InetAddressInfo inetinfo = new InetAddressInfo(protocol, fields[j], properties, propertyValue, converted) ;
Map<String, InetAddressInfo> protocolInetAddressMap=inetAddressMap.get(protocolName);
if(protocolInetAddressMap == null) {
protocolInetAddressMap = new HashMap<String,InetAddressInfo>() ;
inetAddressMap.put(protocolName, protocolInetAddressMap) ;
}
protocolInetAddressMap.put(propertyName, inetinfo) ;
}// recompute
}
}
}
}
return inetAddressMap ;
}
/*
* Method which processes @Property.default() values, associated with the annotation
* using the defaultValue= attribute. This method does the following:
* - locate all properties which have no user value assigned
* - if the defaultValue attribute is not "", generate a value for the field using the
* property converter for that property and assign it to the field
*/
public static void setDefaultValues(Vector<ProtocolConfiguration> protocol_configs, Vector<Protocol> protocols,
StackType ip_version) throws Exception {
InetAddress default_ip_address=Util.getNonLoopbackAddress();
if(default_ip_address == null) {
log.warn("unable to find an address other than loopback for IP version " + ip_version);
default_ip_address=Util.getLocalhost(ip_version);
}
for(int i=0; i < protocol_configs.size(); i++) {
ProtocolConfiguration protocol_config=protocol_configs.get(i);
Protocol protocol=protocols.get(i);
String protocolName=protocol.getName();
// regenerate the Properties which were destroyed during basic property processing
Map<String,String> properties=protocol_config.getOriginalProperties();
Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(protocol.getClass(), Property.class);
for(int j=0; j < methods.length; j++) {
if(isSetPropertyMethod(methods[j])) {
String propertyName=PropertyHelper.getPropertyName(methods[j]);
Object propertyValue=getValueFromProtocol(protocol, propertyName);
if(propertyValue == null) { // if propertyValue is null, check if there is a we can use
Property annotation=methods[j].getAnnotation(Property.class);
// get the default value for the method- check for InetAddress types
String defaultValue=null;
if(InetAddressInfo.isInetAddressRelated(methods[j])) {
defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6();
if(defaultValue != null && defaultValue.length() > 0) {
Object converted=null;
try {
if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS))
converted=default_ip_address;
else
converted=PropertyHelper.getConvertedValue(protocol, methods[j], properties, defaultValue, true);
methods[j].invoke(protocol, converted);
}
catch(Exception e) {
throw new Exception("default could not be assigned for method " + propertyName + " in "
+ protocolName + " with default " + defaultValue, e);
}
if(log.isDebugEnabled())
log.debug("set property " + protocolName + "." + propertyName + " to default value " + converted);
}
}
}
}
}
//traverse class hierarchy and find all annotated fields and add them to the list if annotated
Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), Property.class);
for(int j=0; j < fields.length; j++) {
String propertyName=PropertyHelper.getPropertyName(fields[j], properties);
Object propertyValue=getValueFromProtocol(protocol, fields[j]);
if(propertyValue == null) {
// add to collection of @Properties with no user specified value
Property annotation=fields[j].getAnnotation(Property.class);
// get the default value for the field - check for InetAddress types
String defaultValue=null;
if(InetAddressInfo.isInetAddressRelated(protocol, fields[j])) {
defaultValue=ip_version == StackType.IPv4? annotation.defaultValueIPv4() : annotation.defaultValueIPv6();
if(defaultValue != null && defaultValue.length() > 0) {
// condition for invoking converter
if(defaultValue != null || !PropertyHelper.usesDefaultConverter(fields[j])) {
Object converted=null;
try {
if(defaultValue.equalsIgnoreCase(Global.NON_LOOPBACK_ADDRESS))
converted=default_ip_address;
else
converted=PropertyHelper.getConvertedValue(protocol, fields[j], properties, defaultValue, true);
if(converted != null)
setField(fields[j], protocol, converted);
}
catch(Exception e) {
throw new Exception("default could not be assigned for field " + propertyName + " in "
+ protocolName + " with default value " + defaultValue, e);
}
if(log.isDebugEnabled())
log.debug("set property " + protocolName + "." + propertyName + " to default value " + converted);
}
}
}
}
}
}
}
public static Object getValueFromProtocol(Protocol protocol, Field field) throws IllegalAccessException {
if(protocol == null || field == null) return null;
if(!Modifier.isPublic(field.getModifiers()))
field.setAccessible(true);
return field.get(protocol);
}
public static Object getValueFromProtocol(Protocol protocol, String field_name) throws IllegalAccessException {
if(protocol == null || field_name == null) return null;
Field field=Util.getField(protocol.getClass(), field_name);
return field != null? getValueFromProtocol(protocol, field) : null;
}
/** Check whether any of the protocols 'below' provide evt_type */
static boolean providesUpServices(Vector<ProtocolReq> req_list, int evt_type) {
for (ProtocolReq pr:req_list){
if(pr.providesUpService(evt_type))
return true;
}
return false;
}
/** Checks whether any of the protocols 'above' provide evt_type */
static boolean providesDownServices(Vector<ProtocolReq> req_list, int evt_type) {
for (ProtocolReq pr:req_list){
if(pr.providesDownService(evt_type))
return true;
}
return false;
}
/**
* This method creates a list of all properties (Field or Method) in dependency order,
* where dependencies are specified using the dependsUpon specifier of the Property annotation.
* In particular, it does the following:
* (i) creates a master list of properties
* (ii) checks that all dependency references are present
* (iii) creates a copy of the master list in dependency order
*/
static AccessibleObject[] computePropertyDependencies(Object obj, Map<String,String> properties) {
// List of Fields and Methods of the protocol annotated with @Property
List<AccessibleObject> unorderedFieldsAndMethods = new LinkedList<AccessibleObject>() ;
List<AccessibleObject> orderedFieldsAndMethods = new LinkedList<AccessibleObject>() ;
// Maps property name to property object
Map<String, AccessibleObject> propertiesInventory = new HashMap<String, AccessibleObject>() ;
// get the methods for this class and add them to the list if annotated with @Property
Method[] methods=obj.getClass().getMethods();
for(int i = 0; i < methods.length; i++) {
if (methods[i].isAnnotationPresent(Property.class) && isSetPropertyMethod(methods[i])) {
String propertyName = PropertyHelper.getPropertyName(methods[i]) ;
unorderedFieldsAndMethods.add(methods[i]) ;
propertiesInventory.put(propertyName, methods[i]) ;
}
}
//traverse class hierarchy and find all annotated fields and add them to the list if annotated
for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(int i = 0; i < fields.length; i++ ) {
if (fields[i].isAnnotationPresent(Property.class)) {
String propertyName = PropertyHelper.getPropertyName(fields[i], properties) ;
unorderedFieldsAndMethods.add(fields[i]) ;
// may need to change this based on name parameter of Property
propertiesInventory.put(propertyName, fields[i]) ;
}
}
}
// at this stage, we have all Fields and Methods annotated with @Property
checkDependencyReferencesPresent(unorderedFieldsAndMethods, propertiesInventory) ;
// order the fields and methods by dependency
orderedFieldsAndMethods = orderFieldsAndMethodsByDependency(unorderedFieldsAndMethods, propertiesInventory) ;
// convert to array of Objects
AccessibleObject[] result = new AccessibleObject[orderedFieldsAndMethods.size()] ;
for(int i = 0; i < orderedFieldsAndMethods.size(); i++) {
result[i] = orderedFieldsAndMethods.get(i) ;
}
return result ;
}
static List<AccessibleObject> orderFieldsAndMethodsByDependency(List<AccessibleObject> unorderedList,
Map<String, AccessibleObject> propertiesMap) {
// Stack to detect cycle in depends relation
Stack<AccessibleObject> stack = new Stack<AccessibleObject>() ;
// the result list
List<AccessibleObject> orderedList = new LinkedList<AccessibleObject>() ;
// add the elements from the unordered list to the ordered list
// any dependencies will be checked and added first, in recursive manner
for(int i = 0; i < unorderedList.size(); i++) {
AccessibleObject obj = unorderedList.get(i) ;
addPropertyToDependencyList(orderedList, propertiesMap, stack, obj) ;
}
return orderedList ;
}
/**
* DFS of dependency graph formed by Property annotations and dependsUpon parameter
* This is used to create a list of Properties in dependency order
*/
static void addPropertyToDependencyList(List<AccessibleObject> orderedList, Map<String, AccessibleObject> props, Stack<AccessibleObject> stack, AccessibleObject obj) {
if (orderedList.contains(obj))
return ;
if (stack.search(obj) > 0) {
throw new RuntimeException("Deadlock in @Property dependency processing") ;
}
// record the fact that we are processing obj
stack.push(obj) ;
// process dependencies for this object before adding it to the list
Property annotation = obj.getAnnotation(Property.class) ;
String dependsClause = annotation.dependsUpon() ;
StringTokenizer st = new StringTokenizer(dependsClause, ",") ;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
AccessibleObject dep = props.get(token) ;
// if null, throw exception
addPropertyToDependencyList(orderedList, props, stack, dep) ;
}
// indicate we're done with processing dependencies
stack.pop() ;
// we can now add in dependency order
orderedList.add(obj) ;
}
/*
* Checks that for every dependency referred, there is a matching property
*/
static void checkDependencyReferencesPresent(List<AccessibleObject> objects, Map<String, AccessibleObject> props) {
// iterate overall properties marked by @Property
for(int i = 0; i < objects.size(); i++) {
// get the Property annotation
AccessibleObject ao = objects.get(i) ;
Property annotation = ao.getAnnotation(Property.class) ;
if (annotation == null) {
throw new IllegalArgumentException("@Property annotation is required for checking dependencies;" +
" annotation is missing for Field/Method " + ao.toString()) ;
}
String dependsClause = annotation.dependsUpon() ;
if (dependsClause.trim().length() == 0)
continue ;
// split dependsUpon specifier into tokens; trim each token; search for token in list
StringTokenizer st = new StringTokenizer(dependsClause, ",") ;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim() ;
// check that the string representing a property name is in the list
boolean found = false ;
Set<String> keyset = props.keySet();
for (Iterator<String> iter = keyset.iterator(); iter.hasNext();) {
if (iter.next().equals(token)) {
found = true ;
break ;
}
}
if (!found) {
throw new IllegalArgumentException("@Property annotation " + annotation.name() +
" has an unresolved dependsUpon property: " + token) ;
}
}
}
}
public static void resolveAndInvokePropertyMethods(Object obj, Map<String,String> props) throws Exception {
Method[] methods=obj.getClass().getMethods();
for(Method method: methods) {
resolveAndInvokePropertyMethod(obj, method, props) ;
}
}
public static void resolveAndInvokePropertyMethod(Object obj, Method method, Map<String,String> props) throws Exception {
String methodName=method.getName();
Property annotation=method.getAnnotation(Property.class);
if(annotation != null && isSetPropertyMethod(method)) {
String propertyName=PropertyHelper.getPropertyName(method) ;
String propertyValue=props.get(propertyName);
// if there is a systemProperty attribute defined in the annotation, set the property value from the system property
String tmp=grabSystemProp(method.getAnnotation(Property.class));
if(tmp != null)
propertyValue=tmp;
if(propertyName != null && propertyValue != null) {
String deprecated_msg=annotation.deprecatedMessage();
if(deprecated_msg != null && deprecated_msg.length() > 0) {
log.warn(method.getDeclaringClass().getSimpleName() + "." + methodName + ": " + deprecated_msg);
}
}
if(propertyValue != null) {
Object converted=null;
try {
converted=PropertyHelper.getConvertedValue(obj, method, props, propertyValue, true);
method.invoke(obj, converted);
}
catch(Exception e) {
String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName();
throw new Exception("Could not assign property " + propertyName + " in "
+ name + ", method is " + methodName + ", converted value is " + converted, e);
}
}
props.remove(propertyName);
}
}
public static void resolveAndAssignFields(Object obj, Map<String,String> props) throws Exception {
//traverse class hierarchy and find all annotated fields
for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
Field[] fields=clazz.getDeclaredFields();
for(Field field: fields) {
resolveAndAssignField(obj, field, props) ;
}
}
}
public static void resolveAndAssignField(Object obj, Field field, Map<String,String> props) throws Exception {
Property annotation=field.getAnnotation(Property.class);
if(annotation != null) {
String propertyName = PropertyHelper.getPropertyName(field, props) ;
String propertyValue=props.get(propertyName);
// if there is a systemProperty attribute defined in the annotation, set the property value from the system property
String tmp=grabSystemProp(field.getAnnotation(Property.class));
if(tmp != null)
propertyValue=tmp;
if(propertyName != null && propertyValue != null) {
String deprecated_msg=annotation.deprecatedMessage();
if(deprecated_msg != null && deprecated_msg.length() > 0) {
log.warn(field.getDeclaringClass().getSimpleName() + "." + field.getName() + ": " + deprecated_msg);
}
}
if(propertyValue != null || !PropertyHelper.usesDefaultConverter(field)){
Object converted=null;
try {
converted=PropertyHelper.getConvertedValue(obj, field, props, propertyValue, true);
if(converted != null)
setField(field, obj, converted);
}
catch(Exception e) {
String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName();
throw new Exception("Property assignment of " + propertyName + " in "
+ name + " with original property value " + propertyValue + " and converted to " + converted
+ " could not be assigned", e);
}
}
props.remove(propertyName);
}
}
public static void removeDeprecatedProperties(Object obj, Map<String,String> props) throws Exception {
//traverse class hierarchy and find all deprecated properties
for(Class<?> clazz=obj.getClass(); clazz != null; clazz=clazz.getSuperclass()) {
if(clazz.isAnnotationPresent(DeprecatedProperty.class)) {
DeprecatedProperty declaredAnnotation=clazz.getAnnotation(DeprecatedProperty.class);
String[] deprecatedProperties=declaredAnnotation.names();
for(String propertyName : deprecatedProperties) {
String propertyValue=props.get(propertyName);
if(propertyValue != null) {
if(log.isWarnEnabled()) {
String name=obj instanceof Protocol? ((Protocol)obj).getName() : obj.getClass().getName();
log.warn(name + " property " + propertyName + " was deprecated and is ignored");
}
props.remove(propertyName);
}
}
}
}
}
public static boolean isSetPropertyMethod(Method method) {
return (method.getName().startsWith("set") &&
method.getReturnType() == java.lang.Void.TYPE &&
method.getParameterTypes().length == 1);
}
public static void setField(Field field, Object target, Object value) {
if(!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
}
try {
field.set(target, value);
}
catch(IllegalAccessException iae) {
throw new IllegalArgumentException("Could not set field " + field, iae);
}
}
public static Object getField(Field field, Object target) {
if(!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
}
try {
return field.get(target);
}
catch(IllegalAccessException iae) {
throw new IllegalArgumentException("Could not get field " + field, iae);
}
}
private static String grabSystemProp(Property annotation) {
String[] system_property_names=annotation.systemProperty();
String retval=null;
for(String system_property_name: system_property_names) {
if(system_property_name != null && system_property_name.length() > 0) {
if(system_property_name.equals(Global.BIND_ADDR) || system_property_name.equals(Global.BIND_ADDR_OLD))
if(Util.isBindAddressPropertyIgnored())
continue;
try {
retval=System.getProperty(system_property_name);
if(retval != null)
return retval;
}
catch(SecurityException ex) {
log.error("failed getting system property for " + system_property_name, ex);
}
}
}
return retval;
}
private static class ProtocolReq {
final Vector<Integer> up_reqs=new Vector<Integer>();
final Vector<Integer> down_reqs=new Vector<Integer>();
final Vector<Integer> up_provides=new Vector<Integer>();
final Vector<Integer> down_provides=new Vector<Integer>();
final String name;
ProtocolReq(Protocol p) {
this.name=p.getName();
if(p.requiredUpServices() != null) {
up_reqs.addAll(p.requiredUpServices());
}
if(p.requiredDownServices() != null) {
down_reqs.addAll(p.requiredDownServices());
}
if(p.providedUpServices() != null) {
up_provides.addAll(p.providedUpServices());
}
if(p.providedDownServices() != null) {
down_provides.addAll(p.providedDownServices());
}
}
boolean providesUpService(int evt_type) {
for(Integer type:up_provides) {
if(type == evt_type)
return true;
}
return false;
}
boolean providesDownService(int evt_type) {
for(Integer type:down_provides) {
if(type == evt_type)
return true;
}
return false;
}
public String toString() {
StringBuilder ret=new StringBuilder();
ret.append('\n' + name + ':');
if(!up_reqs.isEmpty())
ret.append("\nRequires from above: " + printUpReqs());
if(!down_reqs.isEmpty())
ret.append("\nRequires from below: " + printDownReqs());
if(!up_provides.isEmpty())
ret.append("\nProvides to above: " + printUpProvides());
if(!down_provides.isEmpty())
ret.append("\nProvides to below: ").append(printDownProvides());
return ret.toString();
}
String printUpReqs() {
StringBuilder ret;
ret=new StringBuilder("[");
for(Integer type:up_reqs) {
ret.append(Event.type2String(type) + ' ');
}
return ret.toString() + ']';
}
String printDownReqs() {
StringBuilder ret=new StringBuilder("[");
for(Integer type:down_reqs) {
ret.append(Event.type2String(type) + ' ');
}
return ret.toString() + ']';
}
String printUpProvides() {
StringBuilder ret=new StringBuilder("[");
for(Integer type:up_provides) {
ret.append(Event.type2String(type) + ' ');
}
return ret.toString() + ']';
}
String printDownProvides() {
StringBuilder ret=new StringBuilder("[");
for(Integer type:down_provides) {
ret.append(Event.type2String(type) + ' ');
}
return ret.toString() + ']';
}
}
/**
* Parses and encapsulates the specification for 1 protocol of the protocol stack, e.g.
* <code>UNICAST(timeout=5000)</code>
*/
public static class ProtocolConfiguration {
private final String protocol_name;
private String properties_str;
private final Map<String,String> properties=new HashMap<String,String>();
public static final String protocol_prefix="org.jgroups.protocols";
/**
* Creates a new ProtocolConfiguration.
* @param config_str The configuration specification for the protocol, e.g.
* <pre>VERIFY_SUSPECT(timeout=1500)</pre>
*/
public ProtocolConfiguration(String config_str) throws Exception {
int index=config_str.indexOf('('); // e.g. "UDP(in_port=3333)"
int end_index=config_str.lastIndexOf(')');
if(index == -1) {
protocol_name=config_str;
properties_str="";
}
else {
if(end_index == -1) {
throw new Exception("Configurator.ProtocolConfiguration(): closing ')' " +
"not found in " + config_str + ": properties cannot be set !");
}
else {
properties_str=config_str.substring(index + 1, end_index);
protocol_name=config_str.substring(0, index);
}
}
parsePropertiesString(properties_str, properties) ;
}
public String getProtocolName() {
return protocol_name;
}
public Map<String, String> getProperties() {
return properties;
}
public Map<String, String> getOriginalProperties() throws Exception {
Map<String,String> props = new HashMap<String,String>();
parsePropertiesString(properties_str, props) ;
return props ;
}
private void parsePropertiesString(String properties_str, Map<String, String> properties) throws Exception {
int index = 0 ;
/* "in_port=5555;out_port=6666" */
if(properties_str.length() > 0) {
String[] components=properties_str.split(";");
for(String property : components) {
String name, value;
index=property.indexOf('=');
if(index == -1) {
throw new Exception("Configurator.ProtocolConfiguration(): '=' not found in " + property
+ " of " + protocol_name);
}
name=property.substring(0, index);
value=property.substring(index + 1, property.length());
properties.put(name, value);
}
}
}
public void substituteVariables() {
for(Iterator<Map.Entry<String,String>> it=properties.entrySet().iterator(); it.hasNext();) {
Map.Entry<String,String> entry=it.next();
String key=entry.getKey();
String val=entry.getValue();
String tmp=Util.substituteVariable(val);
if(!val.equals(tmp)) {
properties.put(key,tmp);
}
else {
if(tmp.contains("${")) {
if(log.isWarnEnabled())
log.warn("variable \"" + val + "\" in " + protocol_name + " could not be substituted; " +
key + " is removed from properties");
it.remove();
}
}
}
properties_str=propertiesToString();
}
public String toString() {
StringBuilder retval=new StringBuilder();
if(protocol_name == null)
retval.append("<unknown>");
else
retval.append(protocol_name);
if(properties != null)
retval.append("(" + Util.print(properties) + ')');
return retval.toString();
}
public String propertiesToString() {
return Util.printMapWithDelimiter(properties, ";");
}
}
public static class InetAddressInfo {
Protocol protocol ;
AccessibleObject fieldOrMethod ;
Map<String,String> properties ;
String propertyName ;
String stringValue ;
Object convertedValue ;
boolean isField ;
boolean isParameterized ; // is the associated type parametrized? (e.g. Collection<String>)
Object baseType ; // what is the base type (e.g. Collection)
InetAddressInfo(Protocol protocol, AccessibleObject fieldOrMethod, Map<String,String> properties, String stringValue,
Object convertedValue) {
// check input values
if (protocol == null) {
throw new IllegalArgumentException("Protocol for Field/Method must be non-null") ;
}
if (fieldOrMethod instanceof Field) {
isField = true ;
} else if (fieldOrMethod instanceof Method) {
isField = false ;
} else
throw new IllegalArgumentException("AccesibleObject is neither Field nor Method") ;
if (properties == null) {
throw new IllegalArgumentException("Properties for Field/Method must be non-null") ;
}
// set the values passed by the user - need to check for null
this.protocol = protocol ;
this.fieldOrMethod = fieldOrMethod ;
this.properties = properties ;
this.stringValue = stringValue ;
this.convertedValue = convertedValue ;
// set the property name
Property annotation=fieldOrMethod.getAnnotation(Property.class);
if (isField())
propertyName=PropertyHelper.getPropertyName((Field)fieldOrMethod, properties) ;
else
propertyName=PropertyHelper.getPropertyName((Method)fieldOrMethod) ;
// is variable type parameterized
this.isParameterized = false ;
if (isField())
this.isParameterized = hasParameterizedType((Field)fieldOrMethod) ;
else
this.isParameterized = hasParameterizedType((Method)fieldOrMethod) ;
// if parameterized, what is the base type?
this.baseType = null ;
if (isField() && isParameterized) {
// the Field has a single type
ParameterizedType fpt = (ParameterizedType)((Field)fieldOrMethod).getGenericType() ;
this.baseType = fpt.getActualTypeArguments()[0] ;
}
else if (!isField() && isParameterized) {
// the Method has several parameters (and so types)
Type[] types = (Type[])((Method)fieldOrMethod).getGenericParameterTypes();
ParameterizedType mpt = (ParameterizedType) types[0] ;
this.baseType = mpt.getActualTypeArguments()[0] ;
}
}
// Protocol getProtocol() {return protocol ;}
Object getProtocol() {return protocol ;}
AccessibleObject getFieldOrMethod() {return fieldOrMethod ;}
boolean isField() { return isField ; }
String getStringValue() {return stringValue ;}
String getPropertyName() {return propertyName ;}
Map<String,String> getProperties() {return properties ;}
Object getConvertedValue() {return convertedValue ;}
boolean isParameterized() {return isParameterized ;}
Object getBaseType() { return baseType ;}
static boolean hasParameterizedType(Field f) {
if (f == null) {
throw new IllegalArgumentException("Field argument is null") ;
}
Type type = f.getGenericType();
return (type instanceof ParameterizedType) ;
}
static boolean hasParameterizedType(Method m) throws IllegalArgumentException {
if (m == null) {
throw new IllegalArgumentException("Method argument is null") ;
}
Type[] types = m.getGenericParameterTypes() ;
return (types[0] instanceof ParameterizedType) ;
}
static boolean isInetAddressRelated(Protocol prot, Field f) {
if (hasParameterizedType(f)) {
// check for List<InetAddress>, List<InetSocketAddress>, List<IpAddress>
ParameterizedType fieldtype = (ParameterizedType) f.getGenericType() ;
// check that this parameterized type satisfies our constraints
try {
parameterizedTypeSanityCheck(fieldtype) ;
}
catch(IllegalArgumentException e) {
// because this Method's parameter fails the sanity check, its probably not an InetAddress related structure
return false ;
}
Class<?> listType = (Class<?>) fieldtype.getActualTypeArguments()[0] ;
return isInetAddressOrCompatibleType(listType) ;
}
else {
// check if the non-parameterized type is InetAddress, InetSocketAddress or IpAddress
Class<?> fieldtype = f.getType() ;
return isInetAddressOrCompatibleType(fieldtype) ;
}
}
/*
* Checks if this method's single parameter represents of of the following:
* an InetAddress, IpAddress or InetSocketAddress or one of
* List<InetAddress>, List<IpAddress> or List<InetSocketAddress>
*/
static boolean isInetAddressRelated(Method m) {
if (hasParameterizedType(m)) {
Type[] types = m.getGenericParameterTypes();
ParameterizedType methodParamType = (ParameterizedType)types[0] ;
// check that this parameterized type satisfies our constraints
try {
parameterizedTypeSanityCheck(methodParamType) ;
}
catch(IllegalArgumentException e) {
if(log.isErrorEnabled()) {
log.error("Method " + m.getName() + " failed paramaterizedTypeSanityCheck()") ;
}
// because this Method's parameter fails the sanity check, its probably not
// an InetAddress related structure
return false ;
}
Class<?> listType = (Class<?>) methodParamType.getActualTypeArguments()[0] ;
return isInetAddressOrCompatibleType(listType) ;
}
else {
Class<?> methodParamType = m.getParameterTypes()[0] ;
return isInetAddressOrCompatibleType(methodParamType) ;
}
}
static boolean isInetAddressOrCompatibleType(Class<?> c) {
return c.equals(InetAddress.class) || c.equals(InetSocketAddress.class) || c.equals(IpAddress.class) ;
}
/*
* Check if the parameterized type represents one of:
* List<InetAddress>, List<IpAddress>, List<InetSocketAddress>
*/
static void parameterizedTypeSanityCheck(ParameterizedType pt) throws IllegalArgumentException {
Type rawType = pt.getRawType() ;
Type[] actualTypes = pt.getActualTypeArguments() ;
// constraints on use of parameterized types with @Property
if (!(rawType instanceof Class<?> && rawType.equals(List.class))) {
throw new IllegalArgumentException("Invalid parameterized type definition - parameterized type must be a List") ;
}
// check for non-parameterized type in List
if (!(actualTypes[0] instanceof Class<?>)) {
throw new IllegalArgumentException("Invalid parameterized type - List must not contain a parameterized type") ;
}
}
/*
* Converts the computedValue to a list of InetAddresses.
* Because computedValues may be null, we need to return
* a zero length list in some cases.
*/
public List<InetAddress> getInetAddresses() {
List<InetAddress> addresses = new ArrayList<InetAddress>() ;
if (getConvertedValue() == null)
return addresses ;
// if we take only an InetAddress argument
if (!isParameterized()) {
addresses.add(getInetAddress(getConvertedValue())) ;
return addresses ;
}
// if we take a List<InetAddress> or similar
else {
List<?> values = (List<?>) getConvertedValue() ;
if (values.isEmpty())
return addresses ;
for (int i = 0; i < values.size(); i++) {
addresses.add(getInetAddress(values.get(i))) ;
}
return addresses ;
}
}
private static InetAddress getInetAddress(Object obj) throws IllegalArgumentException {
if (obj == null)
throw new IllegalArgumentException("Input argument must represent a non-null IP address") ;
if (obj instanceof InetAddress)
return (InetAddress) obj ;
else if (obj instanceof IpAddress)
return ((IpAddress) obj).getIpAddress() ;
else if (obj instanceof InetSocketAddress)
return ((InetSocketAddress) obj).getAddress() ;
else {
if (log.isWarnEnabled())
log.warn("Input argument does not represent one of InetAddress...: class=" + obj.getClass().getName()) ;
throw new IllegalArgumentException("Input argument does not represent one of InetAddress. IpAddress not InetSocketAddress") ;
}
}
public String toString() {
StringBuilder sb = new StringBuilder() ;
sb.append("InetAddressInfo(") ;
sb.append("protocol=" + protocol.getName()) ;
sb.append(", propertyName=" + getPropertyName()) ;
sb.append(", string value=" + getStringValue()) ;
sb.append(", parameterized=" + isParameterized()) ;
if (isParameterized())
sb.append(", baseType=" + getBaseType()) ;
sb.append(")") ;
return sb.toString();
}
}
}
|
package hdm.pk070.jscheme.eval;
import hdm.pk070.jscheme.error.SchemeError;
import hdm.pk070.jscheme.obj.SchemeObject;
import hdm.pk070.jscheme.obj.builtin.simple.SchemeCons;
import hdm.pk070.jscheme.obj.builtin.simple.SchemeSymbol;
import hdm.pk070.jscheme.reader.SchemeReader;
import hdm.pk070.jscheme.table.environment.Environment;
import hdm.pk070.jscheme.table.environment.entry.EnvironmentEntry;
/**
* This class constitutes the JScheme entry point for evaluating the {@link SchemeObject}s returned by
* {@link SchemeReader}. It checks the type of the incoming expression and invokes the
* corresponding {@link AbstractEvaluator} implementation or simply returns the object in case it evaluates to itself.
*
* @author patrick.kleindienst
*/
public class SchemeEval {
public static SchemeEval getInstance() {
return new SchemeEval();
}
private SchemeEval() {
}
/**
* Gets passed an expression by the {@link SchemeReader} and hands it on to a specialized evaluation class
* according to the expression type.
*
* @param expression
* The expression to evaluate as passed by {@link SchemeReader}.
* @param environment
* The evaluation context.
* @return A {@link SchemeObject} as evaluation result.
* @throws SchemeError
* If evaluation fails for some reason.
*/
public SchemeObject eval(SchemeObject expression, Environment<SchemeSymbol, EnvironmentEntry> environment) throws
SchemeError {
if (expression.typeOf(SchemeSymbol.class)) {
return SymbolEvaluator.getInstance().doEval(((SchemeSymbol) expression), environment);
} else if (expression.typeOf(SchemeCons.class)) {
return ListEvaluator.getInstance().doEval(((SchemeCons) expression), environment);
} else {
// Return expression without further evaluation in all the other cases.
return expression;
}
}
}
|
package org.jgroups.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.Global;
import java.util.concurrent.*;
/**
* Fixed-delay & fixed-rate single thread scheduler
* <p/>
* The scheduler supports varying scheduling intervals by asking the task
* every time for its next preferred scheduling interval. Scheduling can
* either be <i>fixed-delay</i> or <i>fixed-rate</i>. The notions are
* borrowed from <tt>java.util.Timer</tt> and retain the same meaning.
* I.e. in fixed-delay scheduling, the task's new schedule is calculated
* as:<br>
* new_schedule = time_task_starts + scheduling_interval
* <p/>
* In fixed-rate scheduling, the next schedule is calculated as:<br>
* new_schedule = time_task_was_supposed_to_start + scheduling_interval
* <p/>
* The scheduler internally holds a queue of tasks sorted in ascending order
* according to their next execution time. A task is removed from the queue
* if it is cancelled, i.e. if <tt>TimeScheduler.Task.isCancelled()</tt>
* returns true.
* <p/>
* The scheduler internally uses a <tt>java.util.SortedSet</tt> to keep tasks
* sorted. <tt>java.util.Timer</tt> uses an array arranged as a binary heap
* that doesn't shrink. It is likely that the latter arrangement is faster.
* <p/>
* Initially, the scheduler is in <tt>SUSPEND</tt>ed mode, <tt>start()</tt>
* need not be called: if a task is added, the scheduler gets started
* automatically. Calling <tt>start()</tt> starts the scheduler if it's
* suspended or stopped else has no effect. Once <tt>stop()</tt> is called,
* added tasks will not restart it: <tt>start()</tt> has to be called to
* restart the scheduler.
* @author Bela Ban
* @version $Id: TimeScheduler.java,v 1.18 2007/03/13 08:36:22 belaban Exp $
*/
public class TimeScheduler extends ScheduledThreadPoolExecutor {
/** The interface that submitted tasks must implement */
public interface Task extends Runnable {
/** @return the next schedule interval. If <= 0 the task will not be re-scheduled */
long nextInterval();
/** Execute the task */
void run();
}
/** Number of milliseconds to wait for pool termination after shutdown */
private static final long TERMINATION_TIMEOUT=5000;
/** How many core threads */
private static int TIMER_DEFAULT_NUM_THREADS=3;
protected static final Log log=LogFactory.getLog(TimeScheduler.class);
static {
String tmp;
try {
tmp=System.getProperty(Global.TIMER_NUM_THREADS);
if(tmp != null)
TIMER_DEFAULT_NUM_THREADS=Integer.parseInt(tmp);
}
catch(Exception e) {
log.error("could not set number of timer threads", e);
}
}
/**
* Create a scheduler that executes tasks in dynamically adjustable intervals
*/
public TimeScheduler() {
this(TIMER_DEFAULT_NUM_THREADS);
}
public TimeScheduler(ThreadFactory factory) {
super(TIMER_DEFAULT_NUM_THREADS, factory);
}
public TimeScheduler(int corePoolSize) {
super(corePoolSize);
}
public String dumpTaskQueue() {
return getQueue().toString();
}
/**
* Schedule a task for execution at varying intervals. After execution, the task will get rescheduled after
* {@link org.jgroups.util.TimeScheduler.Task#nextInterval()} milliseconds. The task is neve done until nextInterval()
* return a value <= 0 or the task is cancelled.
* @param task the task to execute
* @param relative scheduling scheme: <tt>true</tt>:<br>
* Task is rescheduled relative to the last time it <i>actually</i> started execution<p/>
* <tt>false</tt>:<br> Task is scheduled relative to its <i>last</i> execution schedule. This has the effect
* that the time between two consecutive executions of the task remains the same.<p/>
* Note that relative is always true; we always schedule the next execution relative to the last *actual*
* (not scheduled) execution
*/
public ScheduledFuture<?> scheduleWithDynamicInterval(Task task, boolean relative) {
if(task == null)
throw new NullPointerException();
if (isShutdown())
return null;
TaskWrapper task_wrapper=new TaskWrapper(task);
task_wrapper.doSchedule(); // calls schedule() in ScheduledThreadPoolExecutor
return new FutureWrapper(task_wrapper);
}
/**
* Add a task for execution at adjustable intervals
* @param t the task to execute
*/
public ScheduledFuture<?> scheduleWithDynamicInterval(Task t) {
return scheduleWithDynamicInterval(t, true);
}
/**
* Answers the number of tasks currently in the queue.
* @return The number of tasks currently in the queue.
*/
public int size() {
return getQueue().size();
}
/**
* Start the scheduler, if it's suspended or stopped
*/
public void start() {
;
}
/**
* Stop the scheduler if it's running. Switch to stopped, if it's
* suspended. Clear the task queue.
*
* @throws InterruptedException if interrupted while waiting for thread
* to return
*/
public void stop() throws InterruptedException {
shutdownNow();
awaitTermination(TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS);
}
private class TaskWrapper implements Runnable {
Task task;
ScheduledFuture<?> future; // cannot be null !
public TaskWrapper(Task task) {
this.task=task;
}
public ScheduledFuture<?> getFuture() {
return future;
}
public void run() {
try {
if(future != null && future.isCancelled())
return;
task.run();
}
catch(Throwable t) {
log.error("failed running task " + task, t);
}
if(!future.isCancelled()) {
doSchedule();
}
}
public void doSchedule() {
long next_interval=task.nextInterval();
if(next_interval <= 0) {
if(log.isTraceEnabled())
log.trace("task will not get rescheduled as interval is " + next_interval);
}
else {
future=schedule(this, next_interval, TimeUnit.MILLISECONDS);
}
}
}
private static class FutureWrapper<V> implements ScheduledFuture<V> {
TaskWrapper task_wrapper;
public FutureWrapper(TaskWrapper task_wrapper) {
this.task_wrapper=task_wrapper;
}
public long getDelay(TimeUnit unit) {
ScheduledFuture future=task_wrapper.getFuture();
return future != null? future.getDelay(unit) : -1;
}
public int compareTo(Delayed o) {
ScheduledFuture future=task_wrapper.getFuture();
return future != null? future.compareTo(o) : -1;
}
public boolean cancel(boolean mayInterruptIfRunning) {
ScheduledFuture future=task_wrapper.getFuture();
return future != null && future.cancel(mayInterruptIfRunning);
}
public boolean isCancelled() {
ScheduledFuture future=task_wrapper.getFuture();
return future != null && future.isCancelled();
}
public boolean isDone() {
ScheduledFuture future=task_wrapper.getFuture();
return future == null || future.isDone();
}
public V get() throws InterruptedException, ExecutionException {
return null;
}
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return null;
}
}
}
|
package hudson.plugins.ws_cleanup;
import java.io.Serializable;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* @author <a href="mailto:nicolas.deloof@cloudbees.com">Nicolas De loof</a>
*/
public class Pattern implements Serializable{
private final String pattern;
@DataBoundConstructor
public Pattern(String pattern) {
this.pattern = pattern;
}
public String getPattern() {
return pattern;
}
private static final long serialVerisonUID = 1L;
}
|
package org.kelly_ann;
import net.webservicex.GeoIP;
import net.webservicex.GeoIPService;
import net.webservicex.GeoIPServiceSoap;
public class IPLocationFinder
{
public static void main(String[] args)
{
if (args.length != 1)
{
System.out.println("Please pass in an IP address.");
}
else
{
// GeoIPService is in the <wsdl:service> in the wsdl's XML.
// GeoIPServiceSoap is in the <wsdl:port> within the <wsdl:service> XML tags in the wsdl.
// GeoIP is the actual IP object with the information about the IP.
// sample IP's to pass in as an arg: bbc.com = 70.126.135.19 OR google.com = 74.125.239.142
String ipAddress = args[0];
GeoIPService ipService = new GeoIPService();
GeoIPServiceSoap geoIPServiceSoap = ipService.getGeoIPServiceSoap();
GeoIP geoIP = geoIPServiceSoap.getGeoIP(ipAddress);
System.out.println(geoIP.getCountryName());
}
}
}
|
package hudson.remoting;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.List;
import java.util.ArrayList;
/**
* Loads class files from the other peer through {@link Channel}.
*
* @author Kohsuke Kawaguchi
*/
final class RemoteClassLoader extends ClassLoader {
private final IClassLoader proxy;
private final Map<String,URL> resourceMap = new HashMap<String,URL>();
private final Map<String,Vector<URL>> resourcesMap = new HashMap<String,Vector<URL>>();
public RemoteClassLoader(ClassLoader parent, IClassLoader proxy) {
super(parent);
this.proxy = proxy;
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] bytes = proxy.fetch(name);
return defineClass(name, bytes, 0, bytes.length);
}
protected URL findResource(String name) {
if(resourceMap.containsKey(name))
return resourceMap.get(name);
try {
byte[] image = proxy.getResource(name);
if(image==null) {
resourceMap.put(name,null);
return null;
}
URL url = makeResource(name, image);
resourceMap.put(name,url);
return url;
} catch (IOException e) {
throw new Error("Unable to load resource "+name,e);
}
}
protected Enumeration<URL> findResources(String name) throws IOException {
Vector<URL> urls = resourcesMap.get(name);
if(urls!=null)
return urls.elements();
byte[][] images = proxy.getResources(name);
urls = new Vector<URL>();
for( byte[] image: images )
urls.add(makeResource(name,image));
resourcesMap.put(name,urls);
return urls.elements();
}
private URL makeResource(String name, byte[] image) throws IOException {
int idx = name.lastIndexOf('/');
File f = File.createTempFile("hudson-remoting","."+name.substring(idx+1));
FileOutputStream fos = new FileOutputStream(f);
fos.write(image);
fos.close();
f.deleteOnExit();
return f.toURL();
}
/**
* Remoting interface.
*/
/*package*/ static interface IClassLoader {
byte[] fetch(String className) throws ClassNotFoundException;
byte[] getResource(String name) throws IOException;
byte[][] getResources(String name) throws IOException;
}
public static IClassLoader export(ClassLoader cl, Channel local) {
return local.export(IClassLoader.class, new ClassLoaderProxy(cl));
}
/**
* Exports and just returns the object ID, instead of obtaining the proxy.
*/
static int exportId(ClassLoader cl, Channel local) {
return local.export(new ClassLoaderProxy(cl));
}
/*package*/ static final class ClassLoaderProxy implements IClassLoader {
private final ClassLoader cl;
public ClassLoaderProxy(ClassLoader cl) {
this.cl = cl;
}
public byte[] fetch(String className) throws ClassNotFoundException {
InputStream in = cl.getResourceAsStream(className.replace('.', '/') + ".class");
if(in==null)
throw new ClassNotFoundException();
try {
return readFully(in);
} catch (IOException e) {
throw new ClassNotFoundException();
}
}
public byte[] getResource(String name) throws IOException {
InputStream in = cl.getResourceAsStream(name);
if(in==null) return null;
return readFully(in);
}
public byte[][] getResources(String name) throws IOException {
List<byte[]> images = new ArrayList<byte[]>();
Enumeration<URL> e = cl.getResources(name);
while(e.hasMoreElements()) {
images.add(readFully(e.nextElement().openStream()));
}
return images.toArray(new byte[images.size()][]);
}
private byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>0)
baos.write(buf,0,len);
in.close();
return baos.toByteArray();
}
public boolean equals(Object that) {
if (this == that) return true;
if (that == null || getClass() != that.getClass()) return false;
return cl.equals(((ClassLoaderProxy) that).cl);
}
public int hashCode() {
return cl.hashCode();
}
}
}
|
package org.lockss.daemon;
import java.io.*;
import java.util.*;
import org.lockss.app.*;
import org.lockss.util.*;
/** LockssThread abstracts out common features of LOCKSS daemon threads,
* notably watchdog timers. The methods in this class should be called
* only from the thread.
*/
public abstract class LockssThread extends Thread implements LockssWatchdog {
static final String PREFIX = Configuration.PREFIX + "thread.";
static final String PARAM_THREAD_WDOG_EXIT_IMM =
Configuration.PREFIX + "exitImmediately";
static final boolean DEFAULT_THREAD_WDOG_EXIT_IMM = true;
public static final String PARAM_NAMED_WDOG_INTERVAL =
PREFIX + "<name>.watchdog.interval";
public static final String PARAM_NAMED_THREAD_PRIORITY =
PREFIX + "<name>.priority";
private static Logger log = Logger.getLogger("LockssThread");
private OneShotSemaphore runningSem = new OneShotSemaphore();
private Map wdogParamNameMap = new HashMap();
private Map prioParamNameMap = new HashMap();
private volatile boolean triggerOnExit = false;
private volatile long interval = 0;
private TimerQueue.Request timerReq;
private Deadline timerDead;
private TimerQueue.Callback timerCallback =
new TimerQueue.Callback() {
public void timerExpired(Object cookie) {
// Don't trigger the watchdog if it has been turned off. This could
// happen if the timer event happens as it's being cancelled.
if (interval != 0) {
threadHung();
}
}};
private static boolean watchdogDisabled = false;
/** Globally disable the watchdog. Thread watchdogs can cause problems
* during unit testing, esp. when switching between simulated and real
* time. LockssTestCase uses this to disable the watchdog during unit
* tests.
* @param disable disables watchdog if true, enables if false.
* @return the previous state of the disable flag. */
public static boolean disableWatchdog(boolean disable) {
boolean old = watchdogDisabled;
watchdogDisabled = disable;
return old;
}
protected LockssThread(String name) {
super(name);
}
/** Declare that the thread is running and initialized. */
protected void nowRunning() {
runningSem.fill();
}
/** Wait until the thread is running and initialized. Useful to ensure
* the thread has finished its initialization before it is asked to do
* anything. If used in the method that starts the thread, prevents test
* code from finishing before the thread starts, which can cause
* watchdogs to trigger spuriously.
* @param timeout Deadline that limits how long to wait for the thread to
* start running.
* @return true iff the thread has said it's running, false if timeout or
* interrupted.
*/
public boolean waitRunning(Deadline timeout) {
try {
return runningSem.waitFull(timeout);
} catch (InterruptedException e) {
}
return runningSem.isFull();
}
/** Wait until the thread is running and initialized. Useful to ensure
* the thread has finished its initialization before it is asked to do
* anything. If used in the method that starts the thread, prevents test
* code from finishing before the thread starts, which can cause
* watchdogs to trigger spuriously.
* @return true iff the thread has said it's running, false if timeout or
* interrupted.
*/
public boolean waitRunning() {
return waitRunning(Deadline.MAX);
}
/** Set the priority of the thread from a parameter value
* @param name Used to derive a configuration parameter name
* (org.lockss.thread.<i>name</i>.priority) whose value is the priority
* @param defaultPriority the default priority if the config param has no
* value. If this is -1 and the config param has no value, the priority
* will not be changed.
*/
public void setPriority(String name, int defaultPriority) {
int prio = getPriorityFromParam(name, defaultPriority);
if (prio != -1) {
log.debug("Setting priority of " + getName() + " thread to " + prio);
setPriority(prio);
}
}
/** Start a watchdog timer that will expire if not poked for interval
* milliseconds. Calls {@link #threadHung()} if triggered.
* @param interval milliseconds after which watchdog will go off.
*/
public void startWDog(long interval) {
if (watchdogDisabled) {
return;
}
stopWDog();
if (interval != 0) {
this.interval = interval;
logEvent("Starting", true);
timerDead = Deadline.in(interval);
timerReq = TimerQueue.schedule(timerDead, timerCallback, null);
} else {
logEvent("Not starting", true);
}
}
/** Start a watchdog timer that will expire if not poked for interval
* milliseconds. Calls {@link #threadHung()} if triggered.
* @param name Used to derive a configuration parameter name
* (org.lockss.thread.<i>name</i>.watchdog.interval) whose value is the
* watchdog interval.
* @param defaultInterval the default interval if the config param has no
* value.
*/
public void startWDog(String name, long defaultInterval) {
startWDog(getIntervalFromParam(name, defaultInterval));
}
/** Stop the watchdog so that it will not trigger. */
public void stopWDog() {
if (interval != 0) {
interval = 0;
if (timerReq != null) {
TimerQueue.cancel(timerReq);
timerReq = null;
}
logEvent("Stopping", false);
}
}
/** Refresh the watchdog for another interval milliseconds. */
public void pokeWDog() {
if (timerDead != null) {
timerDead.expireIn(interval);
logEvent("Resetting", false);
}
}
/** Set whether thread death should trigger the watchdog. The default is
* false; threads that are supposed to be persistent and never exit
* should set this true. */
public void triggerWDogOnExit(boolean triggerOnExit) {
if (watchdogDisabled) {
return;
}
if (this.triggerOnExit != triggerOnExit) {
logEvent(triggerOnExit ?
"Enabling thread exit" : "Disabling thread exit",
false);
}
this.triggerOnExit = triggerOnExit;
}
/** Called if thread is hung (hasn't poked the watchdog in too long).
* Default action is to exit the daemon; can be overridden is thread is
* able to take some less drastic corrective action (e.g., close socket
* for hung socket reads.) */
protected void threadHung() {
exitDaemon("Thread hung for " + StringUtil.timeIntervalToString(interval));
}
/** Called if thread exited unexpectedly. Default action is to exit the
* daemon; can be overridden is thread is able to take some less drastic
* corrective action. */
protected void threadExited() {
exitDaemon("Thread exited");
}
private void exitDaemon(String msg) {
boolean exitImm = true;
try {
WatchdogService wdog = (WatchdogService)
LockssDaemon.getManager(LockssDaemon. WATCHDOG_SERVICE);
if (wdog != null) {
wdog.forceStop();
}
log.error(msg + ": " + getName());
exitImm = Configuration.getBooleanParam(PARAM_THREAD_WDOG_EXIT_IMM,
DEFAULT_THREAD_WDOG_EXIT_IMM);
} finally {
if (exitImm) {
System.exit(1);
}
}
}
long getIntervalFromParam(String name, long defaultInterval) {
String param = (String)wdogParamNameMap.get(name);
if (param == null) {
param = StringUtil.replaceString(PARAM_NAMED_WDOG_INTERVAL,
"<name>", name);
wdogParamNameMap.put(name, param);
}
return Configuration.getTimeIntervalParam(param, defaultInterval);
}
int getPriorityFromParam(String name, int defaultInterval) {
String param = (String)prioParamNameMap.get(name);
if (param == null) {
param = StringUtil.replaceString(PARAM_NAMED_THREAD_PRIORITY,
"<name>", name);
prioParamNameMap.put(name, param);
}
return Configuration.getIntParam(param, defaultInterval);
}
private void logEvent(String event, boolean includeInterval) {
if (log.isDebug3()) {
StringBuffer sb = new StringBuffer();
sb.append(event);
sb.append(" thread watchdog (");
sb.append(getName());
sb.append(")");
if (includeInterval) {
sb.append(": ");
sb.append(StringUtil.timeIntervalToString(interval));
}
log.debug3(sb.toString());
}
}
/** Invoke the subclass's lockssRun() method, then cancel any outstanding
* thread watchdog */
public final void run() {
try {
lockssRun();
} catch (RuntimeException e) {
log.warning("Thread threw", e);
} finally {
if (triggerOnExit) {
threadExited();
} else {
stopWDog();
}
}
}
/** Subclasses must implement this in place of the run() method */
protected abstract void lockssRun();
}
|
/*
* $Id: LcapSocket.java,v 1.8 2002-12-16 22:13:30 tal Exp $
*/
package org.lockss.protocol;
import java.io.*;
import java.net.*;
import java.util.*;
import org.lockss.util.*;
/** Send and receive unicast and multicast datagrams.
*/
public class LcapSocket {
Logger log;
DatagramSocket sock;
/** Create an LcapSocket to send packets on a new datagram socket. */
public LcapSocket() throws SocketException {
this(new DatagramSocket());
}
/** Create an LcapSocket to send packets on the datagram socket.
* Intended for internal use and testing. */
LcapSocket(DatagramSocket sock) {
this.sock = sock;
}
/** Send a packet
* @param pkt the DatagramPacket to send
*/
public void send(DatagramPacket pkt) throws IOException {
sock.send(pkt);
}
/** Abstract base class for receive sockets */
abstract static class RcvSocket extends LcapSocket {
Queue rcvQ;
private ReceiveThread rcvThread;
/** Subclasses should call this with the socket they create */
protected RcvSocket(Queue rcvQ, DatagramSocket sock) {
super(sock);
this.rcvQ = rcvQ;
log = Logger.getLogger(getThreadName());
}
/** Subclasses must implement this to handle received packets */
abstract void processReceivedDatagram(LockssReceivedDatagram dg);
/** Convenience method to make names for loggers and threads */
String getThreadName() {
return "Sock_" + sock.getLocalPort() + "_Rcv";
}
/** Start the socket's receive thread */
public void start() {
ensureRcvThread();
}
// tk add watchdog
private void ensureRcvThread() {
if (rcvThread == null) {
log.info("Starting receive thread");
rcvThread = new ReceiveThread(getThreadName());
rcvThread.start();
}
}
/** Stop the socket's receive thread */
public void stop() {
if (rcvThread != null) {
log.info("Stopping rev thread");
rcvThread.stopRcvThread();
rcvThread = null;
}
}
/** Receive one packet, build a DatagramPacket, call the LcapSocket's
processReceivedDatagram() */
private void receivePacket() throws IOException {
byte buf[] = new byte[LockssReceivedDatagram.MAX_SIZE];
DatagramPacket pkt =
new DatagramPacket(buf, LockssReceivedDatagram.MAX_SIZE);
try {
sock.receive(pkt);
LockssReceivedDatagram dg = new LockssReceivedDatagram(pkt);
dg.setReceiveSocket(this);
log.debug("Received " + dg);
processReceivedDatagram(dg);
} catch (InterruptedIOException e) {
}
}
// Receive thread
private class ReceiveThread extends Thread {
private boolean goOn = false;
private ReceiveThread(String name) {
super(name);
}
public void run() {
// if (rcvPriority > 0) {
// Thread.currentThread().setPriority(rcvPriority);
goOn = true;
try {
while (goOn) {
receivePacket();
}
// } catch (InterruptedException e) {
} catch (IOException e) {
// tk - what do to here?
log.warning("receive()", e);
} finally {
rcvThread = null;
}
}
private void stopRcvThread() {
goOn = false;
this.interrupt();
}
}
}
/** LcapSocket.Unicast receives packets on a unicast socket */
public static class Unicast extends RcvSocket {
/* Create a Unicast socket that receives packets sent to <i>port</i>,
* and puts them on the specified queue.
@param rcvQ The queue onto which to put received packets
@param port The UDP port to which tobind the socket
*/
public Unicast(Queue rcvQ, int port) throws SocketException {
this(rcvQ, new DatagramSocket(port));
}
/** Create a Unicast receive socket that receives from the datagram socket.
* Intended for internal use and testing only. */
Unicast(Queue rcvQ, DatagramSocket sock) {
super(rcvQ, sock);
}
/* Mark the packet as unicast, add to the queue */
void processReceivedDatagram(LockssReceivedDatagram dg) {
dg.setMulticast(false);
rcvQ.put(dg);
}
String getThreadName() {
return "U" + super.getThreadName();
}
}
/** LcapSocket.Multicast receives multicast packets.
* It identifies as multicast only those packets that were actually
* multicast (<i>ie</i>, not just unicast to a multicast port on this
* machine
*/
public static class Multicast extends RcvSocket {
/** Create a Multicast socket that receives packets sent to <i>port</i>,
* and puts them on the specified queue.
* @param rcvQ The queue onto which to put received packets
* @param grp The multicast group to join
* @param port The UDP port to which to bind the socket
*/
public Multicast(Queue rcvQ, InetAddress grp, int port)
throws IOException {
this(rcvQ, new MulticastSocket(port), grp);
}
/** Create a Multicast receive socket that receives from the multicast
* socket. Intended for internal use and testing only. */
Multicast(Queue rcvQ, MulticastSocket sock, InetAddress grp)
throws IOException {
super(rcvQ, sock);
sock.joinGroup(grp);
}
/** Mark the packet as multicast, add to the queue */
void processReceivedDatagram(LockssReceivedDatagram dg) {
dg.setMulticast(true);
rcvQ.put(dg);
}
String getThreadName() {
return "M" + super.getThreadName();
}
}
}
|
package io.javalin.security;
import io.javalin.Context;
import io.javalin.Handler;
import io.javalin.core.HandlerType;
import java.util.List;
import java.util.Set;
@FunctionalInterface
public interface AccessManager {
void manage(Handler handler, Context ctx, Set<Role> permittedRoles) throws Exception;
}
|
package org.nutz.filepool;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.lang.random.R;
import java.io.File;
public class UU32FilePool implements FilePool {
File root;
public UU32FilePool(String path) {
this.root = Files.createDirIfNoExists(root);
}
public File createFile(String suffix) {
String key = R.UU32();
File dir = new File(root, key.substring(0, 2));
Files.createDirIfNoExists(dir);
return new File(dir, key.substring(2));
}
public void clear() {
Files.deleteDir(root);
this.root = Files.createDirIfNoExists(root);
}
public long current() {
throw Lang.noImplement();
}
public boolean hasFile(long fId, String suffix) {
throw Lang.noImplement();
}
@Override
public File removeFile(long fId, String suffix) {
throw Lang.noImplement();
}
public long getFileId(File f) {
throw Lang.noImplement();
}
public File getFile(long fId, String suffix) {
throw Lang.noImplement();
}
public File returnFile(long fId, String suffix) {
throw Lang.noImplement();
}
public boolean hasDir(long fId) {
throw Lang.noImplement();
}
public File removeDir(long fId) {
throw Lang.noImplement();
}
public File createDir() {
throw Lang.noImplement();
}
public File getDir(long fId) {
throw Lang.noImplement();
}
public File returnDir(long fId) {
throw Lang.noImplement();
}
}
|
package io.reist.visum.view;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import io.reist.visum.ComponentCache;
import io.reist.visum.VisumClientHelper;
import io.reist.visum.presenter.VisumPresenter;
public abstract class VisumActivity<P extends VisumPresenter>
extends AppCompatActivity
implements VisumView<P> {
private final VisumViewHelper<P> helper;
/**
* @deprecated use {@link #VisumActivity(int)} instead
*/
@SuppressWarnings("deprecation")
@Deprecated
public VisumActivity() {
this(VisumPresenter.VIEW_ID_DEFAULT);
}
public VisumActivity(int viewId) {
this.helper = new VisumViewHelper<>(viewId, new VisumClientHelper<>(this));
}
//region VisumClient implementation
@Override
public final void onStartClient() {
helper.onStartClient();
}
@NonNull
@Override
public final ComponentCache getComponentCache() {
return helper.getComponentCache();
}
@Override
public final void onStopClient() {
helper.onStopClient();
}
@NonNull
public final Context getContext() {
return this;
}
//endregion
//region VisumView implementation
@Override
public void attachPresenter() {}
@Override
public void detachPresenter() {}
//endregion
//region Activity implementation
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
helper.onStartClient();
helper.onRestoreInstanceState();
setContentView(getLayoutRes());
}
@Override
public void onResume() {
super.onResume();
helper.attachPresenter();
}
@Override
public void onPause() {
super.onPause();
helper.detachPresenter();
}
@Override
public void onDestroy() {
super.onDestroy();
helper.onStopClient();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
helper.onSaveInstanceState();
}
//endregion
@LayoutRes
protected abstract int getLayoutRes();
}
|
package io.sigpipe.sing.stat;
import java.util.List;
import org.apache.commons.math3.util.FastMath;
import io.sigpipe.sing.dataset.feature.Feature;
public class SquaredError {
private RunningStatistics sqErrs = new RunningStatistics();
private RunningStatistics actualStats = new RunningStatistics();
private RunningStatistics predictedStats = new RunningStatistics();
public SquaredError(List<Feature> actual, List<Feature> predicted) {
if (actual.size() != predicted.size()) {
throw new IllegalArgumentException(
"List sizes must be equal");
}
for (int i = 0; i < actual.size(); ++i) {
Feature a = actual.get(i);
Feature p = predicted.get(i);
this.put(a, p);
}
}
public void put(Feature actual, Feature predicted) {
this.put(actual.getDouble(), predicted.getDouble());
}
public void put(double actual, double predicted) {
double err = actual - predicted;
double p = FastMath.pow(err, 2.0);
sqErrs.put(p);
actualStats.put(actual);
predictedStats.put(predicted);
}
public double RMSE() {
return FastMath.sqrt(sqErrs.mean());
}
public double NRMSE() {
return RMSE() / (actualStats.max() - actualStats.min());
}
public double CVRMSE() {
return RMSE() / actualStats.mean();
}
public SummaryStatistics actualSummary() {
return new SummaryStatistics(actualStats);
}
public SummaryStatistics predictedSummary() {
return new SummaryStatistics(predictedStats);
}
}
|
package org.ojalgo.array;
import org.ojalgo.OjAlgoUtils;
import org.ojalgo.constant.PrimitiveMath;
import org.ojalgo.function.PrimitiveFunction;
import org.ojalgo.machine.Hardware;
import org.ojalgo.scalar.Scalar;
/**
* To be used by implementations that delegate to a DenseArray
*
* @author apete
*/
final class DenseStrategy<N extends Number> {
static long CHUNK = 512L;
static long INITIAL = 16L;
static long SEGMENT = 16_384L;
static int capacity(final long count) {
double tmpInitialCapacity = count;
while (tmpInitialCapacity > DenseArray.MAX_ARRAY_SIZE) {
tmpInitialCapacity = PrimitiveFunction.SQRT.invoke(tmpInitialCapacity);
}
tmpInitialCapacity = PrimitiveFunction.SQRT.invoke(tmpInitialCapacity);
return 2 * (int) tmpInitialCapacity;
}
private long myChunk = CHUNK;
private final DenseArray.Factory<N> myDenseFactory;
private long myInitial = INITIAL;
private long mySegment = SEGMENT;
DenseStrategy(final DenseArray.Factory<N> denseFactory) {
super();
myDenseFactory = denseFactory;
mySegment = this.alignToMemoryPages((OjAlgoUtils.ENVIRONMENT.cache / 2L) / denseFactory.getElementSize());
}
private long alignToMemoryPages(long numberOfElements) {
long tmpElementsPerPage = Hardware.OS_MEMORY_PAGE_SIZE / myDenseFactory.getElementSize();
final long tmpNumberOfPages = Math.max(1L, numberOfElements / tmpElementsPerPage);
return tmpElementsPerPage * tmpNumberOfPages;
}
DenseStrategy<N> chunk(final long chunk) {
final int power = PrimitiveMath.powerOf2Smaller(Math.min(chunk, mySegment));
myChunk = Math.max(INITIAL, 1L << power);
return this;
}
int grow(final int current) {
return (int) grow((long) current);
}
long grow(final long current) {
long required = current + 1L;
long retVal = myChunk;
if (required >= myChunk) {
while (retVal < required) {
retVal += myChunk;
}
} else {
long maybe = retVal / 2L;
while (maybe >= required) {
retVal = maybe;
maybe /= 2L;
}
}
return retVal;
}
int initial() {
return (int) myInitial;
}
/**
* Enforced to be >= 1
*/
DenseStrategy<N> initial(final long initial) {
myInitial = Math.max(1, initial);
return this;
}
boolean isChunked(final long count) {
return count >= myChunk;
}
boolean isSegmented(final long count) {
return count >= mySegment;
}
DenseArray<N> make(final long size) {
return myDenseFactory.make(size);
}
DenseArray<N> makeChunk() {
return this.make(myChunk);
}
DenseArray<N> makeInitial() {
return this.make(myInitial);
}
DenseArray<N> makeSegment() {
return this.make(mySegment);
}
SegmentedArray<N> makeSegmented(final BasicArray<N> segment) {
if (segment.count() == myChunk) {
return myDenseFactory.wrapAsSegments(segment, this.makeChunk());
} else {
throw new IllegalStateException();
}
}
/**
* Will be set to a multiple of {@link Hardware#OS_MEMORY_PAGE_SIZE} amd not {@code 0L}.
*/
DenseStrategy<N> segment(final long segment) {
mySegment = this.alignToMemoryPages(Math.max(myChunk, segment));
return this;
}
Scalar<N> zero() {
return myDenseFactory.zero();
}
}
|
package javaewah32;
import java.util.*;
import java.io.*;
import javaewah.IntIterator;
public final class EWAHCompressedBitmap32 implements Cloneable, Externalizable,
Iterable<Integer>, BitmapStorage32 {
/**
* Creates an empty bitmap (no bit set to true).
*/
public EWAHCompressedBitmap32() {
this.buffer = new int[defaultbuffersize];
this.rlw = new RunningLengthWord32(this.buffer, 0);
}
/**
* Sets explicitly the buffer size (in 32-bit words). The initial memory usage
* will be "buffersize * 32". For large poorly compressible bitmaps, using
* large values may improve performance.
*
* @param buffersize number of 32-bit words reserved when the object is created)
*/
public EWAHCompressedBitmap32(final int buffersize) {
this.buffer = new int[buffersize];
this.rlw = new RunningLengthWord32(this.buffer, 0);
}
/**
* Gets an EWAHIterator over the data. This is a customized
* iterator which iterates over run length word. For experts only.
*
* @return the EWAHIterator
*/
private EWAHIterator32 getEWAHIterator() {
return new EWAHIterator32(this.buffer, this.actualsizeinwords);
}
/**
* Returns a new compressed bitmap containing the bitwise XOR values of the
* current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
public EWAHCompressedBitmap32 xor(final EWAHCompressedBitmap32 a) {
final EWAHCompressedBitmap32 container = new EWAHCompressedBitmap32();
container.reserve(this.actualsizeinwords + a.actualsizeinwords);
xor(a,container);
return container;
}
/**
* Computes a new compressed bitmap containing the bitwise XOR values of the
* current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @param container where we store the result
*/
private void xor(final EWAHCompressedBitmap32 a, final BitmapStorage32 container) {
final EWAHIterator32 i = a.getEWAHIterator();
final EWAHIterator32 j = getEWAHIterator();
if (!(i.hasNext() && j.hasNext())) {// this never happens...
container.setSizeInBits(sizeInBits());
}
// at this point, this is safe:
BufferedRunningLengthWord32 rlwi = new BufferedRunningLengthWord32(i.next());
BufferedRunningLengthWord32 rlwj = new BufferedRunningLengthWord32(j.next());
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord32 prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord32 predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
final int predatorrl = predator.getRunningLength();
final int preyrl = prey.getRunningLength();
final int tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container
.addStreamOfEmptyWords(predator.getRunningBit(), tobediscarded);
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
container.addStreamOfDirtyWords(i_is_prey ? j.buffer() : i.buffer(),
dw_predator, preyrl - tobediscarded);
predator.discardFirstWords(preyrl);
prey.discardFirstWords(preyrl);
} else {
// we have a stream of 1x11
final int predatorrl = predator.getRunningLength();
final int preyrl = prey.getRunningLength();
final int tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container.addStreamOfEmptyWords(!predator.getRunningBit(),
tobediscarded);
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
final int[] buf = i_is_prey ? j.buffer() : i.buffer();
for (int k = 0; k < preyrl - tobediscarded; ++k)
container.add(~buf[k + dw_predator]);
predator.discardFirstWords(preyrl);
prey.discardFirstWords(preyrl);
}
final int predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
container.addStreamOfDirtyWords(i_is_prey ? i.buffer() : j.buffer(),
dw_prey, tobediscarded);
} else {
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
final int[] buf = i_is_prey ? i.buffer() : j.buffer();
for (int k = 0; k < tobediscarded; ++k)
container.add(~buf[k + dw_prey]);
}
}
// all that is left to do now is to AND the dirty words
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
container.add(i.buffer()[prey.dirtywordoffset + i.dirtyWords() + k]
^ j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k]);
else
container.add(i.buffer()[predator.dirtywordoffset + i.dirtyWords()
+ k]
^ j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k]);
}
predator.discardFirstWords(nbre_dirty_prey);
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());
}
}
if (rlwi != null)
discharge(rlwi, i, container);
if (rlwj != null)
discharge(rlwj, j, container);
container.setSizeInBits( Math.max(sizeInBits(), a.sizeInBits()) );
}
/**
* Returns a new compressed bitmap containing the bitwise AND values of the
* current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
public EWAHCompressedBitmap32 and(final EWAHCompressedBitmap32 a) {
final EWAHCompressedBitmap32 container = new EWAHCompressedBitmap32();
container
.reserve(this.actualsizeinwords > a.actualsizeinwords ? this.actualsizeinwords
: a.actualsizeinwords);
and(a,container);
return container;
}
/**
* Computes new compressed bitmap containing the bitwise AND values of the
* current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @param container where we store the result
*/
private void and(final EWAHCompressedBitmap32 a, final BitmapStorage32 container) {
final EWAHIterator32 i = a.getEWAHIterator();
final EWAHIterator32 j = getEWAHIterator();
if (!(i.hasNext() && j.hasNext())) {// this never happens...
container.setSizeInBits(sizeInBits());
}
// at this point, this is safe:
BufferedRunningLengthWord32 rlwi = new BufferedRunningLengthWord32(i.next());
BufferedRunningLengthWord32 rlwj = new BufferedRunningLengthWord32(j.next());
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord32 prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord32 predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
container.addStreamOfEmptyWords(false, prey.RunningLength);
predator.discardFirstWords(prey.RunningLength);
prey.RunningLength = 0;
} else {
// we have a stream of 1x11
final int predatorrl = predator.getRunningLength();
final int preyrl = prey.getRunningLength();
final int tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container
.addStreamOfEmptyWords(predator.getRunningBit(), tobediscarded);
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
container.addStreamOfDirtyWords(i_is_prey ? j.buffer() : i.buffer(),
dw_predator, preyrl - tobediscarded);
predator.discardFirstWords(preyrl);
prey.RunningLength = 0;
}
final int predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
container.addStreamOfEmptyWords(false, tobediscarded);
} else {
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
final int tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
container.addStreamOfDirtyWords(i_is_prey ? i.buffer() : j.buffer(),
dw_prey, tobediscarded);
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
}
}
// all that is left to do now is to AND the dirty words
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
container.add(i.buffer()[prey.dirtywordoffset + i.dirtyWords() + k]
& j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k]);
else
container.add(i.buffer()[predator.dirtywordoffset + i.dirtyWords()
+ k]
& j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k]);
}
predator.discardFirstWords(nbre_dirty_prey);
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());
}
}
if (rlwi != null)
dischargeAsEmpty(rlwi, i, container);
if (rlwj != null)
dischargeAsEmpty(rlwj, j, container);
container.setSizeInBits( Math.max(sizeInBits(), a.sizeInBits()) );
}
/**
* Returns a new compressed bitmap containing the bitwise AND values of the
* provided bitmaps.
*
* @param bitmaps bitmaps to AND together
* @return result of the AND
*/
public static EWAHCompressedBitmap32 and(final EWAHCompressedBitmap32...bitmaps) {
final EWAHCompressedBitmap32 container = new EWAHCompressedBitmap32();
int largestSize = 0;
for (EWAHCompressedBitmap32 bitmap : bitmaps) {
largestSize = Math.max( bitmap.actualsizeinwords, largestSize );
}
container.reserve((int)(largestSize * 1.5));
and(container, bitmaps);
return container;
}
/**
* Returns the cardinality of the result of a bitwise AND of the values
* of the provided bitmaps. Avoids needing to
* allocate an intermediate bitmap to hold the result of the AND.
*
* @param bitmaps bitmaps to AND
* @return the cardinality
*/
public static int andCardinality(final EWAHCompressedBitmap32...bitmaps) {
final BitCounter32 counter = new BitCounter32();
and(counter, bitmaps);
return counter.getCount();
}
/**
* For internal use.
* Computes the bitwise and of the provided bitmaps and stores the result in the
* container.
* @param container where the result is stored
* @param bitmaps bitmaps to AND
*/
private static void and(final BitmapStorage32 container, final EWAHCompressedBitmap32...bitmaps) {
if (bitmaps.length == 2)
{
// should be more efficient
bitmaps[0].and(bitmaps[1], container);
return;
}
// Sort the bitmaps in ascending order by sizeinbits. When we exhaust the first bitmap the rest
// of the result is zeros.
final EWAHCompressedBitmap32[] sortedBitmaps = bitmaps.clone();
Arrays.sort(sortedBitmaps, new Comparator<EWAHCompressedBitmap32> () {
public int compare(EWAHCompressedBitmap32 a, EWAHCompressedBitmap32 b) {
return a.sizeinbits < b.sizeinbits ? -1 : a.sizeinbits == b.sizeinbits ? 0 : 1;
}
});
int maxSize = sortedBitmaps[sortedBitmaps.length - 1].sizeinbits;
final IteratingBufferedRunningLengthWord32[] rlws = new IteratingBufferedRunningLengthWord32[bitmaps.length];
for (int i = 0; i < sortedBitmaps.length; i++) {
EWAHIterator32 iterator = sortedBitmaps[i].getEWAHIterator();
if (iterator.hasNext())
{
rlws[i] = new IteratingBufferedRunningLengthWord32(iterator);
}
else
{
//this never happens...
if (maxSize > 0) {
extendEmptyBits(container, 0, maxSize);
}
container.setSizeInBits(maxSize);
return;
}
}
while (true) {
int maxZeroRl = 0;
int minOneRl = Integer.MAX_VALUE;
int minSize = Integer.MAX_VALUE;
int numEmptyRl = 0;
if (rlws[0].size() == 0)
{
extendEmptyBits(container, sortedBitmaps[0].sizeinbits, maxSize);
break;
}
for (IteratingBufferedRunningLengthWord32 rlw : rlws) {
int size = rlw.size();
minSize = Math.min(minSize, size);
if (!rlw.getRunningBit()) {
int rl = rlw.getRunningLength();
maxZeroRl = Math.max(maxZeroRl, rl);
minOneRl = 0;
if (rl == 0 && size > 0) {
numEmptyRl++;
}
}
else
{
int rl = rlw.getRunningLength();
minOneRl = Math.min(minOneRl, rl);
if (rl == 0 && size > 0) {
numEmptyRl++;
}
}
}
if (maxZeroRl > 0) {
container.addStreamOfEmptyWords(false, maxZeroRl);
for (IteratingBufferedRunningLengthWord32 rlw : rlws) {
rlw.discardFirstWords(maxZeroRl);
}
}
else if (minOneRl > 0) {
container.addStreamOfEmptyWords(true, minOneRl);
for (IteratingBufferedRunningLengthWord32 rlw : rlws) {
rlw.discardFirstWords(minOneRl);
}
}
else {
int index = 0;
if (numEmptyRl == 1) {
// if one rlw has dirty words to process and the rest have a run of 1's we can write them out here
IteratingBufferedRunningLengthWord32 emptyRl = null;
int minNonEmptyRl = Integer.MAX_VALUE;
for (IteratingBufferedRunningLengthWord32 rlw : rlws) {
int rl = rlw.getRunningLength();
if( rl == 0 )
{
assert emptyRl == null;
emptyRl = rlw;
}
else
{
minNonEmptyRl = Math.min(minNonEmptyRl, rl);
}
}
int wordsToWrite = minNonEmptyRl > minSize ? minSize : minNonEmptyRl;
if(emptyRl!=null) emptyRl.writeDirtyWords(wordsToWrite, container);
index += wordsToWrite;
}
while (index < minSize) {
int word = ~0;
for (IteratingBufferedRunningLengthWord32 rlw : rlws) {
if (rlw.getRunningLength() <= index)
{
word &= rlw.getDirtyWordAt(index - rlw.getRunningLength());
}
}
container.add(word);
index++;
}
for (IteratingBufferedRunningLengthWord32 rlw : rlws) {
rlw.discardFirstWords(minSize);
}
}
}
container.setSizeInBits(maxSize);
}
/**
* Return true if the two EWAHCompressedBitmap have both at least one
* true bit in the same position. Equivalently, you could call "and"
* and check whether there is a set bit, but intersects will run faster
* if you don't need the result of the "and" operation.
*
* @param a the other bitmap
* @return whether they intersect
*/
public boolean intersects(final EWAHCompressedBitmap32 a) {
NonEmptyVirtualStorage32 nevs = new NonEmptyVirtualStorage32();
try {
this.and(a,nevs);
} catch(NonEmptyVirtualStorage32.NonEmptyException nee) {
return true;
}
return false; }
/**
* Returns a new compressed bitmap containing the bitwise AND NOT values of
* the current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
public EWAHCompressedBitmap32 andNot(final EWAHCompressedBitmap32 a) {
final EWAHCompressedBitmap32 container = new EWAHCompressedBitmap32();
container
.reserve(this.actualsizeinwords > a.actualsizeinwords ? this.actualsizeinwords
: a.actualsizeinwords);
andNot(a,container);
return container;
}
/**
* Returns a new compressed bitmap containing the bitwise AND NOT values of
* the current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
private void andNot(final EWAHCompressedBitmap32 a, final BitmapStorage32 container) {
final EWAHIterator32 i = a.getEWAHIterator();
final EWAHIterator32 j = getEWAHIterator();
if (!(i.hasNext() && j.hasNext())) {// this never happens...
container.setSizeInBits( sizeInBits());
}
// at this point, this is safe:
BufferedRunningLengthWord32 rlwi = new BufferedRunningLengthWord32(i.next());
rlwi.setRunningBit(!rlwi.getRunningBit());
BufferedRunningLengthWord32 rlwj = new BufferedRunningLengthWord32(j.next());
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord32 prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord32 predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
container.addStreamOfEmptyWords(false, prey.RunningLength);
predator.discardFirstWords(prey.RunningLength);
prey.RunningLength = 0;
} else {
// we have a stream of 1x11
final int predatorrl = predator.getRunningLength();
final int preyrl = prey.getRunningLength();
final int tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container
.addStreamOfEmptyWords(predator.getRunningBit(), tobediscarded);
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
if (i_is_prey)
container.addStreamOfDirtyWords(j.buffer(), dw_predator, preyrl
- tobediscarded);
else
container.addStreamOfNegatedDirtyWords(i.buffer(), dw_predator,
preyrl - tobediscarded);
predator.discardFirstWords(preyrl);
prey.RunningLength = 0;
}
final int predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
container.addStreamOfEmptyWords(false, tobediscarded);
} else {
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
final int tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
if (i_is_prey)
container.addStreamOfNegatedDirtyWords(i.buffer(), dw_prey,
tobediscarded);
else
container.addStreamOfDirtyWords(j.buffer(), dw_prey, tobediscarded);
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
}
}
// all that is left to do now is to AND the dirty words
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
container.add((~i.buffer()[prey.dirtywordoffset + i.dirtyWords()
+ k])
& j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k]);
else
container.add((~i.buffer()[predator.dirtywordoffset
+ i.dirtyWords() + k])
& j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k]);
}
predator.discardFirstWords(nbre_dirty_prey);
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());
rlwi.setRunningBit(!rlwi.getRunningBit());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());
}
}
if (rlwi != null)
dischargeAsEmpty(rlwi, i, container);
if (rlwj != null)
discharge(rlwj, j, container);
container.setSizeInBits( Math.max(sizeInBits(), a.sizeInBits()) );
}
/**
* Negate (bitwise) the current bitmap. To get a negated copy, do
* ((EWAHCompressedBitmap) mybitmap.clone()).not();
*
* The running time is proportional to the compressed size (as reported by
* sizeInBytes()).
*
*/
public void not() {
final EWAHIterator32 i = new EWAHIterator32(this.buffer, this.actualsizeinwords);
if(! i.hasNext()) return;
while (true) {
final RunningLengthWord32 rlw1 = i.next();
rlw1.setRunningBit(!rlw1.getRunningBit());
for (int j = 0; j < rlw1.getNumberOfLiteralWords(); ++j) {
i.buffer()[i.dirtyWords() + j] = ~i.buffer()[i.dirtyWords() + j];
}
if(!i.hasNext()) {// must potentially adjust the last dirty word
if(rlw1.getNumberOfLiteralWords()==0) return;
final int usedbitsinlast = this.sizeinbits % wordinbits;
if(usedbitsinlast==0) return;
i.buffer()[i.dirtyWords() + rlw1.getNumberOfLiteralWords() - 1] &= ( (~0) >>> (wordinbits - usedbitsinlast));
return;
}
}
}
/**
* Returns a new compressed bitmap containing the bitwise OR values of the
* current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
public EWAHCompressedBitmap32 or(final EWAHCompressedBitmap32 a) {
final EWAHCompressedBitmap32 container = new EWAHCompressedBitmap32();
container.reserve(this.actualsizeinwords + a.actualsizeinwords);
or(a, container);
return container;
}
/**
* Returns the cardinality of the result of a bitwise OR of the values
* of the current bitmap with some other bitmap. Avoids needing to
* allocate an intermediate bitmap to hold the result of the OR.
*
* @param a the other bitmap
* @return the cardinality
*/
public int orCardinality(final EWAHCompressedBitmap32 a) {
final BitCounter32 counter = new BitCounter32();
or(a, counter);
return counter.getCount();
}
/**
* Returns the cardinality of the result of a bitwise AND of the values
* of the current bitmap with some other bitmap. Avoids needing to
* allocate an intermediate bitmap to hold the result of the OR.
*
* @param a the other bitmap
* @return the cardinality
*/
public int andCardinality(final EWAHCompressedBitmap32 a) {
final BitCounter32 counter = new BitCounter32();
and(a, counter);
return counter.getCount();
}
/**
* Returns the cardinality of the result of a bitwise AND NOT of the values
* of the current bitmap with some other bitmap. Avoids needing to
* allocate an intermediate bitmap to hold the result of the OR.
*
* @param a the other bitmap
* @return the cardinality
*/
public int andNotCardinality(final EWAHCompressedBitmap32 a) {
final BitCounter32 counter = new BitCounter32();
andNot(a, counter);
return counter.getCount();
}
/**
* Returns the cardinality of the result of a bitwise XOR of the values
* of the current bitmap with some other bitmap. Avoids needing to
* allocate an intermediate bitmap to hold the result of the OR.
*
* @param a the other bitmap
* @return the cardinality
*/
public int xorCardinality(final EWAHCompressedBitmap32 a) {
final BitCounter32 counter = new BitCounter32();
xor(a, counter);
return counter.getCount();
}
/**
* Computes the bitwise or between the current bitmap and the bitmap "a". Stores
* the result in the container.
*
* @param a the other bitmap
* @param container where we store the result
*/
private void or( final EWAHCompressedBitmap32 a, final BitmapStorage32 container ) {
final EWAHIterator32 i = a.getEWAHIterator();
final EWAHIterator32 j = getEWAHIterator();
if (!(i.hasNext() && j.hasNext())) {// this never happens...
container.setSizeInBits(sizeInBits());
return;
}
// at this point, this is safe:
BufferedRunningLengthWord32 rlwi = new BufferedRunningLengthWord32(i.next());
BufferedRunningLengthWord32 rlwj = new BufferedRunningLengthWord32(j.next());
// RunningLength;
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord32 prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord32 predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
final int predatorrl = predator.getRunningLength();
final int preyrl = prey.getRunningLength();
final int tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container
.addStreamOfEmptyWords(predator.getRunningBit(), tobediscarded);
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
container.addStreamOfDirtyWords(i_is_prey ? j.buffer() : i.buffer(),
dw_predator, preyrl - tobediscarded);
predator.discardFirstWords(preyrl);
prey.discardFirstWords(preyrl);
prey.RunningLength = 0;
} else {
// we have a stream of 1x11
container.addStreamOfEmptyWords(true, prey.RunningLength);
predator.discardFirstWords(prey.RunningLength);
prey.RunningLength = 0;
}
int predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
container.addStreamOfDirtyWords(i_is_prey ? i.buffer() : j.buffer(),
dw_prey, tobediscarded);
} else {
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
container.addStreamOfEmptyWords(true, tobediscarded);
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
}
}
// all that is left to do now is to OR the dirty words
final int nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
container.add(i.buffer()[prey.dirtywordoffset + i.dirtyWords() + k]
| j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k]);
else
container.add(i.buffer()[predator.dirtywordoffset + i.dirtyWords()
+ k]
| j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k]);
}
predator.discardFirstWords(nbre_dirty_prey);
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());// = new
// BufferedRunningLengthWord(i.next());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());// = new
// BufferedRunningLengthWord(
// j.next());
}
}
if (rlwi != null)
discharge(rlwi, i, container);
if (rlwj != null)
discharge(rlwj, j, container);
container.setSizeInBits(Math.max(sizeInBits(), a.sizeInBits()));
}
/**
* Returns a new compressed bitmap containing the bitwise OR values of the
* provided bitmaps.
*
* @param bitmaps bitmaps to OR together
* @return result of the OR
*/
public static EWAHCompressedBitmap32 or(final EWAHCompressedBitmap32...bitmaps) {
final EWAHCompressedBitmap32 container = new EWAHCompressedBitmap32();
int largestSize = 0;
for (EWAHCompressedBitmap32 bitmap : bitmaps) {
largestSize = Math.max( bitmap.actualsizeinwords, largestSize );
}
container.reserve((int)(largestSize * 1.5));
or(container, bitmaps);
return container;
}
/**
* Returns the cardinality of the result of a bitwise OR of the values
* of the provided bitmaps. Avoids needing to
* allocate an intermediate bitmap to hold the result of the OR.
*
* @param bitmaps bitmaps to OR
* @return the cardinality
*/
public static int orCardinality(final EWAHCompressedBitmap32...bitmaps) {
final BitCounter32 counter = new BitCounter32();
or(counter, bitmaps);
return counter.getCount();
}
/**
* For internal use.
* Computes the bitwise or of the provided bitmaps and stores the result in the
* container.
*/
private static void or(final BitmapStorage32 container, final EWAHCompressedBitmap32...bitmaps) {
if (bitmaps.length == 2)
{
// should be more efficient
bitmaps[0].or(bitmaps[1], container);
return;
}
// Sort the bitmaps in descending order by sizeinbits. We will exhaust the sorted bitmaps from right to left.
final EWAHCompressedBitmap32[] sortedBitmaps = bitmaps.clone();
Arrays.sort(sortedBitmaps, new Comparator<EWAHCompressedBitmap32> () {
public int compare(EWAHCompressedBitmap32 a, EWAHCompressedBitmap32 b) {
return a.sizeinbits < b.sizeinbits ? 1 : a.sizeinbits == b.sizeinbits ? 0 : -1;
}
});
final IteratingBufferedRunningLengthWord32[] rlws = new IteratingBufferedRunningLengthWord32[bitmaps.length];
int maxAvailablePos = 0;
for (EWAHCompressedBitmap32 bitmap : sortedBitmaps ) {
EWAHIterator32 iterator = bitmap.getEWAHIterator();
if( iterator.hasNext() )
{
rlws[maxAvailablePos++] = new IteratingBufferedRunningLengthWord32(iterator);
}
}
if (maxAvailablePos == 0) { //this never happens...
container.setSizeInBits(0);
return;
}
int maxSize = sortedBitmaps[0].sizeinbits;
while (true) {
int maxOneRl = 0;
int minZeroRl = Integer.MAX_VALUE;
int minSize = Integer.MAX_VALUE;
int numEmptyRl = 0;
for (int i = 0; i < maxAvailablePos; i++) {
IteratingBufferedRunningLengthWord32 rlw = rlws[i];
int size = rlw.size();
if (size == 0) {
maxAvailablePos = i;
break;
}
minSize = Math.min(minSize, size);
if (rlw.getRunningBit()) {
int rl = rlw.getRunningLength();
maxOneRl = Math.max(maxOneRl, rl);
minZeroRl = 0;
if (rl == 0 && size > 0) {
numEmptyRl++;
}
}
else
{
int rl = rlw.getRunningLength();
minZeroRl = Math.min(minZeroRl, rl);
if (rl == 0 && size > 0) {
numEmptyRl++;
}
}
}
if (maxAvailablePos == 0) {
break;
}
else if (maxAvailablePos == 1) {
// only one bitmap is left so just write the rest of it out
rlws[0].discharge(container);
break;
}
if (maxOneRl > 0) {
container.addStreamOfEmptyWords(true, maxOneRl);
for (int i = 0; i < maxAvailablePos; i++) {
IteratingBufferedRunningLengthWord32 rlw = rlws[i];
rlw.discardFirstWords(maxOneRl);
}
}
else if (minZeroRl > 0) {
container.addStreamOfEmptyWords(false, minZeroRl);
for (int i = 0; i < maxAvailablePos; i++) {
IteratingBufferedRunningLengthWord32 rlw = rlws[i];
rlw.discardFirstWords(minZeroRl);
}
}
else {
int index = 0;
if (numEmptyRl == 1) {
// if one rlw has dirty words to process and the rest have a run of 0's we can write them out here
IteratingBufferedRunningLengthWord32 emptyRl = null;
int minNonEmptyRl = Integer.MAX_VALUE;
for (int i = 0; i < maxAvailablePos; i++) {
IteratingBufferedRunningLengthWord32 rlw = rlws[i];
int rl = rlw.getRunningLength();
if( rl == 0 )
{
assert emptyRl == null;
emptyRl = rlw;
}
else
{
minNonEmptyRl = Math.min(minNonEmptyRl, rl);
}
}
int wordsToWrite = minNonEmptyRl > minSize ? minSize : minNonEmptyRl;
if(emptyRl!=null) emptyRl.writeDirtyWords(wordsToWrite, container);
index += wordsToWrite;
}
while (index < minSize) {
int word = 0;
for (int i = 0; i < maxAvailablePos; i++) {
IteratingBufferedRunningLengthWord32 rlw = rlws[i];
if (rlw.getRunningLength() <= index)
{
word |= rlw.getDirtyWordAt(index - rlw.getRunningLength());
}
}
container.add(word);
index++;
}
for (int i = 0; i < maxAvailablePos; i++) {
IteratingBufferedRunningLengthWord32 rlw = rlws[i];
rlw.discardFirstWords(minSize);
}
}
}
container.setSizeInBits(maxSize);
}
/**
* For internal use.
*
* @param initialWord the initial word
* @param iterator the iterator
* @param container the container
*/
protected static void discharge(final BufferedRunningLengthWord32 initialWord,
final EWAHIterator32 iterator, final BitmapStorage32 container) {
BufferedRunningLengthWord32 runningLengthWord = initialWord;
for (;;) {
final int runningLength = runningLengthWord.getRunningLength();
container.addStreamOfEmptyWords(runningLengthWord.getRunningBit(),
runningLength);
container.addStreamOfDirtyWords(iterator.buffer(), iterator.dirtyWords()
+ runningLengthWord.dirtywordoffset,
runningLengthWord.getNumberOfLiteralWords());
if (!iterator.hasNext())
break;
runningLengthWord = new BufferedRunningLengthWord32(iterator.next());
}
}
/**
* For internal use.
*
* @param initialWord the initial word
* @param iterator the iterator
* @param container the container
*/
private static void dischargeAsEmpty(final BufferedRunningLengthWord32 initialWord,
final EWAHIterator32 iterator, final BitmapStorage32 container) {
BufferedRunningLengthWord32 runningLengthWord = initialWord;
for (;;) {
final int runningLength = runningLengthWord.getRunningLength();
container.addStreamOfEmptyWords(false,
runningLength + runningLengthWord.getNumberOfLiteralWords());
if (!iterator.hasNext())
break;
runningLengthWord = new BufferedRunningLengthWord32(iterator.next());
}
}
/**
* set the bit at position i to true, the bits must be set in increasing
* order. For example, set(15) and then set(7) will fail. You must do set(7)
* and then set(15).
*
* @param i the index
* @return true if the value was set (always true when i>= sizeInBits()).
*/
public boolean set(final int i) {
if (i < this.sizeinbits)
return false;
boolean sameWord = false;
// must I complete a word?
if ((this.sizeinbits % wordinbits) != 0) {
final int possiblesizeinbits = (this.sizeinbits / wordinbits) * wordinbits + wordinbits;
if (possiblesizeinbits < i + 1) {
this.sizeinbits = possiblesizeinbits;
}
else {
// we are modifying the word at the end of the bitmap
sameWord = true;
}
}
addStreamOfEmptyWords(false, (i / wordinbits) - this.sizeinbits / wordinbits);
final int bittoflip = i - (this.sizeinbits / wordinbits * wordinbits);
// next, we set the bit
if ((this.rlw.getNumberOfLiteralWords() == 0)
|| ((this.sizeinbits - 1) / wordinbits < i / wordinbits)) {
final int newdata = 1 << bittoflip;
addLiteralWord(newdata);
if (sameWord && !this.rlw.getRunningBit() && this.rlw.getRunningLength() > 0) {
// the previous literal word is replacing the last running word
this.rlw.setRunningLength(this.rlw.getRunningLength()-1);
}
} else {
this.buffer[this.actualsizeinwords - 1] |= 1 << bittoflip;
// check if we just completed a stream of 1s
if (this.buffer[this.actualsizeinwords - 1] == ~0) {
// we remove the last dirty word
this.buffer[this.actualsizeinwords - 1] = 0;
--this.actualsizeinwords;
this.rlw
.setNumberOfLiteralWords(this.rlw.getNumberOfLiteralWords() - 1);
// next we add one clean word
addEmptyWord(true);
}
}
this.sizeinbits = i + 1;
return true;
}
/**
* Adding words directly to the bitmap (for expert use).
*
* This is normally how you add data to the array. So you add bits in streams
* of 8*8 bits.
*
* @param newdata the word
* @return the number of words added to the buffer
*/
public int add(final int newdata) {
return add(newdata, wordinbits);
}
/**
* For experts: You want to add many
* zeroes or ones? This is the method you use.
*
* @param v the boolean value
* @param number the number
* @return the number of words added to the buffer
*/
public int addStreamOfEmptyWords(final boolean v, final int number) {
if (number == 0)
return 0;
final boolean noliteralword = (this.rlw.getNumberOfLiteralWords() == 0);
final int runlen = this.rlw.getRunningLength();
if ((noliteralword) && (runlen == 0)) {
this.rlw.setRunningBit(v);
}
int wordsadded = 0;
if ((noliteralword) && (this.rlw.getRunningBit() == v)
&& (runlen < RunningLengthWord32.largestrunninglengthcount)) {
int whatwecanadd = number < RunningLengthWord32.largestrunninglengthcount
- runlen ? number : RunningLengthWord32.largestrunninglengthcount
- runlen;
this.rlw.setRunningLength(runlen + whatwecanadd);
this.sizeinbits += whatwecanadd * wordinbits;
if (number - whatwecanadd > 0)
wordsadded += addStreamOfEmptyWords(v, number - whatwecanadd);
} else {
push_back(0);
++wordsadded;
this.rlw.position = this.actualsizeinwords - 1;
final int whatwecanadd = number < RunningLengthWord32.largestrunninglengthcount ? number
: RunningLengthWord32.largestrunninglengthcount;
this.rlw.setRunningBit(v);
this.rlw.setRunningLength(whatwecanadd);
this.sizeinbits += whatwecanadd * wordinbits;
if (number - whatwecanadd > 0)
wordsadded += addStreamOfEmptyWords(v, number - whatwecanadd);
}
return wordsadded;
}
/**
* Same as addStreamOfDirtyWords, but the words are negated.
*
* @param data the dirty words
* @param start the starting point in the array
* @param number the number of dirty words to add
* @return how many (compressed) words were added to the bitmap
*/
public int addStreamOfNegatedDirtyWords(final int[] data,
final int start, final int number) {
if (number == 0)
return 0;
final int NumberOfLiteralWords = this.rlw.getNumberOfLiteralWords();
final int whatwecanadd = number < RunningLengthWord32.largestliteralcount
- NumberOfLiteralWords ? number : RunningLengthWord32.largestliteralcount
- NumberOfLiteralWords;
this.rlw.setNumberOfLiteralWords(NumberOfLiteralWords + whatwecanadd);
final int leftovernumber = number - whatwecanadd;
negative_push_back(data, start, whatwecanadd);
this.sizeinbits += whatwecanadd * wordinbits;
int wordsadded = whatwecanadd;
if (leftovernumber > 0) {
push_back(0);
this.rlw.position = this.actualsizeinwords - 1;
++wordsadded;
wordsadded += addStreamOfDirtyWords(data, start + whatwecanadd,
leftovernumber);
}
return wordsadded;
}
/**
* if you have several dirty words to copy over, this might be faster.
*
*
* @param data the dirty words
* @param start the starting point in the array
* @param number the number of dirty words to add
* @return how many (compressed) words were added to the bitmap
*/
public int addStreamOfDirtyWords(final int[] data, final int start,
final int number) {
if (number == 0)
return 0;
final int NumberOfLiteralWords = this.rlw.getNumberOfLiteralWords();
final int whatwecanadd = number < RunningLengthWord32.largestliteralcount
- NumberOfLiteralWords ? number : RunningLengthWord32.largestliteralcount
- NumberOfLiteralWords;
this.rlw.setNumberOfLiteralWords(NumberOfLiteralWords + whatwecanadd);
final int leftovernumber = number - whatwecanadd;
push_back(data, start, whatwecanadd);
this.sizeinbits += whatwecanadd * wordinbits;
int wordsadded = whatwecanadd;
if (leftovernumber > 0) {
push_back(0);
this.rlw.position = this.actualsizeinwords - 1;
++wordsadded;
wordsadded += addStreamOfDirtyWords(data, start + whatwecanadd,
leftovernumber);
}
return wordsadded;
}
/**
* Adding words directly to the bitmap (for expert use).
*
* @param newdata the word
* @param bitsthatmatter the number of significant bits (by default it should be 32)
* @return the number of words added to the buffer
*/
public int add(final int newdata, final int bitsthatmatter) {
this.sizeinbits += bitsthatmatter;
if (newdata == 0) {
return addEmptyWord(false);
} else if (newdata == ~0) {
return addEmptyWord(true);
} else {
return addLiteralWord(newdata);
}
}
/**
* Returns the size in bits of the *uncompressed* bitmap represented by this
* compressed bitmap. Initially, the sizeInBits is zero. It is extended
* automatically when you set bits to true.
*
* @return the size in bits
*/
public int sizeInBits() {
return this.sizeinbits;
}
/**
* set the size in bits
*
*/
public void setSizeInBits(final int size)
{
this.sizeinbits = size;
}
/**
* Change the reported size in bits of the *uncompressed* bitmap represented
* by this compressed bitmap. It is not possible to reduce the sizeInBits, but
* it can be extended. The new bits are set to false or true depending on the
* value of defaultvalue.
*
* @param size the size in bits
* @param defaultvalue the default boolean value
* @return true if the update was possible
*/
public boolean setSizeInBits(final int size, final boolean defaultvalue) {
if (size < this.sizeinbits)
return false;
// next loop could be optimized further
if (defaultvalue)
while (((this.sizeinbits % wordinbits) != 0) && (this.sizeinbits < size)) {
this.set(this.sizeinbits);
}
if (defaultvalue == false)
extendEmptyBits(this, this.sizeinbits, size);
else {
final int leftover = size % wordinbits;
this.addStreamOfEmptyWords(defaultvalue, (size / wordinbits) - this.sizeinbits
/ wordinbits);
final int newdata = (1 << leftover) + ((1 << leftover) - 1);
this.addLiteralWord(newdata);
}
this.sizeinbits = size;
return true;
}
/**
* For internal use. This simply adds a stream of words made of zeroes so that
* we pad to the desired size.
*
* @param storage bitmap to extend
* @param currentSize current size (in bits)
* @param newSize new desired size (in bits)
*/
private static void extendEmptyBits(final BitmapStorage32 storage, final int currentSize, final int newSize ) {
final int currentLeftover = currentSize % wordinbits;
final int finalLeftover = newSize % wordinbits;
storage.addStreamOfEmptyWords(false, (newSize / wordinbits) - currentSize
/ wordinbits + (finalLeftover != 0 ? 1 : 0) + (currentLeftover != 0 ? -1 : 0));
}
/**
* Report the *compressed* size of the bitmap (equivalent to memory usage,
* after accounting for some overhead).
*
* @return the size in bytes
*/
public int sizeInBytes() {
return this.actualsizeinwords * (wordinbits / 8);
}
/**
* For internal use (trading off memory for speed).
*
* @param size the number of words to allocate
* @return True if the operation was a success.
*/
private boolean reserve(final int size) {
if (size > this.buffer.length) {
final int oldbuffer[] = this.buffer;
this.buffer = new int[size];
System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length);
this.rlw.array = this.buffer;
return true;
}
return false;
}
/**
* For internal use.
*
* @param data the word to be added
*/
private void push_back(final int data) {
if (this.actualsizeinwords == this.buffer.length) {
final int oldbuffer[] = this.buffer;
this.buffer = new int[oldbuffer.length * 2];
System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length);
this.rlw.array = this.buffer;
}
this.buffer[this.actualsizeinwords++] = data;
}
/**
* For internal use.
*
* @param data the array of words to be added
* @param start the starting point
* @param number the number of words to add
*/
private void push_back(final int[] data, final int start, final int number) {
while (this.actualsizeinwords + number >= this.buffer.length) {
final int oldbuffer[] = this.buffer;
this.buffer = new int[oldbuffer.length * 2];
System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length);
this.rlw.array = this.buffer;
}
System.arraycopy(data, start, this.buffer, this.actualsizeinwords, number);
this.actualsizeinwords += number;
}
/**
* For internal use.
*
* @param data the array of words to be added
* @param start the starting point
* @param number the number of words to add
*/
private void negative_push_back(final int[] data, final int start,
final int number) {
while (this.actualsizeinwords + number >= this.buffer.length) {
final int oldbuffer[] = this.buffer;
this.buffer = new int[oldbuffer.length * 2];
System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length);
this.rlw.array = this.buffer;
}
for (int k = 0; k < number; ++k)
this.buffer[this.actualsizeinwords + k] = ~data[start + k];
this.actualsizeinwords += number;
}
/**
* For internal use.
*
* @param v the boolean value
* @return the storage cost of the addition
*/
private int addEmptyWord(final boolean v) {
final boolean noliteralword = (this.rlw.getNumberOfLiteralWords() == 0);
final int runlen = this.rlw.getRunningLength();
if ((noliteralword) && (runlen == 0)) {
this.rlw.setRunningBit(v);
}
if ((noliteralword) && (this.rlw.getRunningBit() == v)
&& (runlen < RunningLengthWord32.largestrunninglengthcount)) {
this.rlw.setRunningLength(runlen + 1);
return 0;
}
push_back(0);
this.rlw.position = this.actualsizeinwords - 1;
this.rlw.setRunningBit(v);
this.rlw.setRunningLength(1);
return 1;
}
/**
* For internal use.
*
* @param newdata the dirty word
* @return the storage cost of the addition
*/
private int addLiteralWord(final int newdata) {
final int numbersofar = this.rlw.getNumberOfLiteralWords();
if (numbersofar >= RunningLengthWord32.largestliteralcount) {
push_back(0);
this.rlw.position = this.actualsizeinwords - 1;
this.rlw.setNumberOfLiteralWords(1);
push_back(newdata);
return 2;
}
this.rlw.setNumberOfLiteralWords(numbersofar + 1);
push_back(newdata);
return 1;
}
/**
* reports the number of bits set to true. Running time is proportional to
* compressed size (as reported by sizeInBytes).
*
* @return the number of bits set to true
*/
public int cardinality() {
int counter = 0;
final EWAHIterator32 i = new EWAHIterator32(this.buffer, this.actualsizeinwords);
while (i.hasNext()) {
RunningLengthWord32 localrlw = i.next();
if (localrlw.getRunningBit()) {
counter += wordinbits * localrlw.getRunningLength();
}
for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) {
counter += Integer.bitCount(i.buffer()[i.dirtyWords() + j]);
}
}
return counter;
}
/**
* A string describing the bitmap.
*
* @return the string
*/
@Override
public String toString() {
String ans = " EWAHCompressedBitmap, size in bits = " + this.sizeinbits
+ " size in words = " + this.actualsizeinwords + "\n";
final EWAHIterator32 i = new EWAHIterator32(this.buffer, this.actualsizeinwords);
while (i.hasNext()) {
RunningLengthWord32 localrlw = i.next();
if (localrlw.getRunningBit()) {
ans += localrlw.getRunningLength() + " 1x11\n";
} else {
ans += localrlw.getRunningLength() + " 0x00\n";
}
ans += localrlw.getNumberOfLiteralWords() + " dirties\n";
}
return ans;
}
/**
* A more detailed string describing the bitmap (useful for debugging).
*
* @return the string
*/
public String toDebugString() {
String ans = " EWAHCompressedBitmap, size in bits = " + this.sizeinbits
+ " size in words = " + this.actualsizeinwords + "\n";
final EWAHIterator32 i = new EWAHIterator32(this.buffer, this.actualsizeinwords);
while (i.hasNext()) {
RunningLengthWord32 localrlw = i.next();
if (localrlw.getRunningBit()) {
ans += localrlw.getRunningLength() + " 1x11\n";
} else {
ans += localrlw.getRunningLength() + " 0x00\n";
}
ans += localrlw.getNumberOfLiteralWords() + " dirties\n";
for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) {
int data = i.buffer()[i.dirtyWords() + j];
ans += "\t" + data + "\n";
}
}
return ans;
}
/**
* Populate an array of (sorted integers) corresponding to the location
* of the set bits.
*
* @return the array containing the location of the set bits
*/
public int[] toArray() {
int[] ans = new int[this.cardinality()];
int inanspos = 0;
int pos = 0;
final EWAHIterator32 i = new EWAHIterator32(this.buffer, this.actualsizeinwords);
while (i.hasNext()) {
RunningLengthWord32 localrlw = i.next();
if (localrlw.getRunningBit()) {
for (int j = 0; j < localrlw.getRunningLength(); ++j) {
for (int c = 0; c < wordinbits; ++c) {
ans[inanspos++] = pos++;
}
}
} else {
pos += wordinbits * localrlw.getRunningLength();
}
for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) {
int data = i.buffer()[i.dirtyWords() + j];
while (data != 0) {
final int ntz = Integer.numberOfTrailingZeros(data);
data ^= (1 << ntz);
ans[inanspos++] = ntz + pos ;
}
pos += wordinbits;
}
}
return ans;
}
/**
* Iterator over the set bits (this is what most people will want to use to
* browse the content if they want an iterator). The location of the set bits
* is returned, in increasing order.
*
* @return the int iterator
*/
public IntIterator intIterator() {
final EWAHIterator32 i = new EWAHIterator32(this.buffer, this.actualsizeinwords);
return new IntIterator() {
int pos = 0;
RunningLengthWord32 localrlw = null;
final static int initcapacity = 512;
int[] localbuffer = new int[initcapacity];
int localbuffersize = 0;
int bufferpos = 0;
boolean status = queryStatus();
public boolean hasNext() {
return this.status;
}
public boolean queryStatus() {
while (this.localbuffersize == 0) {
if (!loadNextRLE())
return false;
loadBuffer();
}
return true;
}
private boolean loadNextRLE() {
while (i.hasNext()) {
this.localrlw = i.next();
return true;
}
return false;
}
private void add(final int val) {
++this.localbuffersize;
if (this.localbuffersize > this.localbuffer.length) {
int[] oldbuffer = this.localbuffer;
this.localbuffer = new int[this.localbuffer.length * 2];
System.arraycopy(oldbuffer, 0, this.localbuffer, 0, oldbuffer.length);
}
this.localbuffer[this.localbuffersize - 1] = val;
}
private void loadBuffer() {
this.bufferpos = 0;
this.localbuffersize = 0;
if (this.localrlw.getRunningBit()) {
for (int j = 0; j < this.localrlw.getRunningLength(); ++j) {
for (int c = 0; c < wordinbits; ++c) {
add(this.pos++);
}
}
} else {
this.pos += wordinbits * this.localrlw.getRunningLength();
}
for (int j = 0; j < this.localrlw.getNumberOfLiteralWords(); ++j) {
int data = i.buffer()[i.dirtyWords() + j];
while (data != 0) {
final int ntz = Integer.numberOfTrailingZeros(data);
data ^= (1 << ntz);
add(ntz + this.pos) ;
}
this.pos += wordinbits;
}
}
public int next() {
final int answer = this.localbuffer[this.bufferpos++];
if (this.localbuffersize == this.bufferpos) {
this.localbuffersize = 0;
this.status = queryStatus();
}
return answer;
}
};
}
/**
* iterate over the positions of the true values.
* This is similar to intIterator(), but it uses
* Java generics.
*
* @return the iterator
*/
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
final private IntIterator under = intIterator();
public Integer next() {
return new Integer(this.under.next());
}
public boolean hasNext() {
return this.under.hasNext();
}
public void remove() {
throw new UnsupportedOperationException("bitsets do not support remove");
}
};
}
/**
* get the locations of the true values as one vector. (may use more memory
* than iterator())
*
* @return the positions
*/
public List<Integer> getPositions() {
final ArrayList<Integer> v = new ArrayList<Integer>();
final EWAHIterator32 i = new EWAHIterator32(this.buffer, this.actualsizeinwords);
int pos = 0;
while (i.hasNext()) {
RunningLengthWord32 localrlw = i.next();
if (localrlw.getRunningBit()) {
for (int j = 0; j < localrlw.getRunningLength(); ++j) {
for (int c = 0; c < wordinbits; ++c)
v.add(new Integer(pos++));
}
} else {
pos += wordinbits * localrlw.getRunningLength();
}
for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) {
int data = i.buffer()[i.dirtyWords() + j];
while (data != 0) {
final int ntz = Integer.numberOfTrailingZeros(data);
data ^= (1 << ntz);
v.add(new Integer(ntz + pos)) ;
}
pos += wordinbits;
}
}
while ((v.size() > 0)
&& (v.get(v.size() - 1).intValue() >= this.sizeinbits))
v.remove(v.size() - 1);
return v;
}
/**
* Check to see whether the two compressed bitmaps contain the same data.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o instanceof EWAHCompressedBitmap32) {
EWAHCompressedBitmap32 other = (EWAHCompressedBitmap32) o;
if( this.sizeinbits == other.sizeinbits
&& this.actualsizeinwords == other.actualsizeinwords
&& this.rlw.position == other.rlw.position) {
for(int k = 0; k<this.actualsizeinwords; ++k)
if(this.buffer[k]!= other.buffer[k])
return false;
return true;
}
}
return false;
}
/**
* Returns a customized hash code (based on Karp-Rabin).
* Naturally, if the bitmaps are equal, they will hash to the same value.
*
*/
@Override
public int hashCode() {
int karprabin = 0;
final int B = 31;
for(int k = 0; k<this.actualsizeinwords; ++k) {
karprabin += B*karprabin+(this.buffer[k]& ((1<<32) - 1));
karprabin += B*karprabin+(this.buffer[k]>>> 32);
}
return this.sizeinbits ^ karprabin;
}
/*
* @see java.lang.Object#clone()
*/
@Override
public Object clone() throws java.lang.CloneNotSupportedException {
final EWAHCompressedBitmap32 clone = (EWAHCompressedBitmap32) super.clone();
clone.buffer = this.buffer.clone();
clone.actualsizeinwords = this.actualsizeinwords;
clone.sizeinbits = this.sizeinbits;
return clone;
}
/*
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
public void readExternal(ObjectInput in) throws IOException {
deserialize(in);
}
/**
* Deserialize.
*
* @param in the DataInput stream
* @throws IOException Signals that an I/O exception has occurred.
*/
public void deserialize(DataInput in) throws IOException {
this.sizeinbits = in.readInt();
this.actualsizeinwords = in.readInt();
if (this.buffer.length < this.actualsizeinwords) {
this.buffer = new int[this.actualsizeinwords];
}
for (int k = 0; k < this.actualsizeinwords; ++k)
this.buffer[k] = in.readInt();
this.rlw = new RunningLengthWord32(this.buffer, in.readInt());
}
/*
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
public void writeExternal(ObjectOutput out) throws IOException {
serialize(out);
}
/**
* Serialize.
*
* @param out the DataOutput stream
* @throws IOException Signals that an I/O exception has occurred.
*/
public void serialize(DataOutput out) throws IOException {
out.writeInt(this.sizeinbits);
out.writeInt(this.actualsizeinwords);
for (int k = 0; k < this.actualsizeinwords; ++k)
out.writeInt(this.buffer[k]);
out.writeInt(this.rlw.position);
}
/**
* Report the size required to serialize this bitmap
*
* @return the size in bytes
*/
public int serializedSizeInBytes() {
return this.sizeInBytes() + 3 * 4;
}
/**
* Clear any set bits and set size in bits back to 0
*/
public void clear() {
this.sizeinbits = 0;
this.actualsizeinwords = 1;
this.rlw.position = 0;
// buffer is not fully cleared but any new set operations should overwrite stale data
this.buffer[0] = 0;
}
/** The Constant defaultbuffersize: default memory allocation when the object is constructed. */
static final int defaultbuffersize = 4;
/** The buffer (array of 32-bit words) */
int buffer[] = null;
/** The actual size in words. */
int actualsizeinwords = 1;
/** sizeinbits: number of bits in the (uncompressed) bitmap. */
int sizeinbits = 0;
/** The current (last) running length word. */
RunningLengthWord32 rlw = null;
/** The Constant wordinbits represents the number of bits in a int. */
public static final int wordinbits = 32;
}
|
package org.opendroidphp.app;
import android.os.Environment;
public class Constants {
public static final String EXTERNAL_STORAGE = Environment.getExternalStorageDirectory().getPath();
public static final String SERVER_LOCATION = EXTERNAL_STORAGE + "/htdocs";
public static final String PROJECT_LOCATION = EXTERNAL_STORAGE + "/droidphp";
public static final String UPDATE_FROM_EXTERNAL_REPOSITORY = EXTERNAL_STORAGE + "/droidphp/repositroy/update.zip";
public static final String REPOSITORY_URL = "http://droidphp-repository.herokuapp.com/extension.json";
public static final String INTERNAL_LOCATION = "/data/data/org.opendroidphp";
public static final String LIGHTTPD_SBIN_LOCATION = INTERNAL_LOCATION + "/components/lighttpd/sbin/lighttpd";
public static final String LIGTTTPD_CONF_LOCATION = INTERNAL_LOCATION + "/components/lighttpd/conf/lighttpd.conf";
public static final String PHP_SBIN_LOCATION = INTERNAL_LOCATION + "/components/php/sbin/php-cgi";
public static final String PHP_INI_LOCATION = INTERNAL_LOCATION + "/components/php/conf/php.ini";
public static final String MYSQL_DATA_DATA_LOCATION = INTERNAL_LOCATION + "/components/mysql/sbin/data";
public static final String MYSQL_SHARE_DATA_LOCATION = INTERNAL_LOCATION + "/components/mysql/sbin/share";
public static final String MYSQL_DAEMON_SBIN_LOCATION = INTERNAL_LOCATION + "/components/mysql/sbin/mysqld";
public static final String MYSQL_INI_LOCATION = INTERNAL_LOCATION + "/components/mysql/conf/mysql.ini";
public static final String MYSQL_MONITOR_SBIN_LOCATION = INTERNAL_LOCATION + "/components/mysql/sbin/mysql-monitor";
public static final String BUSYBOX_SBIN_LOCATION = INTERNAL_LOCATION + "/components/busybox/sbin/busybox";
public static final String NGINX_SBIN_LOCATION = INTERNAL_LOCATION + "/components/nginx/sbin/nginx";
}
|
package jnr.unixsocket.example;
import jnr.enxio.channels.NativeSelectorProvider;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Set;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import jnr.unixsocket.UnixServerSocket;
import jnr.unixsocket.UnixServerSocketChannel;
import jnr.unixsocket.UnixSocketAddress;
import jnr.unixsocket.UnixSocketChannel;
public class UnixServer {
public static void main(String[] args) throws IOException {
java.io.File path = new java.io.File("/tmp/fubar.sock");
path.deleteOnExit();
UnixSocketAddress address = new UnixSocketAddress(path);
UnixServerSocketChannel channel = UnixServerSocketChannel.open();
try {
Selector sel = NativeSelectorProvider.getInstance().openSelector();
channel.configureBlocking(false);
channel.socket().bind(address);
channel.register(sel, SelectionKey.OP_ACCEPT, new ServerActor(channel, sel));
while (sel.select() > 0) {
Set<SelectionKey> keys = sel.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while ( iterator.hasNext() ) {
SelectionKey k = iterator.next();
Actor a = (Actor) k.attachment();
if (!a.rxready()) {
k.cancel();
}
iterator.remove();
}
}
} catch (IOException ex) {
Logger.getLogger(UnixServerSocket.class.getName()).log(Level.SEVERE, null, ex);
}
}
static interface Actor {
public boolean rxready();
}
static final class ServerActor implements Actor {
private final UnixServerSocketChannel channel;
private final Selector selector;
public ServerActor(UnixServerSocketChannel channel, Selector selector) {
this.channel = channel;
this.selector = selector;
}
public final boolean rxready() {
try {
UnixSocketChannel client = channel.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ, new ClientActor(client));
return true;
} catch (IOException ex) {
return false;
}
}
}
static final class ClientActor implements Actor {
private final UnixSocketChannel channel;
public ClientActor(UnixSocketChannel channel) {
this.channel = channel;
}
public final boolean rxready() {
try {
ByteBuffer buf = ByteBuffer.allocate(1024);
int n = channel.read(buf);
UnixSocketAddress remote = channel.getRemoteSocketAddress();
System.out.printf("Read in %d bytes from %s\n", n, remote);
if (n > 0) {
buf.flip();
channel.write(buf);
return true;
} else if (n < 0) {
return false;
}
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
return true;
}
}
}
|
package kalang.compiler.codegen;
import kalang.ast.AbstractAstVisitor;
import kalang.ast.AssignExpr;
import kalang.ast.AstVisitor;
import kalang.ast.BinaryExpr;
import kalang.ast.BlockStmt;
import kalang.ast.BreakStmt;
import kalang.ast.CastExpr;
import kalang.ast.CatchBlock;
import kalang.ast.ClassNode;
import kalang.ast.ConstExpr;
import kalang.ast.ContinueStmt;
import kalang.ast.ElementExpr;
import kalang.ast.ExprStmt;
import kalang.ast.FieldExpr;
import kalang.ast.IfStmt;
import kalang.ast.InvocationExpr;
import kalang.ast.ThisExpr;
import kalang.ast.LoopStmt;
import kalang.ast.MethodNode;
import kalang.ast.MultiStmtExpr;
import kalang.ast.NewArrayExpr;
import kalang.ast.ParameterExpr;
import kalang.ast.ReturnStmt;
import kalang.ast.ThrowStmt;
import kalang.ast.TryStmt;
import kalang.ast.UnaryExpr;
import kalang.ast.VarExpr;
import kalang.ast.VarObject;
import java.io.*;
import java.lang.reflect.Modifier;
import java.nio.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import kalang.AstNotFoundException;
import kalang.ast.AnnotationNode;
import kalang.ast.ArrayLengthExpr;
import kalang.ast.AssignableExpr;
import kalang.ast.AstNode;
import kalang.ast.ClassReference;
import kalang.ast.CompareExpr;
import kalang.ast.ErrorousExpr;
import kalang.ast.ExprNode;
import kalang.ast.FieldNode;
import kalang.ast.IncrementExpr;
import kalang.ast.InstanceOfExpr;
import kalang.ast.LocalVarNode;
import kalang.ast.LogicExpr;
import kalang.ast.MathExpr;
import kalang.ast.MultiStmt;
import kalang.ast.NewObjectExpr;
import kalang.ast.ObjectFieldExpr;
import kalang.ast.ObjectInvokeExpr;
import kalang.ast.ParameterNode;
import kalang.ast.PrimitiveCastExpr;
import kalang.ast.Statement;
import kalang.ast.StaticFieldExpr;
import kalang.ast.StaticInvokeExpr;
import kalang.ast.StoreArrayElementExpr;
import kalang.ast.SuperExpr;
import kalang.ast.UnknownFieldExpr;
import kalang.ast.UnknownInvocationExpr;
import kalang.ast.VarDeclStmt;
import kalang.compiler.AstLoader;
import kalang.compiler.CodeGenerator;
import kalang.core.ArrayType;
import kalang.core.ObjectType;
import kalang.core.ExecutableDescriptor;
import kalang.core.GenericType;
import kalang.core.ClassType;
import kalang.core.NullableKind;
import kalang.core.PrimitiveType;
import kalang.core.Type;
import kalang.core.Types;
import static kalang.core.Types.*;
import kalang.core.VarTable;
import kalang.core.WildcardType;
import kalang.exception.Exceptions;
import kalang.tool.OutputManager;
import kalang.util.AstUtil;
import kalang.util.MethodUtil;
import kalang.util.ModifierUtil;
import kalang.util.NameUtil;
import kalang.util.Parameters;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import static org.objectweb.asm.Opcodes.*;
/**
*The class generate the java class binary data for ast
*
* @author Kason Yang <i@kasonyang.com>
*/
public class Ast2Class extends AbstractAstVisitor<Object> implements CodeGenerator{
private ClassWriter classWriter;
private MethodVisitor md;
OutputManager outputManager;
private Map<Integer,Label> lineLabels = new HashMap();
private Map<VarObject,Integer> varIds = new HashMap<>();
private Stack<Integer> varStartIndexOfFrame = new Stack();
private Map<VarObject,Label> varStartLabels = new HashMap();
private VarTable<Integer,LocalVarNode> varTables = new VarTable();
private int varIdCounter = 0;
private Stack<Label> breakLabels = new Stack<>();
private Stack<Label> continueLabels = new Stack<>();
private Label methodStartLabel ;
private Label methodEndLabel;
private final static int
T_I = 0,
T_L = 1,
T_F = 2,
T_D = 3,
T_A = 4;
private ClassNode clazz;
private String classInternalName;
public Ast2Class(OutputManager outputManager) {
this.outputManager = outputManager;
}
private int getT(Type type){
int t;
if(
type.equals(INT_TYPE)
||type.equals(BOOLEAN_TYPE)
|| type.equals(CHAR_TYPE)
|| type.equals(BYTE_TYPE)
|| type.equals(SHORT_TYPE)
){
t = T_I;
}else if(type.equals(LONG_TYPE)){
t = T_L;
}else if(type.equals(FLOAT_TYPE)){
t = T_F;
}else if(type.equals(DOUBLE_TYPE)){
t = T_D;
}else{
t = T_A;
}
return t;
}
@Nullable
private String classSignature(ClassNode c){
GenericType[] genericTypes = c.getGenericTypes();
if(genericTypes==null || genericTypes.length==0){
return null;
}
String gnrTypeStr = "";
for(GenericType t:genericTypes){
gnrTypeStr += t.getName() + ":" + "Ljava/lang/Object;";
}
String superTypeStr = "";
if(c.superType!=null) superTypeStr += typeSignature(c.superType);
for(ObjectType itf:c.getInterfaces()){
superTypeStr += typeSignature(itf);
}
return "<" + gnrTypeStr + ">" + superTypeStr ;
}
private String methodSignature(MethodNode m){
String ptype = "";
for(ParameterNode p:m.getParameters()){
ptype += typeSignature(p.getType());
}
return "(" + ptype + ")" + typeSignature(m.getType());
}
@Nullable
private String typeSignature(Type type){
if(type instanceof GenericType){
return "T" + type.getName() + ";" ;
}else if(type instanceof ClassType){
ClassType pt = (ClassType) type;
String ptypes = "";
for(Type p:pt.getTypeArguments()){
ptypes += typeSignature(p);
}
if(!ptypes.isEmpty()) ptypes = "<" + ptypes + ">";
return "L" + pt.getClassNode().name.replace('.', '/') + ptypes + ";";
}else if(type instanceof PrimitiveType){
return getTypeDescriptor(type);
}else if(type instanceof ArrayType){
return "[" + typeSignature(((ArrayType)type).getComponentType());
}else if(type instanceof WildcardType){
WildcardType wt = (WildcardType) type;
Type[] lbs = wt.getLowerBounds();
Type[] ubs = wt.getUpperBounds();
if(lbs.length>0){
//FIXME handle other lowerBounds
return "-" + typeSignature(lbs[0]) ;
}else if(ubs.length>0){
//FIXME handle other lowerBounds
return "+" + typeSignature(ubs[0]) ;
}else{
return "*";
}
}else{
throw Exceptions.unsupportedTypeException(type);
}
}
private String internalName(String className){
return className.replace(".", "/");
}
private String[] internalNames(String[] names){
String[] inames = new String[names.length];
for(int i=0;i<names.length;i++){
inames[i] = internalName(names[i]);
}
return inames;
}
protected String getNullableAnnotation(ObjectType type){
NullableKind nullable = type.getNullable();
if(nullable == NullableKind.NONNULL){
return "kalang.annotation.Nonnull";
}else if(nullable == NullableKind.NULLABLE){
return "kalang.annotation.Nullable";
}else{
return null;
}
}
protected void annotationNullable(Object obj,ObjectType type){
String annotation = getNullableAnnotation(type);
if(annotation!=null){
try {
annotation(obj, new AnnotationNode(AstLoader.BASE_AST_LOADER.loadAst(annotation)));
} catch (AstNotFoundException ex) {
throw Exceptions.missingRuntimeClass(ex.getMessage());
}
}
}
protected void annotation(Object obj,AnnotationNode... annotations){
for(AnnotationNode an:annotations){
AnnotationVisitor av;
String desc = getTypeDescriptor(Types.getClassType(an.getAnnotationType()));
//TODO set annotation visible
boolean isVisible = true;
if(obj instanceof ClassWriter){
av = ((ClassWriter)obj).visitAnnotation(desc,isVisible);
}else if(obj instanceof MethodVisitor){
av = ((MethodVisitor)obj).visitAnnotation(desc, isVisible);
}else{
throw Exceptions.unsupportedTypeException(obj);
}
for(String v:an.values.keySet()){
//TODO handle enum value
Object javaConst = getJavaConst(an.values.get(v));
av.visit(v, javaConst);
}
}
}
@Override
public Object visitClassNode(ClassNode node) {
ClassNode oldClass = this.clazz;
this.clazz = node;
String oldClassInternalName = this.classInternalName;
this.classInternalName = internalName(clazz);
ClassWriter oldClassWriter = this.classWriter;
this.classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
annotation(classWriter, clazz.getAnnotations());
String parentName = "java.lang.Object";
ObjectType superType = node.superType;
if(superType!=null){
parentName = superType.getName();
}
String[] interfaces = null;
if(node.getInterfaces().length>0){
interfaces = internalName(node.getInterfaces());
}
int access = node.modifier;
classWriter.visit(V1_6, access,internalName(node.name),classSignature(node), internalName(parentName),interfaces); String fileName = node.fileName;
if(fileName!=null && !fileName.isEmpty()){
classWriter.visitSource(fileName, null);
}
visitChildren(node);
//clinit
if(!node.staticInitStmts.isEmpty()){
md = classWriter.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
visitAll(node.staticInitStmts);
md.visitInsn(RETURN);
md.visitMaxs(1, 1);
}
if(node.enclosingClass!=null){
this.classWriter.visitInnerClass(this.internalName(node), this.internalName(node.enclosingClass), NameUtil.getSimpleClassName(node.name), node.modifier);
}
for(ClassNode ic:node.classes){
classWriter.visitInnerClass(internalName(ic), internalName(node), NameUtil.getSimpleClassName(ic.name), ic.modifier);
}
classWriter.visitEnd();
if(outputManager!=null){
try {
try (OutputStream os = outputManager.createOutputStream(node.name)) {
os.write(this.classWriter.toByteArray());
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}else{
LOG.log(Level.WARNING, "outputManager is null");
}
this.clazz = oldClass;
this.classInternalName = oldClassInternalName;
this.classWriter = oldClassWriter;
return null;
}
private static final Logger LOG = Logger.getLogger(Ast2Class.class.getName());
@Override
public Object visitMethodNode(MethodNode node) {
int access = node.getModifier();
md = classWriter.visitMethod(access, internalName(node.getName()),getMethodDescriptor(node),methodSignature(node),internalName(node.getExceptionTypes()) );
if(node.getType() instanceof ObjectType){
annotationNullable(md,(ObjectType)node.getType());
}
annotation(md, node.getAnnotations());
this.methodStartLabel = new Label();
this.methodEndLabel = new Label();
if(AstUtil.isStatic(node.getModifier())){
varIdCounter = 0;
}else{
varIdCounter = 1;
}
BlockStmt body = node.getBody();
ParameterNode[] parameters = node.getParameters();
for(int i=0;i<parameters.length;i++){
ParameterNode p = parameters[i];
visit(p);
if(p.getType() instanceof ObjectType){
md.visitParameterAnnotation(i,getClassDescriptor(getNullableAnnotation((ObjectType)p.getType())), true).visitEnd();
}
}
md.visitLabel(methodStartLabel);
if(body!=null){
visit(body);
if(node.getType().equals(VOID_TYPE)){
md.visitInsn(RETURN);
}
md.visitLabel(methodEndLabel);
try{
md.visitMaxs(0, 0);
}catch(Exception ex){
ex.printStackTrace(System.err);
//throw new RuntimeException("exception when visit method:" + node.name, ex);
}
}
md.visitEnd();
return null;
}
private void newFrame(){
this.varStartIndexOfFrame.push(this.varIdCounter);
this.varTables = this.varTables.newStack();
}
private void popFrame(){
for(LocalVarNode v:this.varTables.values()){
this.destroyLocalVarNode(v);
}
int startVarIdx = this.varStartIndexOfFrame.pop();
this.varIdCounter = startVarIdx;
this.varTables = this.varTables.popStack();
}
private void declareNewVar(VarObject vo){
int vid = varIdCounter;
int vSize = asmType(vo.getType()).getSize();
if(vSize==0){
throw Exceptions.unexceptedException("");
}
varIdCounter+= vSize;
varIds.put(vo, vid);
Label startLabel = new Label();
md.visitLabel(startLabel);
this.varStartLabels.put(vo,startLabel);
if(vo instanceof LocalVarNode){
this.varTables.put(vid, (LocalVarNode) vo);
}
}
private void destroyLocalVarNode(LocalVarNode var){
Integer vid = this.varIds.get(var);
//TODO why vid==null
// if(vid==null){
// throw Exceptions.unexceptedValue(vid);
Label endLabel = new Label();
md.visitLabel(endLabel);
this.varIds.remove(var);
String name = var.getName();
if(vid!=null && name!=null && !name.isEmpty()){
md.visitLocalVariable(name, getTypeDescriptor(var.getType()),null ,varStartLabels.get(var), endLabel, vid);
}
}
@Override
public Object visitBlockStmt(BlockStmt node) {
this.newFrame();
visitChildren(node);
this.popFrame();
return null;
}
@Override
public Object visitBreakStmt(BreakStmt node) {
md.visitJumpInsn(GOTO, breakLabels.peek());
return null;
}
@Override
public Object visitContinueStmt(ContinueStmt node) {
md.visitJumpInsn(GOTO, continueLabels.peek());
return null;
}
private void pop(Type type){
int size = asmType(type).getSize();
if(size==1){
md.visitInsn(POP);
}else if(size==2){
md.visitInsn(POP2);
}else{
throw new UnsupportedOperationException("It is unsupported to pop for the type:" + type);
}
}
@Override
public Object visitExprStmt(ExprStmt node) {
visitChildren(node);
Type type = node.getExpr().getType();
if(type !=null && !Types.VOID_TYPE.equals(type)){
pop(type);
}
return null;
}
private void ifExpr(boolean jumpOnTrue,ExprNode condition,Label label){
if(condition instanceof LogicExpr){
LogicExpr be = (LogicExpr) condition;
ExprNode e1 = be.getExpr1();
ExprNode e2 = be.getExpr2();
String op = be.getOperation();
switch(op){
case "&&":
if(jumpOnTrue){
Label stopLabel = new Label();
ifExpr(false,e1,stopLabel);
ifExpr(false,e2,stopLabel);
md.visitJumpInsn(GOTO, label);
md.visitLabel(stopLabel);
}else{
ifExpr(false, e1, label);
ifExpr(false, e2, label);
}
break;
case "||":
if(jumpOnTrue){
ifExpr(true, e1, label);
ifExpr(true, e2, label);
}else{
Label stopLabel = new Label();
ifExpr(true, e1, stopLabel);
ifExpr(true, e2, stopLabel);
md.visitJumpInsn(GOTO, label);
md.visitLabel(stopLabel);
}
break;
default:
throw new UnsupportedOperationException("Unsupported operation:" + op);
}
}else if(condition instanceof CompareExpr){
ifCompare(jumpOnTrue,((CompareExpr) condition).getExpr1(), ((CompareExpr) condition).getExpr2(), ((CompareExpr) condition).getOperation(), label);
}else if(condition instanceof UnaryExpr && ((UnaryExpr)condition).getOperation().equals("!")){
ifExpr(!jumpOnTrue, ((UnaryExpr)condition).getExpr(), label);
}else{
visit(condition);
md.visitJumpInsn(jumpOnTrue ? IFNE : IFEQ, label);
}
}
@Override
public Object visitIfStmt(IfStmt node) {
Label stopLabel = new Label();
Label falseLabel = new Label();
ExprNode condition = node.getConditionExpr();
Statement trueBody = node.getTrueBody();
Statement falseBody = node.getFalseBody();
ifExpr(false,condition,falseLabel);
if(trueBody!=null){
visit(trueBody);
}
if(falseBody==null){
md.visitLabel(falseLabel);
}else{
md.visitJumpInsn(GOTO, stopLabel);
md.visitLabel(falseLabel);
visit(falseBody);
}
md.visitLabel(stopLabel);
return null;
}
@Override
public Object visitLoopStmt(LoopStmt node) {
//visitAll(node.initStmts);
Label startLabel = new Label();
Label stopLabel = new Label();
continueLabels.push(startLabel);
breakLabels.push(stopLabel);
md.visitLabel(startLabel);
if(node.preConditionExpr!=null){
ifExpr(false,node.preConditionExpr,stopLabel);
}
visit(node.loopBody);
if(node.postConditionExpr!=null){
ifExpr(false,node.postConditionExpr,stopLabel);
}
md.visitJumpInsn(GOTO, startLabel);
md.visitLabel(stopLabel);
continueLabels.pop();
breakLabels.pop();
return null;
}
@Override
public Object visitReturnStmt(ReturnStmt node) {
int lnsn = RETURN;
if(node.expr!=null){
visit(node.expr);
Type type = node.expr.getType();
lnsn = asmType(type).getOpcode(IRETURN);
}
md.visitInsn(lnsn);
return null;
}
@Override
public Object visitTryStmt(TryStmt node) {
Label startLabel = new Label();
Label endLabel = new Label();
Label stopLabel = new Label();
md.visitLabel(startLabel);
visit(node.getExecStmt());
md.visitJumpInsn(GOTO, stopLabel);
md.visitLabel(endLabel);
if(node.getCatchStmts()!=null){
for(CatchBlock s:node.getCatchStmts()){
this.newFrame();
Label handler = new Label();
md.visitLabel(handler);
visit(s);
md.visitJumpInsn(GOTO, stopLabel);
String type = asmType(s.catchVar.getType()).getInternalName();
md.visitTryCatchBlock(startLabel, endLabel, handler,type);
this.popFrame();
}
}
if(node.getFinallyStmt()!=null){
this.newFrame();
Label handler = new Label();
md.visitLabel(handler);
visit(node.getFinallyStmt());
md.visitJumpInsn(GOTO, stopLabel);
md.visitTryCatchBlock(startLabel, endLabel, handler, null);
this.popFrame();
}
md.visitLabel(stopLabel);
return null;
}
@Override
public Object visitCatchBlock(CatchBlock node) {
visit(node.catchVar);
int exVarId = getVarId(node.catchVar);
md.visitVarInsn(ASTORE, exVarId);
visit(node.execStmt);
return null;
}
@Override
public Object visitThrowStmt(ThrowStmt node) {
visit(node.expr);
md.visitInsn(ATHROW);
return null;
}
private void assignVarObject(VarObject to,ExprNode from){
org.objectweb.asm.Type type = asmType(to.getType());
visit(from);
int vid = getVarId(to);
md.visitVarInsn(type.getOpcode(ISTORE), vid);
}
private void assignField(FieldNode fn,ExprNode target,ExprNode expr){
int opc = PUTFIELD;
if (AstUtil.isStatic(fn.modifier)) {
opc = PUTSTATIC;
} else {
visit(target);
}
visit(expr);
md.visitFieldInsn(opc,
asmType(Types.getClassType(fn.getClassNode())).getInternalName(), fn.getName(), getTypeDescriptor(fn.getType()));
}
private void assignField(FieldExpr fieldExpr,ExprNode expr){
if(fieldExpr instanceof StaticFieldExpr){
assignField(fieldExpr.getField().getFieldNode(), null, expr);
}else if(fieldExpr instanceof ObjectFieldExpr){
assignField(fieldExpr.getField().getFieldNode(), ((ObjectFieldExpr) fieldExpr).getTarget(), expr);
}else{
throw new UnsupportedOperationException();
}
}
private void astore(ExprNode expr){
visit(expr);
org.objectweb.asm.Type type = asmType(expr.getType());
md.visitInsn(type.getOpcode(IASTORE));
}
private void assignArrayElement(ExprNode array,ExprNode key,ExprNode value){
Parameters.requireNonNull(array);
Parameters.requireNonNull(key);
Parameters.requireNonNull(value);
visit(array);
visit(key);
astore(value);
}
private void assign(ExprNode to,ExprNode from){
if(to instanceof FieldExpr){
FieldExpr toField = (FieldExpr) to;
assignField(toField, from);
}else if(to instanceof VarExpr){
assignVarObject(((VarExpr) to).getVar(), from);
}else if(to instanceof ElementExpr){
ElementExpr elementExpr = (ElementExpr) to;
assignArrayElement(elementExpr.getArrayExpr(), elementExpr.getIndex(), from);
}else{
throw new UnknownError("unknown expression:" + to);
}
}
@Override
public Object visitAssignExpr(AssignExpr node) {
assign(node.getTo(), node.getFrom());
visit(node.getTo());
return null;
}
@Override
public Object visitBinaryExpr(BinaryExpr node) {
ExprNode e1 = node.getExpr1();
ExprNode e2 = node.getExpr2();
int op;
org.objectweb.asm.Type at = asmType(node.getExpr1().getType());
switch(node.getOperation()){
case "+": op = IADD;break;
case "-" : op = ISUB;break;
case "*" : op = IMUL;break;
case "/" : op = IDIV;break;
case "%":op = IREM;break;
//bitwise
case BinaryExpr.OP_AND:op = IAND;break;
case BinaryExpr.OP_OR:op = IOR;break;
case BinaryExpr.OP_XOR: op = IXOR;break;
case BinaryExpr.OP_SHIFT_LEFT:op = ISHL;break;
case BinaryExpr.OP_SHIFT_RIGHT:op = ISHR;break;
default://logic expression
Label trueLabel = new Label();
Label stopLabel = new Label();
ifExpr(true,node, trueLabel);
constFalse();
md.visitJumpInsn(GOTO, stopLabel);
md.visitLabel(trueLabel);
constTrue();
md.visitLabel(stopLabel);
return null;
}
visit(e1);
visit(e2);
md.visitInsn(at.getOpcode(op));
return null;
}
protected Object getJavaConst(ConstExpr ce){
Object v = ce.getValue();
if(v==null){
return null;
}else if(v instanceof ClassReference){
return asmType(Types.getClassType(((ClassReference) v).getReferencedClassNode()));
}else{
Type ct = ce.getType();
if(
Types.isNumber(ct)
|| Types.isBoolean(ct)
|| ct.equals(Types.getCharClassType())
|| ct.equals(Types.getStringClassType())
){
return ce.getValue();
}
throw Exceptions.unsupportedTypeException(ce);
}
}
@Override
public Object visitConstExpr(ConstExpr node) {
Object v = getJavaConst(node);
if(v==null){
md.visitInsn(ACONST_NULL);
}else{
md.visitLdcInsn(v);
}
return null;
}
@Override
public Object visitElementExpr(ElementExpr node) {
visit(node.getArrayExpr());
visit(node.getIndex());
org.objectweb.asm.Type t = asmType(node.getType());
md.visitInsn(t.getOpcode(IALOAD));
return null;
}
@Override
public Object visitFieldExpr(FieldExpr node) {
int opc ;
String owner = internalName(node.getField().getFieldNode().getClassNode());
if(node instanceof ObjectFieldExpr){
ExprNode target =((ObjectFieldExpr)node).getTarget();
visit(target);
opc = GETFIELD;
}else if(node instanceof StaticFieldExpr){
opc = GETSTATIC;
}else{
throw new UnsupportedOperationException("unsupported field type:" + node);
}
md.visitFieldInsn(opc
,owner
, node.getField().getName()
,getTypeDescriptor(node.getType()));
return null;
}
@Override
public Object visitInvocationExpr(InvocationExpr node) {
int opc;
ExecutableDescriptor method = node.getMethod();
String ownerClass;// = internalName(node.getMethod().classNode);
if (node instanceof StaticInvokeExpr) {
opc = INVOKESTATIC;
ownerClass = internalName(((StaticInvokeExpr) node).getInvokeClass().getReferencedClassNode());
} else if(node instanceof ObjectInvokeExpr) {
ObjectInvokeExpr oie = (ObjectInvokeExpr) node;
ObjectType targetType = (ObjectType) oie.getInvokeTarget().getType();
ownerClass = internalName(targetType);
ExprNode target = oie.getInvokeTarget();
visit(target);
if (Modifier.isPrivate(method.getModifier()) || (target instanceof SuperExpr) || method.getName().equals("<init>")) {
opc = INVOKESPECIAL;
} else {
opc =ModifierUtil.isInterface(targetType.getClassNode().modifier) ?
INVOKEINTERFACE : INVOKEVIRTUAL;
}
}else{
throw Exceptions.unsupportedTypeException(node);
}
visitAll(node.getArguments());
md.visitMethodInsn(
opc
,ownerClass
,method.getName()
,getMethodDescriptor(method.getMethodNode())
);
return null;
}
@Override
public Object visitUnaryExpr(UnaryExpr node) {
Type exprType = node.getExpr().getType();
org.objectweb.asm.Type t = asmType(exprType);
visit(node.getExpr());
switch(node.getOperation()){
case UnaryExpr.OPERATION_POS:
break;
case UnaryExpr.OPERATION_NEG:
md.visitInsn(t.getOpcode(INEG));
break;
case UnaryExpr.OPERATION_NOT:
//TODO here I am not sure
constX(exprType, -1);
md.visitInsn(t.getOpcode(IXOR));
break;
//md.visitInsn(ICONST_M1);
case UnaryExpr.OPERATION_LOGIC_NOT:
Label falseLabel = new Label();
Label stopLabel = new Label();
md.visitJumpInsn(IFEQ, falseLabel);
constFalse();
md.visitJumpInsn(GOTO, stopLabel);
md.visitLabel(falseLabel);
constTrue();
md.visitLabel(stopLabel);
break;
default:
throw new UnsupportedOperationException("unsupported unary operation:" + node.getOperation());
}
return null;
}
@Override
public Object visitVarExpr(VarExpr node) {
visitVarObject(node.getVar());
return null;
}
@Override
public Object visitParameterExpr(ParameterExpr node) {
visitVarObject(node.getParameter());
return null;
}
@Override
public Object visitCastExpr(CastExpr node) {
visit(node.getExpr());
md.visitTypeInsn(CHECKCAST, internalName(node.getToType()));
return null;
}
@Override
public Object visitNewArrayExpr(NewArrayExpr node) {
visit(node.getSize());
Type t = node.getComponentType();
int opr = -1;
int op = NEWARRAY;
if(t.equals(BOOLEAN_TYPE)){
opr = T_BOOLEAN;
}else if(t.equals(CHAR_TYPE)){
opr = T_CHAR;
}else if(t.equals(SHORT_TYPE)){
opr = T_SHORT;
}else if(t.equals(INT_TYPE)){
opr = T_INT;
}else if(t.equals(LONG_TYPE)){
opr = T_LONG;
}else if(t.equals(FLOAT_TYPE)){
opr = T_FLOAT;
}else if(t.equals(DOUBLE_TYPE)){
opr = T_DOUBLE;
}else if(t.equals(BYTE_TYPE)){
opr = T_BYTE;
}else{
op = ANEWARRAY;
}
if(op==NEWARRAY){
md.visitIntInsn(op, opr);
}else{
md.visitTypeInsn(ANEWARRAY, internalName(t));
}
return null;
}
@Override
public Object visitThisExpr(ThisExpr node) {
md.visitVarInsn(ALOAD, 0);
return null;
}
@Override
public Object visitMultiStmtExpr(MultiStmtExpr node) {
visitAll(node.stmts);
visit(node.reference);
return null;
}
private String getTypeDescriptor(Type[] types){
if(types==null) return null;
if(types.length==0) return null;
String ts = "";
for(Type t:types){
ts += getTypeDescriptor(t);
}
return ts;
}
private String getTypeDescriptor(Type t){
if(t instanceof PrimitiveType){
if(t.equals(VOID_TYPE)){
return "V";
}else if(t.equals(BOOLEAN_TYPE)){
return "Z";
}else if(t.equals(LONG_TYPE)){
return "J";
}else if(t.equals(INT_TYPE)){
return "I";
}else if(t.equals(CHAR_TYPE)){
return "C";
}else if(t.equals(SHORT_TYPE)){
return "S";
}else if(t.equals(BYTE_TYPE)){
return "B";
}else if(t.equals(FLOAT_TYPE)){
return "F";
}else if(t.equals(DOUBLE_TYPE)){
return "D";
}else if(t.equals(NULL_TYPE)){
return "Ljava/lang/Object;";
}else{
throw Exceptions.unsupportedTypeException(t);
}
}else if(t instanceof ArrayType){
return "[" + getTypeDescriptor(((ArrayType)t).getComponentType());
}else if(t instanceof GenericType){
return getTypeDescriptor(((GenericType) t).getSuperType());
}else if(t instanceof ClassType){
return "L" + internalName(((ClassType) t).getClassNode().name) + ";";
}else if(t instanceof WildcardType){
return getTypeDescriptor(((WildcardType) t).getSuperType());
}else{
throw Exceptions.unsupportedTypeException(t);
}
}
private String getClassDescriptor(String className){
return "L" + internalName(className) + ";" ;
}
private String getMethodDescriptor(Type returnType,Type[] parameterTypes){
String desc = "";
String retTyp = getTypeDescriptor(returnType);
if(parameterTypes!=null){
for(Type t:parameterTypes){
desc += getTypeDescriptor(t);
}
}
return "(" + desc + ")" + retTyp;
}
private String getMethodDescriptor(MethodNode node) {
return getMethodDescriptor(node.getType(), MethodUtil.getParameterTypes(node));
}
private org.objectweb.asm.Type asmType(Type type){
String typeDesc = getTypeDescriptor(type);
return org.objectweb.asm.Type.getType(typeDesc);
}
private int getVarId(VarObject var) {
Integer vid = varIds.get(var);
if(vid==null){
throw new UnknownError("unknown var:" + var);
}
return vid;
}
private void visitVarObject(VarObject vo){
org.objectweb.asm.Type type = asmType(vo.getType());
int vid = getVarId(vo);
md.visitVarInsn(type.getOpcode(ILOAD),vid);
}
@Nonnull
private String[] internalName(@Nonnull ClassNode[] clazz){
String[] names = new String[clazz.length];
for(int i=0;i<clazz.length;i++){
names[i] = internalName(clazz[i]);
}
return names;
}
private String internalName(ClassNode clazz){
return internalName(Types.getClassType(clazz));
}
private String internalName(Type t) {
org.objectweb.asm.Type asmType = asmType(t);
Objects.requireNonNull(asmType, "couldn't get asm type for " + t);
try{
return asmType.getInternalName();
}catch(Exception ex){
throw new RuntimeException("couldn't get asm type for " + t);
}
}
private String[] internalName(Type[] types){
String[] ts = new String[types.length];
for(int i=0;i<types.length;i++){
ts[i] = internalName(types[i]);
}
return ts;
}
@Override
public void generate(ClassNode classNode){
visitClassNode(classNode);
}
@Override
public Object visitVarDeclStmt(VarDeclStmt node) {
return visitChildren(node);
}
private int getPrimitiveCastOpc(Type fromType,Type toType){
Type f = fromType;
Type tt = toType;
if(f.equals(INT_TYPE)){
if(tt.equals(LONG_TYPE)) return I2L;
else if(tt.equals(FLOAT_TYPE)) return I2F;
else if(tt.equals(DOUBLE_TYPE)) return I2D;
else if(tt.equals(SHORT_TYPE)) return I2S;
else if(tt.equals(BYTE_TYPE)) return I2B;
else if(tt.equals(CHAR_TYPE)) return I2C;
}else if(f.equals(FLOAT_TYPE)){
if(tt.equals(INT_TYPE)) return F2I;
else if(tt.equals(LONG_TYPE)) return F2L;
else if(tt.equals(DOUBLE_TYPE)) return F2D;
}else if(f.equals(LONG_TYPE)){
if(tt.equals(INT_TYPE)) return L2I;
else if(tt.equals(FLOAT_TYPE)) return L2F;
else if(tt.equals(DOUBLE_TYPE)) return L2D;
}else if(f.equals(DOUBLE_TYPE)){
if(tt.equals(INT_TYPE)) return D2I;
else if(tt.equals(LONG_TYPE)) return D2L;
else if(tt.equals(FLOAT_TYPE)) return D2F;
}else if(f.equals(BYTE_TYPE)){
if(tt.equals(SHORT_TYPE)) return 0;
else if(tt.equals(INT_TYPE)) return 0;
else if(tt.equals(LONG_TYPE)) return I2L;
else if(tt.equals(FLOAT_TYPE)) return I2F;
else if(tt.equals(DOUBLE_TYPE)) return I2D;
}else if(f.equals(CHAR_TYPE) || f.equals(SHORT_TYPE)){
if(tt.equals(INT_TYPE)) return 0;
else if(tt.equals(LONG_TYPE)) return I2L;
else if(tt.equals(FLOAT_TYPE)) return I2F;
else if(tt.equals(DOUBLE_TYPE)) return I2D;
}
throw Exceptions.unexceptedException("It is unable to cast " + fromType + " to " + toType);
}
@Override
public Object visitPrimitiveCastExpr(PrimitiveCastExpr node) {
ExprNode expr = node.getExpr();
visit(expr);
int opc;
Type ft = expr.getType();
Type tt = node.getToType();
opc = getPrimitiveCastOpc(ft, tt);
if(opc>0){
md.visitInsn(opc);
}
return null;
}
@Override
public Object visitLocalVarNode(LocalVarNode localVarNode) {
this.declareNewVar(localVarNode);
return null;
}
@Override
public Object visitParameterNode(ParameterNode parameterNode) {
md.visitParameter(parameterNode.getName(), parameterNode.modifier);
this.declareNewVar(parameterNode);
return null;
}
@Override
public Object visitFieldNode(FieldNode fieldNode) {
classWriter.visitField(fieldNode.modifier, fieldNode.getName(), getTypeDescriptor(fieldNode.getType()), null, null);
return null;
}
@Override
public Object visitNewObjectExpr(NewObjectExpr node) {
org.objectweb.asm.Type t = asmType(node.getObjectType());
md.visitTypeInsn(NEW, t.getInternalName());
md.visitInsn(DUP);
visitAll(node.getConstructor().getArguments());
md.visitMethodInsn(
INVOKESPECIAL
, t.getInternalName()
, "<init>"
,getMethodDescriptor(node.getConstructor().getMethod().getMethodNode())
, false);
return null;
}
private void dupX(Type type){
int size = asmType(type).getSize();
if(size==1) md.visitInsn(DUP);
else if(size==2) md.visitInsn(DUP2);
else throw new UnsupportedOperationException("unsupported type:" + type);
}
@Override
public Object visitIncrementExpr(IncrementExpr node) {
if(!node.isIsPrefix()){
visit(node.getExpr());
}
Type exprType = node.getExpr().getType();
ConstExpr ce = getConstX(exprType, node.isIsDesc() ? -1 : 1);
BinaryExpr be = new MathExpr(node.getExpr(),ce, "+");
AssignExpr addOne = new AssignExpr(node.getExpr(),be);
visit(addOne);
pop(exprType);
if(node.isIsPrefix()){
visit(node.getExpr());
}
return null;
}
private ConstExpr getConstX(Type type, int i) {
Object obj;
int t = getT(type);
switch (t) {
case T_I:
obj = new Integer(i);
break;
case T_L:
obj = new Long(i);
break;
case T_F:
obj = new Float(i);
break;
case T_D:
obj = new Double(i);
break;
default:
throw new UnsupportedOperationException("unsupported type:" + type);
}
return new ConstExpr(obj);
}
private void constX(Object x){
md.visitLdcInsn(x);
}
private void constX(Type type,int i) {
constX(getConstX(type, i).getValue());
}
@Override
public Object visit(AstNode node) {
int lineNum = node.offset.startLine;
if(lineNum>0 && (node instanceof Statement || node instanceof ExprNode) && !lineLabels.containsKey(lineNum)){
Label lb = new Label();
md.visitLabel(lb);
md.visitLineNumber(lineNum, lb);
lineLabels.put(lineNum, lb);
}
return super.visit(node);
}
@Override
public Object visitArrayLengthExpr(ArrayLengthExpr node) {
visit(node.getArrayExpr());
md.visitInsn(ARRAYLENGTH);
return null;
}
private void constTrue(){
constX(1);
}
private void constFalse(){
constX(0);
}
@Override
public Object visitUnknownFieldExpr(UnknownFieldExpr node) {
throw new UnsupportedOperationException("BUG:invoking unknown method:" + node.getFieldName());
}
@Override
public Object visitUnknownInvocationExpr(UnknownInvocationExpr node) {
throw new UnsupportedOperationException("BUG:invoking unknown method:" + node.getMethodName());
}
@Override
public Object visitClassReference(ClassReference node) {
//do nothing
return null;
}
@Override
public Object visitSuperExpr(SuperExpr node) {
md.visitVarInsn(ALOAD, 0);
return null;
}
@Override
public Object visitErrorousExpr(ErrorousExpr node) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object visitInstanceOfExpr(InstanceOfExpr node) {
visit(node.getExpr());
md.visitTypeInsn(INSTANCEOF, internalName(node.getTarget().getReferencedClassNode()));
return null;
}
private void ifCompare(boolean jumpOnTrue,ExprNode expr1, ExprNode expr2, String op, Label label) {
Type type = expr1.getType();
visit(expr1);
visit(expr2);
int t = getT(type);
if(T_I == t){
int opc = -1;
switch(op){
case "==" :
opc = jumpOnTrue ? IF_ICMPEQ : IF_ICMPNE;
break;
case ">" :
opc =jumpOnTrue ? IF_ICMPGT : IF_ICMPLE;
break;
case ">=" :
opc =jumpOnTrue ? IF_ICMPGE : IF_ICMPLT;
break;
case "<" :
opc = jumpOnTrue ? IF_ICMPLT : IF_ICMPGE;
break;
case "<=" :
opc =jumpOnTrue ? IF_ICMPLE : IF_ICMPGT;
break;
case "!=" :
opc = jumpOnTrue ? IF_ICMPNE : IF_ACMPEQ;
break;
default:
throw new UnsupportedOperationException("Unsupported operation:" + op);
}
md.visitJumpInsn(opc, label);
}else if(T_A==t){//object type
if(op.equals("==")){
md.visitJumpInsn(jumpOnTrue ? IF_ACMPEQ : IF_ACMPNE,label);
}else if(op.equals("!=")){
md.visitJumpInsn(jumpOnTrue ? IF_ACMPNE:IF_ACMPEQ,label);
}else{
throw new UnsupportedOperationException("It is unsupported to compare object type:" + type);
}
}else{//type is not int,not object
if(T_L==t){
md.visitInsn(LCMP);
}else if(T_F==t){
md.visitInsn(FCMPL);
}else if(T_D==t){
md.visitInsn(DCMPL);
}else{
throw new UnsupportedOperationException("It is unsupported to compare object type:" + type);
}
int opc = -1;
switch(op){
case "==" : opc =jumpOnTrue ? IFEQ : IFNE;break;
case ">" : opc =jumpOnTrue ? IFGT : IFLE ;break;
case ">=" : opc =jumpOnTrue ? IFGE : IFLT ;break;
case "<" : opc =jumpOnTrue ? IFLT:IFGE;break;
case "<=" : opc =jumpOnTrue ? IFLE:IFGT;break;
case "!=" : opc =jumpOnTrue ? IFNE:IFEQ;break;
default:
throw new UnsupportedOperationException("Unsupported operation:" + op);
}
md.visitJumpInsn(opc, label);
}
}
@Override
public Object visitMultiStmt(MultiStmt node) {
visitAll(node.statements);
return null;
}
@Override
public Object visitStoreArrayElementExpr(StoreArrayElementExpr node) {
md.visitVarInsn(ALOAD, this.getVarId(node.getArray()));
visit(node.getIndex());
astore(node.getValueExpr());
return null;
}
}
|
package li.l1t.tingo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class TingoErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
@Autowired
private ErrorAttributes errorAttributes;
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public String errorHtml(HttpServletRequest request, Model model) {
Object errCodeObj = request.getAttribute("javax.servlet.error.status_code");
int errorCode = errCodeObj == null ? 0 : (int) errCodeObj;
model.addAttribute("errorCode", errCodeObj);
model.addAttribute("errorType", request.getAttribute("javax.servlet.error.exception"));
switch(errorCode) {
case 401:
return "error/401";
case 0:
default:
return "error/generic";
}
}
}
|
package me.geso.jtt;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import me.geso.jtt.vm.Irep;
class CacheEntry {
final Irep irep;
final long mtime;
CacheEntry(Irep irep, long mtime) {
this.irep = irep;
this.mtime = mtime;
}
}
public class InMemoryTemplateCache implements TemplateCache {
Map<String, CacheEntry> cache = new ConcurrentHashMap<>();
public enum CacheMode {
NO_CACHE, CACHE_WITH_UPDATE_CHECK, CACHE_BUT_DO_NOT_CHECK_UPDATES,
}
private final CacheMode cacheMode;
public InMemoryTemplateCache(CacheMode cacheMode) {
this.cacheMode = cacheMode;
}
@Override
public Irep get(Path filePath) {
CacheEntry entry = cache.get(filePath.toAbsolutePath().toString());
if (entry == null) {
return null;
} else {
if (cacheMode == CacheMode.CACHE_WITH_UPDATE_CHECK) {
if (filePath.toFile().lastModified() >= entry.mtime) {
return null;
}
}
return entry.irep;
}
}
@Override
public void set(Path filePath, Irep irep) {
if (cacheMode == CacheMode.NO_CACHE) {
return;
}
CacheEntry entry = new CacheEntry(irep, filePath.toFile()
.lastModified());
cache.put(filePath.toAbsolutePath().toString(), entry);
}
public int size() {
return cache.size();
}
}
|
package me.ianhe.isite.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
/**
* @author iHelin
* @since 2018/4/27 21:09
*/
@Configuration
public class RedisConfig {
/*@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//CacheManagerJdkSerializationRedisSerializer,RedisCacheConfigurationStringRedisSerializerkeyJdkSerializationRedisSerializervalue,
Jackson2JsonRedisSerializer redisSerializer = new Jackson2JsonRedisSerializer(Article.class);
RedisSerializationContext.SerializationPair<Article> pair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer);
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
//30
defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
//RedisCacheManager
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
template.setDefaultSerializer(serializer);
return template;
}
}
|
package nl.mpi.kinnate.kindata;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Entity")
public class EntityData {
public enum SymbolType {
// symbol terms are used here to try to keep things agnostic
square, triangle, circle, union, resource, ego, none
}
@XmlElement(name = "Identifier")
private String uniqueIdentifier;
@XmlElement(name = "Path")
private String entityPath;
private String[] kinTypeArray = new String[]{};
private String[] kinTermArray = new String[]{};
private SymbolType symbolType;
@XmlElement(name = "Symbol")
private String symbolTypeString;
@XmlElement(name = "DateOfBirth")
private Date dateOfBirth;
public boolean isEgo = false;
@XmlElementWrapper(name = "Labels")
@XmlElement(name = "String")
private String[] labelStringArray;
ArrayList<String> tempLabelsList = null;
@XmlElementWrapper(name = "Relations")
@XmlElement(name = "Relation")
private EntityRelation[] relatedNodes;
protected int xPos;
protected int yPos;
public boolean isVisible = false;
private EntityRelation[] visiblyRelateNodes = null;
private EntityRelation[] distinctRelateNodes = null;
private EntityData() {
}
public EntityData(String uniqueIdentifierLocal, String entityPathLocal, String kinTypeStringLocal, String symbolTypeLocal, String[] labelStringLocal, boolean isEgoLocal) {
uniqueIdentifier = uniqueIdentifierLocal;
entityPath = entityPathLocal;
kinTypeArray = new String[]{kinTypeStringLocal};
symbolType = null;
symbolTypeString = symbolTypeLocal;
labelStringArray = labelStringLocal;
isEgo = isEgoLocal;
}
public EntityData(String uniqueIdentifierLocal, String entityPathLocal, String kinTypeStringLocal, SymbolType symbolIndex, String[] labelStringLocal, boolean isEgoLocal) {
uniqueIdentifier = uniqueIdentifierLocal;
entityPath = entityPathLocal;
kinTypeArray = new String[]{kinTypeStringLocal};
symbolType = symbolIndex;
labelStringArray = labelStringLocal;
isEgo = isEgoLocal;
}
public int getxPos() {
return xPos;
}
public void setxPos(int xPos) {
this.xPos = xPos;
}
public int getyPos() {
return yPos;
}
// public void setyPos(int yPos) {
// // todo: y position cannot be set in the default layout of vertical generations
// // this.yPos = yPos;
public String getSymbolType() {
if (symbolType != null) {
switch (symbolType) {
case circle:
return "circle";
case ego:
return "square";
case none:
return "none";
case resource:
return "resource";
case square:
return "square";
case triangle:
return "triangle";
case union:
return "union";
}
}
return symbolTypeString;
}
public String getEntityPath() {
return entityPath;
}
public void addKinTypeString(String kinTypeString) {
ArrayList<String> tempList = new ArrayList<String>(Arrays.asList(kinTypeArray));
tempList.add(kinTypeString);
kinTypeArray = tempList.toArray(new String[]{});
}
public String[] getKinTypeStrings() {
return kinTypeArray;
}
public void addKinTermString(String kinTermString) {
ArrayList<String> tempList = new ArrayList<String>(Arrays.asList(kinTermArray));
tempList.add(kinTermString);
kinTermArray = tempList.toArray(new String[]{});
}
public String[] getKinTermStrings() {
return kinTermArray;
}
public String[] getLabel() {
if (tempLabelsList != null) {
return tempLabelsList.toArray(new String[]{});
} else {
return labelStringArray;
}
}
public void clearTempLabels() {
tempLabelsList = null;
}
public void appendTempLabel(String labelString) {
if (tempLabelsList == null) {
tempLabelsList = new ArrayList<String>(Arrays.asList(labelStringArray));
}
if (!tempLabelsList.contains(labelString)) {
tempLabelsList.add(labelString);
}
}
public void addRelatedNode(EntityData alterNodeLocal, int generationalDistance, DataTypes.RelationType relationType, DataTypes.RelationLineType relationLineType, String lineColourLocal, String labelString) {
// note that the test gedcom file has multiple links for a given pair so in might be necessary to filter incoming links on a preferential basis
EntityRelation nodeRelation = new EntityRelation();
nodeRelation.setAlterNode(alterNodeLocal);
nodeRelation.generationalDistance = generationalDistance;
nodeRelation.relationType = relationType;
nodeRelation.relationLineType = relationLineType;
nodeRelation.labelString = labelString;
nodeRelation.lineColour = lineColourLocal;
if (relatedNodes != null) {
ArrayList<EntityRelation> relatedNodesList = new ArrayList<EntityRelation>();
relatedNodesList.addAll(Arrays.asList(relatedNodes));
relatedNodesList.add(nodeRelation);
relatedNodes = relatedNodesList.toArray(new EntityRelation[]{});
} else {
relatedNodes = new EntityRelation[]{nodeRelation};
}
}
public void clearVisibility() {
isVisible = false;
isEgo = false;
visiblyRelateNodes = null;
distinctRelateNodes = null;
}
public EntityRelation[] getVisiblyRelateNodes() {
if (visiblyRelateNodes == null) {
ArrayList<EntityRelation> visiblyRelatedNodes = new ArrayList<EntityRelation>();
for (EntityRelation nodeRelation : getDistinctRelateNodes()) {
if (nodeRelation.getAlterNode() != null) {
if (nodeRelation.getAlterNode().isVisible) {
visiblyRelatedNodes.add(nodeRelation);
}
}
}
visiblyRelateNodes = visiblyRelatedNodes.toArray(new EntityRelation[]{});
}
return visiblyRelateNodes;
}
public EntityRelation[] getDistinctRelateNodes() {
if (distinctRelateNodes == null) {
ArrayList<String> processedIds = new ArrayList<String>();
ArrayList<EntityRelation> uniqueNodes = new ArrayList<EntityRelation>();
if (relatedNodes != null) {
for (EntityRelation nodeRelation : relatedNodes) {
if (!processedIds.contains(nodeRelation.alterUniqueIdentifier)) {
uniqueNodes.add(nodeRelation);
processedIds.add(nodeRelation.alterUniqueIdentifier);
}
}
}
distinctRelateNodes = uniqueNodes.toArray(new EntityRelation[]{});
}
return distinctRelateNodes;
}
public String getUniqueIdentifier() {
return uniqueIdentifier;
}
}
|
package nl.wiegman.home.config;
import nl.wiegman.home.service.api.*;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;
import javax.ws.rs.ApplicationPath;
@Configuration
@ApplicationPath("/rest")
public class RestConfig extends ResourceConfig {
public RestConfig() {
register(CacheServiceRest.class);
register(GasServiceRest.class);
register(KlimaatServiceRest.class);
register(KostenServiceRest.class);
register(MeterstandServiceRest.class);
register(MindergasnlSettingsServiceRest.class);
register(StroomServiceRest.class);
// packages("nl.wiegman.home.service");
}
}
|
package polyglot.types;
import java.util.ArrayList;
import java.util.List;
import polyglot.frontend.*;
import polyglot.frontend.goals.FieldConstantsChecked;
import polyglot.frontend.goals.Goal;
import polyglot.types.*;
import polyglot.util.*;
/**
* A <code>FieldInstance</code> contains type information for a field.
*/
public class FieldInstance_c extends VarInstance_c implements FieldInstance
{
protected ReferenceType container;
/** Used for deserializing types. */
protected FieldInstance_c() { }
public FieldInstance_c(TypeSystem ts, Position pos,
ReferenceType container,
Flags flags, Type type, String name) {
super(ts, pos, flags, type, name);
this.container = container;
}
public FieldInstance orig() {
return (FieldInstance) declaration();
}
public FieldInstance flags(Flags flags) {
if (!flags.equals(this.flags)) {
FieldInstance n = (FieldInstance) copy();
n.setFlags(flags);
return n;
}
return this;
}
public FieldInstance name(String name) {
if ((name != null && !name.equals(this.name)) ||
(name == null && this.name != null)) {
FieldInstance n = (FieldInstance) copy();
n.setName(name);
return n;
}
return this;
}
public FieldInstance type(Type type) {
if (this.type != type) {
FieldInstance n = (FieldInstance) copy();
n.setType(type);
return n;
}
return this;
}
public FieldInstance container(ReferenceType container) {
if (this.container != container) {
FieldInstance_c n = (FieldInstance_c) copy();
n.setContainer(container);
return n;
}
return this;
}
public FieldInstance constantValue(Object constantValue) {
if (!constantValueSet
|| (constantValue != null && !constantValue.equals(this.constantValue))
|| (constantValue == null && this.constantValue != null)) {
FieldInstance copy = (FieldInstance) this.copy();
copy.setConstantValue(constantValue);
return copy;
}
return this;
}
public FieldInstance notConstant() {
if (! this.constantValueSet || this.isConstant) {
FieldInstance copy = (FieldInstance) this.copy();
copy.setNotConstant();
return copy;
}
return this;
}
public ReferenceType container() {
return container;
}
public boolean isConstant() {
if (this != orig()) {
return orig().isConstant();
}
if (! constantValueSet) {
if (this.isCanonical() && (! flags.isFinal() || !type.isPrimitive() && !type.equals(ts.String()))) {
// Only primitive-typed or String-typed fields can be constant.
setNotConstant();
return isConstant;
}
Scheduler scheduler = typeSystem().extensionInfo().scheduler();
Goal g = scheduler.FieldConstantsChecked(this);
throw new MissingDependencyException(g);
}
return isConstant;
}
/**
* @param container The container to set.
*/
public void setContainer(ReferenceType container) {
this.container = container;
}
public boolean equalsImpl(TypeObject o) {
if (o instanceof FieldInstance) {
FieldInstance i = (FieldInstance) o;
return super.equalsImpl(i) && ts.equals(container, i.container());
}
return false;
}
public String toString() {
Object v = constantValue;
if (v instanceof String) {
String s = (String) v;
if (s.length() > 8) {
s = s.substring(0, 8) + "...";
}
v = "\"" + s + "\"";
}
return "field " + flags.translate() + type + " " +
container + "." + name +
(isConstant ? (" = " + v) : "");
}
public boolean isCanonical() {
return container.isCanonical() && type.isCanonical();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.sam;
import org.apache.log4j.Logger;
import org.broad.igv.feature.Range;
import org.broad.igv.feature.Strand;
import java.util.*;
/**
* Packs alignments such that there is no overlap
*
* @author jrobinso
*/
public class AlignmentPacker {
private static final Logger log = Logger.getLogger(AlignmentPacker.class);
/**
* Minimum gap between the end of one alignment and start of another.
*/
public static final int MIN_ALIGNMENT_SPACING = 2;
private static final Comparator<Alignment> lengthComparator = new Comparator<Alignment>() {
public int compare(Alignment row1, Alignment row2) {
return (row2.getEnd() - row2.getStart()) -
(row1.getEnd() - row2.getStart());
}
};
private static final String NULL_GROUP_VALUE = "";
public static final int tenMB = 10000000;
/**
* Allocates each alignment to row such that there is no overlap.
*/
public PackedAlignments packAlignments(
AlignmentInterval interval,
AlignmentTrack.RenderOptions renderOptions) {
LinkedHashMap<String, List<Row>> packedAlignments = new LinkedHashMap<String, List<Row>>();
List<Alignment> alList = interval.getAlignments();
// TODO -- means to undo this
if (renderOptions.isLinkedReads()) {
alList = linkByTag(alList, renderOptions.getLinkByTag());
}
if (renderOptions.getGroupByOption() == null) {
List<Row> alignmentRows = new ArrayList<>(10000);
pack(alList, renderOptions, alignmentRows);
packedAlignments.put("", alignmentRows);
} else {
// Separate alignments into groups.
Map<Object, List<Alignment>> groupedAlignments = new HashMap<Object, List<Alignment>>();
Iterator<Alignment> iter = alList.iterator();
while (iter.hasNext()) {
Alignment alignment = iter.next();
Object groupKey = getGroupValue(alignment, renderOptions);
if (groupKey == null) {
groupKey = NULL_GROUP_VALUE;
}
List<Alignment> groupList = groupedAlignments.get(groupKey);
if (groupList == null) {
groupList = new ArrayList<>(1000);
groupedAlignments.put(groupKey, groupList);
}
groupList.add(alignment);
}
// Now alphabetize (sort) and pack the groups
List<Object> keys = new ArrayList<Object>(groupedAlignments.keySet());
Comparator<Object> groupComparator = getGroupComparator(renderOptions.getGroupByOption());
Collections.sort(keys, groupComparator);
for (Object key : keys) {
List<Row> alignmentRows = new ArrayList<>(10000);
List<Alignment> group = groupedAlignments.get(key);
pack(group, renderOptions, alignmentRows);
packedAlignments.put(key.toString(), alignmentRows);
}
}
List<AlignmentInterval> tmp = new ArrayList<AlignmentInterval>();
tmp.add(interval);
return new PackedAlignments(tmp, packedAlignments);
}
private void pack(List<Alignment> alList, AlignmentTrack.RenderOptions renderOptions, List<Row> alignmentRows) {
Map<String, PairedAlignment> pairs = null;
boolean isPairedAlignments = renderOptions.isViewPairs();
String linkByTag = renderOptions.getLinkByTag();
if (isPairedAlignments) {
pairs = new HashMap<>(1000);
}
// Allocate alignemnts to buckets for each range.
// We use priority queues to keep the buckets sorted by alignment length. However this is probably a needless
// complication, any collection type would do.
int totalCount = 0;
if (alList == null || alList.size() == 0) return;
Range curRange = getAlignmentListRange(alList);
BucketCollection bucketCollection;
// Use dense buckets for < 10,000,000 bp windows sparse otherwise
int bpLength = curRange.getLength();
if (bpLength < tenMB) {
bucketCollection = new DenseBucketCollection(bpLength, curRange);
} else {
bucketCollection = new SparseBucketCollection(curRange);
}
int curRangeStart = curRange.getStart();
for (Alignment al : alList) {
if (al.isMapped()) {
Alignment alignment = al;
// Pair alignments -- do not pair secondaryalignments
if (isPairedAlignments && isPairable(al)) {
String readName = al.getReadName();
PairedAlignment pair = pairs.get(readName);
if (pair == null) {
pair = new PairedAlignment(al);
pairs.put(readName, pair);
alignment = pair;
} else {
// Add second alignment to pair.
pair.setSecondAlignment(al);
pairs.remove(readName);
continue;
}
}
// Allocate to bucket.
// Negative "bucketNumbers" can arise with soft clips at the left edge of the chromosome. Allocate
// these alignments to the first bucket.
int bucketNumber = Math.max(0, al.getStart() - curRangeStart);
if (bucketNumber < bucketCollection.getBucketCount()) {
PriorityQueue<Alignment> bucket = bucketCollection.get(bucketNumber);
if (bucket == null) {
bucket = new PriorityQueue<Alignment>(5, lengthComparator);
bucketCollection.set(bucketNumber, bucket);
}
bucket.add(alignment);
totalCount++;
} else {
log.debug("Alignment out of bounds. name: " + alignment.getReadName() + " startPos:" + alignment.getStart());
}
}
}
bucketCollection.finishedAdding();
// Now allocate alignments to rows.
long t0 = System.currentTimeMillis();
int allocatedCount = 0;
Row currentRow = new Row();
while (allocatedCount < totalCount) {
curRange = bucketCollection.getRange();
curRangeStart = curRange.getStart();
int nextStart = curRangeStart;
List<Integer> emptyBuckets = new ArrayList<Integer>(100);
while (true) {
int bucketNumber = nextStart - curRangeStart;
PriorityQueue<Alignment> bucket = bucketCollection.getNextBucket(bucketNumber, emptyBuckets);
// Pull the next alignment out of the bucket and add to the current row
if (bucket != null) {
Alignment alignment = bucket.remove();
currentRow.addAlignment(alignment);
allocatedCount++;
nextStart = alignment.getEnd() + MIN_ALIGNMENT_SPACING;
}
//Reached the end of this range, move to the next
if (bucket == null || nextStart > curRange.getEnd()) {
//Remove empty buckets. This has no affect on the dense implementation,
//they are removed on the fly, but is needed for the sparse implementation
bucketCollection.removeBuckets(emptyBuckets);
emptyBuckets.clear();
break;
}
}
// We've reached the end of the interval, start a new row
if (currentRow.alignments.size() > 0) {
alignmentRows.add(currentRow);
}
currentRow = new Row();
}
if (log.isDebugEnabled()) {
long dt = System.currentTimeMillis() - t0;
log.debug("Packed alignments in " + dt);
}
// Add the last row
if (currentRow != null && currentRow.alignments.size() > 0) {
alignmentRows.add(currentRow);
}
}
private boolean isPairable(Alignment al) {
return al.isPrimary() &&
al.isPaired() &&
al.getMate().isMapped() &&
al.getMate().getChr().equals(al.getChr());
}
private List<Alignment> linkByTag(List<Alignment> alList, String tag) {
List<Alignment> bcList = new ArrayList<>(alList.size() / 10);
Map<Object, LinkedAlignment> map = new HashMap<>(bcList.size() * 2);
for (Alignment a : alList) {
if(a.isPrimary()) {
Object bc;
if("READNAME".equals(tag)) {
bc = a.getReadName();
if(a.isPaired()) {
bc += a.isFirstOfPair() ? "/1" : "/2";
}
}
else {
bc = a.getAttribute(tag);
}
if (bc == null) {
bcList.add(a);
} else {
LinkedAlignment linkedAlignment = map.get(bc);
if (linkedAlignment == null) {
linkedAlignment = new LinkedAlignment(tag, bc.toString());
map.put(bc, linkedAlignment);
bcList.add(linkedAlignment);
}
linkedAlignment.addAlignment(a);
}
}
else {
// Don't link secondary reads
bcList.add(a);
}
}
// Now copy list, de-linking orhpaned alignments (alignments with no linked mates)
List<Alignment> delinkedList = new ArrayList<>(alList.size());
for(Alignment a : bcList) {
if(a instanceof LinkedAlignment) {
final List<Alignment> alignments = ((LinkedAlignment) a).alignments;
if(alignments.size() == 1) {
delinkedList.add(alignments.get(0));
}
else {
a.finish();
delinkedList.add(a);
}
}
else {
delinkedList.add(a);
}
}
return delinkedList;
}
/**
* Gets the range over which alignmentsList spans. Asssumes all on same chr, and sorted
*
* @param alignmentsList
* @return
*/
private Range getAlignmentListRange(List<Alignment> alignmentsList) {
if (alignmentsList == null || alignmentsList.size() == 0) return null;
Alignment firstAlignment = alignmentsList.get(0);
int minStart = firstAlignment.getStart();
int maxEnd = firstAlignment.getEnd();
for (Alignment alignment : alignmentsList) {
maxEnd = Math.max(maxEnd, alignment.getEnd());
}
return new Range(firstAlignment.getChr(), minStart,
maxEnd);
}
private Comparator<Object> getGroupComparator(AlignmentTrack.GroupOption groupByOption) {
switch (groupByOption) {
case PAIR_ORIENTATION:
return new PairOrientationComparator();
default:
//Sort null values towards the end
return new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
if (o1 == null && o2 == null) {
return 0;
} else if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
} else {
// no nulls
if (o1.equals(o2)) {
return 0;
} else if (o1 instanceof String && NULL_GROUP_VALUE.equals(o1)) {
return 1;
} else if (o2 instanceof String && NULL_GROUP_VALUE.equals(o2)) {
return -1;
} else {
if (o1 instanceof Integer && o2 instanceof Integer) {
Integer i1 = (Integer) o1, i2 = (Integer) o2;
return i1.compareTo(i2);
}
else if (o1 instanceof Float && o2 instanceof Float) {
Float f1 = (Float) o1, f2 = (Float) o2;
return f1.compareTo(f2);
}
else if (o1 instanceof Double && o2 instanceof Double) {
Double d1 = (Double) o1, d2 = (Double) o2;
return d1.compareTo(d2);
}
else {
String s1 = o1.toString(), s2 = o2.toString();
return s1.compareToIgnoreCase(s2);
}
}
}
}
};
}
}
private Object getGroupValue(Alignment al, AlignmentTrack.RenderOptions renderOptions) {
AlignmentTrack.GroupOption groupBy = renderOptions.getGroupByOption();
String tag = renderOptions.getGroupByTag();
Range pos = renderOptions.getGroupByPos();
String readNameParts[], movieName, zmw;
switch (groupBy) {
case STRAND:
return al.isNegativeStrand() ? "-" : "+";
case SAMPLE:
return al.getSample();
case LIBRARY:
return al.getLibrary();
case READ_GROUP:
return al.getReadGroup();
case TAG:
Object tagValue = al.getAttribute(tag);
if (tagValue == null) {
return null;
}
else if (tagValue instanceof Integer || tagValue instanceof Float || tagValue instanceof Double) {
return tagValue;
}
else {
return tagValue.toString();
}
case FIRST_OF_PAIR_STRAND:
Strand strand = al.getFirstOfPairStrand();
String strandString = strand == Strand.NONE ? null : strand.toString();
return strandString;
case PAIR_ORIENTATION:
PEStats peStats = AlignmentRenderer.getPEStats(al, renderOptions);
AlignmentTrack.OrientationType type = AlignmentRenderer.getOrientationType(al, peStats);
if (type == null) {
return AlignmentTrack.OrientationType.UNKNOWN.name();
}
return type.name();
case MATE_CHROMOSOME:
ReadMate mate = al.getMate();
if (mate == null) {
return null;
}
if (mate.isMapped() == false) {
return "UNMAPPED";
} else {
return mate.getChr();
}
case SUPPLEMENTARY:
return al.isSupplementary() ? "SUPPLEMENTARY" : "";
case BASE_AT_POS:
// Use a string prefix to enforce grouping rules:
// 1: alignments with a base at the position
// 2: alignments with a gap at the position
// 3: alignment that do not overlap the position (or are on a different chromosome)
if (al.getChr().equals(pos.getChr()) &&
al.getAlignmentStart() <= pos.getStart() &&
al.getAlignmentEnd() > pos.getStart()) {
byte[] baseAtPos = new byte[] {al.getBase(pos.getStart())};
if (baseAtPos[0] == 0) { // gap at position
return "2:";
}
else { // base at position
return "1:" + new String(baseAtPos);
}
}
else { // does not overlap position
return "3:";
}
case MOVIE: // group PacBio reads by movie
readNameParts = al.getReadName().split("/");
if (readNameParts.length != 3) {
return "";
}
movieName = readNameParts[0];
return movieName;
case ZMW: // group PacBio reads by ZMW
readNameParts = al.getReadName().split("/");
if (readNameParts.length != 3) {
return "";
}
movieName = readNameParts[0];
zmw = readNameParts[1];
return movieName + "/" + zmw;
}
return null;
}
interface BucketCollection {
Range getRange();
void set(int idx, PriorityQueue<Alignment> bucket);
PriorityQueue<Alignment> get(int idx);
PriorityQueue<Alignment> getNextBucket(int bucketNumber, Collection<Integer> emptyBuckets);
void removeBuckets(Collection<Integer> emptyBuckets);
void finishedAdding();
int getBucketCount();
}
/**
* Dense array implementation of BucketCollection. Assumption is all or nearly all the genome region is covered
* with reads.
*/
static class DenseBucketCollection implements BucketCollection {
Range range;
int lastBucketNumber = -1;
final PriorityQueue[] bucketArray;
DenseBucketCollection(int bucketCount, Range range) {
this.bucketArray = new PriorityQueue[bucketCount];
this.range = range;
}
public void set(int idx, PriorityQueue<Alignment> bucket) {
bucketArray[idx] = bucket;
}
public PriorityQueue<Alignment> get(int idx) {
return bucketArray[idx];
}
public int getBucketCount() {
return this.bucketArray.length;
}
public Range getRange() {
return range;
}
/**
* Return the next occupied bucket after bucketNumber
*
* @param bucketNumber
* @param emptyBuckets ignored
* @return
*/
public PriorityQueue<Alignment> getNextBucket(int bucketNumber, Collection<Integer> emptyBuckets) {
if (bucketNumber == lastBucketNumber) {
// TODO -- detect inf loop here
}
PriorityQueue<Alignment> bucket = null;
while (bucketNumber < bucketArray.length) {
if (bucketNumber < 0) {
log.info("Negative bucket number: " + bucketNumber);
}
bucket = bucketArray[bucketNumber];
if (bucket != null) {
if (bucket.isEmpty()) {
bucketArray[bucketNumber] = null;
} else {
return bucket;
}
}
bucketNumber++;
}
return null;
}
public void removeBuckets(Collection<Integer> emptyBuckets) {
// Nothing to do, empty buckets are removed "on the fly"
}
public void finishedAdding() {
// nothing to do
}
}
/**
* "Sparse" implementation of an alignment BucketCollection. Assumption is there are small clusters of alignments
* along the genome, with mostly "white space".
*/
static class SparseBucketCollection implements BucketCollection {
Range range;
boolean finished = false;
List<Integer> keys;
final HashMap<Integer, PriorityQueue<Alignment>> buckets;
SparseBucketCollection(Range range) {
this.range = range;
this.buckets = new HashMap(1000);
}
public void set(int idx, PriorityQueue<Alignment> bucket) {
if (finished) {
log.error("Error: bucket added after finishAdding() called");
}
buckets.put(idx, bucket);
}
public PriorityQueue<Alignment> get(int idx) {
return buckets.get(idx);
}
public Range getRange() {
return range;
}
/**
* Return the next occupied bucket at or after after bucketNumber.
*
* @param bucketNumber -- the hash bucket index for the alignments, essential the position relative to the start
* of this packing interval
* @return the next occupied bucket at or after bucketNumber, or null if there are none.
*/
public PriorityQueue<Alignment> getNextBucket(int bucketNumber, Collection<Integer> emptyBuckets) {
PriorityQueue<Alignment> bucket = null;
int min = 0;
int max = keys.size() - 1;
// Get close to the right index, rather than scan from the beginning
while ((max - min) > 5) {
int mid = (max + min) / 2;
Integer key = keys.get(mid);
if (key > bucketNumber) {
max = mid;
} else {
min = mid;
}
}
// Now march from min to max until we cross bucketNumber
for (int i = min; i < keys.size(); i++) {
Integer key = keys.get(i);
if (key >= bucketNumber) {
bucket = buckets.get(key);
if (bucket.isEmpty()) {
emptyBuckets.add(key);
bucket = null;
} else {
return bucket;
}
}
}
return null; // No bucket found
}
public void removeBuckets(Collection<Integer> emptyBuckets) {
if (emptyBuckets.isEmpty()) {
return;
}
for (Integer i : emptyBuckets) {
buckets.remove(i);
}
keys = new ArrayList<Integer>(buckets.keySet());
Collections.sort(keys);
}
public void finishedAdding() {
finished = true;
keys = new ArrayList<Integer>(buckets.keySet());
Collections.sort(keys);
}
public int getBucketCount() {
return Integer.MAX_VALUE;
}
}
private class PairOrientationComparator implements Comparator<Object> {
private final List<AlignmentTrack.OrientationType> orientationTypes;
//private final Set<String> orientationNames = new HashSet<String>(AlignmentTrack.OrientationType.values().length);
public PairOrientationComparator() {
orientationTypes = Arrays.asList(AlignmentTrack.OrientationType.values());
// for(AlignmentTrack.OrientationType type: orientationTypes){
// orientationNames.add(type.name());
}
@Override
public int compare(Object o0, Object o1) {
String s0 = o0.toString();
String s1 = o1.toString();
if (s0 != null && s1 != null) {
AlignmentTrack.OrientationType t0 = AlignmentTrack.OrientationType.valueOf(s0);
AlignmentTrack.OrientationType t1 = AlignmentTrack.OrientationType.valueOf(s1);
return orientationTypes.indexOf(t0) - orientationTypes.indexOf(t1);
} else if (s0 == null ^ s1 == null) {
//exactly one is null
return s0 == null ? 1 : -1;
} else {
//both null
return 0;
}
}
}
}
|
package org.concord.energy3d.model;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import org.concord.energy3d.gui.MainFrame;
import org.concord.energy3d.scene.Scene;
import org.concord.energy3d.shapes.Annotation;
import org.concord.energy3d.shapes.SizeAnnotation;
import org.concord.energy3d.util.Util;
import com.ardor3d.bounding.BoundingBox;
import com.ardor3d.bounding.CollisionTreeManager;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Vector3;
import com.ardor3d.math.type.ReadOnlyColorRGBA;
import com.ardor3d.math.type.ReadOnlyVector3;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.MaterialState;
import com.ardor3d.renderer.state.MaterialState.ColorMaterial;
import com.ardor3d.scenegraph.Line;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Spatial;
import com.ardor3d.scenegraph.hint.CullHint;
import com.ardor3d.ui.text.BMText;
import com.ardor3d.ui.text.BMText.Align;
import com.ardor3d.util.geom.BufferUtils;
public class Window extends HousePart implements Thermalizable {
private static final long serialVersionUID = 1L;
public static final int NO_MUNTIN_BAR = -1;
public static final int MORE_MUNTIN_BARS = 0;
public static final int MEDIUM_MUNTIN_BARS = 1;
public static final int LESS_MUNTIN_BARS = 2;
public static final ReadOnlyColorRGBA DEFAULT_TINT = new ColorRGBA(0.3f, 0.3f, 0.5f, 0.5f);
private transient Mesh collisionMesh;
private transient BMText label1;
private transient Line bars;
private transient int roofIndex;
private ReadOnlyVector3 normal;
private double solarHeatGainCoefficient = 0.5;
private double uValue = 2.0;
private double volumetricHeatCapacity = 0.5; // unit: kWh/m^3/C (1 kWh = 3.6MJ)
private int style = MORE_MUNTIN_BARS;
private ReadOnlyColorRGBA glassColor = DEFAULT_TINT;
public Window() {
super(2, 4, 30.0);
}
@Override
protected void init() {
label1 = Annotation.makeNewLabel();
super.init();
mesh = new Mesh("Window");
mesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(6));
mesh.getMeshData().setNormalBuffer(BufferUtils.createVector3Buffer(6));
mesh.setModelBound(new BoundingBox());
mesh.getSceneHints().setAllPickingHints(false);
if (glassColor == null)
glassColor = DEFAULT_TINT;
mesh.setDefaultColor(glassColor);
final BlendState blend = new BlendState();
blend.setBlendEnabled(true);
// blend.setTestEnabled(true);
mesh.setRenderState(blend);
mesh.getSceneHints().setRenderBucketType(RenderBucketType.Transparent);
final MaterialState ms = new MaterialState();
ms.setColorMaterial(ColorMaterial.Diffuse);
mesh.setRenderState(ms);
root.attachChild(mesh);
collisionMesh = new Mesh("Window Collision");
collisionMesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(6));
collisionMesh.setVisible(false);
collisionMesh.setUserData(new UserData(this));
collisionMesh.setModelBound(new BoundingBox());
root.attachChild(collisionMesh);
label1.setAlign(Align.SouthWest);
root.attachChild(label1);
bars = new Line("Window (bars)");
bars.setLineWidth(3);
bars.setModelBound(new BoundingBox());
Util.disablePickShadowLight(bars);
bars.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(8));
root.attachChild(bars);
}
@Override
public void setPreviewPoint(final int x, final int y) {
int index = editPointIndex;
if (index == -1) {
if (isFirstPointInserted())
index = 3;
else
index = 0;
}
final PickedHousePart pick = pickContainer(x, y, new Class[] { Wall.class, Roof.class });
Vector3 p = points.get(index);
if (pick != null) {
p.set(pick.getPoint());
snapToGrid(p, getAbsPoint(index), getGridSize(), false);
p = toRelative(p);
if (container instanceof Wall) {
toAbsolute(p);
p = enforceContraints(p);
}
} else
return;
final ArrayList<Vector3> orgPoints = new ArrayList<Vector3>(points.size());
for (final Vector3 v : points)
orgPoints.add(v.clone());
points.get(index).set(p);
if (container instanceof Roof)
computeNormalAndKeepOnRoof();
if (!isFirstPointInserted()) {
points.get(1).set(p);
if (container instanceof Roof)
normal = (ReadOnlyVector3) ((Roof) container).getRoofPartsRoot().getChild(pick.getUserData().getIndex()).getUserData();
} else if (container instanceof Wall) {
if (index == 0 || index == 3) {
points.get(1).set(points.get(0).getX(), 0, points.get(3).getZ());
points.get(2).set(points.get(3).getX(), 0, points.get(0).getZ());
} else {
points.get(0).set(points.get(1).getX(), 0, points.get(2).getZ());
points.get(3).set(points.get(2).getX(), 0, points.get(1).getZ());
}
} else {
final boolean isFlat = Vector3.UNIT_Z.equals(normal);
final ReadOnlyVector3 u = isFlat ? Vector3.UNIT_X : Vector3.UNIT_Z.cross(normal, null);
final ReadOnlyVector3 v = isFlat ? Vector3.UNIT_Y : normal.cross(u, null);
if (index == 0 || index == 3) {
final Vector3 p0 = getAbsPoint(0);
final Vector3 p3 = getAbsPoint(3);
points.get(1).set(toRelative(Util.closestPoint(p0, v, p3, u)));
points.get(2).set(toRelative(Util.closestPoint(p0, u, p3, v)));
} else {
final Vector3 p1 = getAbsPoint(1);
final Vector3 p2 = getAbsPoint(2);
points.get(0).set(toRelative(Util.closestPoint(p1, v, p2, u)));
points.get(3).set(toRelative(Util.closestPoint(p1, u, p2, v)));
}
}
if (isFirstPointInserted())
if (container instanceof Wall && !((Wall) container).fits(this)) {
for (int i = 0; i < points.size(); i++)
points.get(i).set(orgPoints.get(i));
return;
}
if (container != null) {
draw();
setEditPointsVisible(true);
container.draw();
}
}
@Override
protected void drawMesh() {
if (points.size() < 4)
return;
mesh.setVisible(container instanceof Roof);
normal = computeNormalAndKeepOnRoof();
updateEditShapes();
final boolean drawBars = style != NO_MUNTIN_BAR && !isFrozen() && !Util.isEqual(getAbsPoint(2), getAbsPoint(0)) && !Util.isEqual(getAbsPoint(1), getAbsPoint(0));
final ReadOnlyVector3 meshOffset, barsOffset;
if (container instanceof Roof) {
if (drawBars) {
meshOffset = normal.multiply(-0.1, null);
barsOffset = new Vector3();
} else {
meshOffset = new Vector3();
barsOffset = null;
}
} else {
meshOffset = normal.multiply(-0.6, null);
if (drawBars)
barsOffset = normal.multiply(-0.5, null);
else
barsOffset = null;
}
fillRectangleBuffer(mesh.getMeshData().getVertexBuffer(), meshOffset);
final FloatBuffer normalBuffer = mesh.getMeshData().getNormalBuffer();
for (int i = 0; i < 6; i += 1)
BufferUtils.setInBuffer(normal.negate(null), normalBuffer, i);
fillRectangleBuffer(collisionMesh.getMeshData().getVertexBuffer(), normal.multiply(0.1, null));
mesh.updateModelBound();
collisionMesh.updateModelBound();
CollisionTreeManager.INSTANCE.updateCollisionTree(mesh);
CollisionTreeManager.INSTANCE.updateCollisionTree(collisionMesh);
if (!drawBars)
bars.getSceneHints().setCullHint(CullHint.Always);
else {
bars.getSceneHints().setCullHint(CullHint.Inherit);
final double divisionLength = 3.0 + style * 3.0;
FloatBuffer barsVertices = bars.getMeshData().getVertexBuffer();
final int cols = (int) Math.max(2, getAbsPoint(0).distance(getAbsPoint(2)) / divisionLength);
final int rows = (int) Math.max(2, getAbsPoint(0).distance(getAbsPoint(1)) / divisionLength);
if (barsVertices.capacity() < (4 + rows + cols) * 6) {
barsVertices = BufferUtils.createVector3Buffer((4 + rows + cols) * 2);
bars.getMeshData().setVertexBuffer(barsVertices);
} else {
barsVertices.rewind();
barsVertices.limit(barsVertices.capacity());
}
int i = 0;
BufferUtils.setInBuffer(getAbsPoint(0).addLocal(barsOffset), barsVertices, i++);
BufferUtils.setInBuffer(getAbsPoint(1).addLocal(barsOffset), barsVertices, i++);
BufferUtils.setInBuffer(getAbsPoint(1).addLocal(barsOffset), barsVertices, i++);
BufferUtils.setInBuffer(getAbsPoint(3).addLocal(barsOffset), barsVertices, i++);
BufferUtils.setInBuffer(getAbsPoint(3).addLocal(barsOffset), barsVertices, i++);
BufferUtils.setInBuffer(getAbsPoint(2).addLocal(barsOffset), barsVertices, i++);
BufferUtils.setInBuffer(getAbsPoint(2).addLocal(barsOffset), barsVertices, i++);
BufferUtils.setInBuffer(getAbsPoint(0).addLocal(barsOffset), barsVertices, i++);
final ReadOnlyVector3 o = getAbsPoint(0).add(barsOffset, null);
final ReadOnlyVector3 u = getAbsPoint(2).subtract(getAbsPoint(0), null);
final ReadOnlyVector3 v = getAbsPoint(1).subtract(getAbsPoint(0), null);
final Vector3 p = new Vector3();
for (int col = 1; col < cols; col++) {
u.multiply((double) col / cols, p).addLocal(o);
BufferUtils.setInBuffer(p, barsVertices, i++);
p.addLocal(v);
BufferUtils.setInBuffer(p, barsVertices, i++);
}
for (int row = 1; row < rows; row++) {
v.multiply((double) row / rows, p).addLocal(o);
BufferUtils.setInBuffer(p, barsVertices, i++);
p.addLocal(u);
BufferUtils.setInBuffer(p, barsVertices, i++);
}
barsVertices.limit(i * 3);
bars.getMeshData().updateVertexCount();
bars.updateModelBound();
}
}
private void fillRectangleBuffer(final FloatBuffer vertexBuffer, final ReadOnlyVector3 meshOffset) {
BufferUtils.setInBuffer(getAbsPoint(0).addLocal(meshOffset), vertexBuffer, 0);
BufferUtils.setInBuffer(getAbsPoint(2).addLocal(meshOffset), vertexBuffer, 1);
BufferUtils.setInBuffer(getAbsPoint(1).addLocal(meshOffset), vertexBuffer, 2);
BufferUtils.setInBuffer(getAbsPoint(1).addLocal(meshOffset), vertexBuffer, 3);
BufferUtils.setInBuffer(getAbsPoint(2).addLocal(meshOffset), vertexBuffer, 4);
BufferUtils.setInBuffer(getAbsPoint(3).addLocal(meshOffset), vertexBuffer, 5);
}
@Override
public void drawAnnotations() {
if (points.size() < 4)
return;
int annotCounter = 0;
Vector3 p0 = getAbsPoint(0);
Vector3 p1 = getAbsPoint(1);
Vector3 p2 = getAbsPoint(2);
Vector3 p3 = getAbsPoint(3);
final int vIndex = getNormal().equals(Vector3.UNIT_Z) ? 1 : 2;
if (!Util.isEqual(p0.getValue(vIndex), p2.getValue(vIndex))) {
final Vector3 tmp = p0;
p0 = p2;
p2 = p3;
p3 = p1;
p1 = tmp;
}
if (p0.getValue(vIndex) > p1.getValue(vIndex)) {
swap(p0, p1);
swap(p2, p3);
}
final Vector3 p01 = p1.subtract(p0, null).normalizeLocal();
if (p2.subtract(p0, null).normalizeLocal().dot(p01.cross(getNormal(), null)) < 0) {
swap(p0, p2);
swap(p1, p3);
}
final Vector3 cornerXY = p0.subtract(container.getAbsPoint(0), null);
cornerXY.setZ(0);
final ReadOnlyVector3 faceDirection = getNormal();
if (container instanceof Wall) {
final ReadOnlyVector3 v02 = container.getAbsPoint(2).subtract(container.getAbsPoint(0), null);
final boolean reversedFace = v02.normalize(null).crossLocal(container.getNormal()).dot(Vector3.NEG_UNIT_Z) < 0.0;
double xy = cornerXY.length();
if (reversedFace)
xy = v02.length() - xy;
label1.setText("(" + Math.round(Scene.getInstance().getAnnotationScale() * 10 * xy) / 10.0 + ", " + Math.round(Scene.getInstance().getAnnotationScale() * 10.0 * (p0.getZ() - container.getAbsPoint(0).getZ())) / 10.0 + ")");
label1.setTranslation(p0);
label1.setRotation(new Matrix3().fromAngles(0, 0, -Util.angleBetween(v02.normalize(null).multiplyLocal(reversedFace ? -1 : 1), Vector3.UNIT_X, Vector3.UNIT_Z)));
}
final ReadOnlyVector3 center = getCenter();
final float lineWidth = original == null ? 1f : 2f;
SizeAnnotation annot = fetchSizeAnnot(annotCounter++);
annot.setRange(p0, p1, center, faceDirection, false, Align.Center, true, true, false);
annot.setLineWidth(lineWidth);
annot = fetchSizeAnnot(annotCounter++);
annot.setRange(p0, p2, center, faceDirection, false, Align.Center, true, false, false);
annot.setLineWidth(lineWidth);
}
private void swap(final Vector3 v1, final Vector3 v2) {
final Vector3 tmp = Vector3.fetchTempInstance();
tmp.set(v1);
v1.set(v2);
v2.set(tmp);
Vector3.releaseTempInstance(tmp);
}
@Override
public ReadOnlyVector3 getCenter() {
// return bars.getModelBound().getCenter();
return mesh.getModelBound().getCenter();
}
@Override
public boolean isPrintable() {
return false;
}
@Override
public void setAnnotationsVisible(final boolean visible) {
super.setAnnotationsVisible(visible);
if (label1 != null)
label1.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
}
private Vector3 enforceContraints(final ReadOnlyVector3 p) {
if (container == null)
return new Vector3(p);
double wallx = container.getAbsPoint(2).subtract(container.getAbsPoint(0), null).length();
if (Util.isZero(wallx))
wallx = MathUtils.ZERO_TOLERANCE;
final double margin = 0.2 / wallx;
double x = Math.max(p.getX(), margin);
x = Math.min(x, 1 - margin);
return new Vector3(x, p.getY(), p.getZ());
}
@Override
public void updateTextureAndColor() {
}
public void hideBars() {
if (bars != null)
bars.getSceneHints().setCullHint(CullHint.Always);
}
@Override
public Vector3 getAbsPoint(final int index) {
return container != null ? container.getRoot().getTransform().applyForward(super.getAbsPoint(index)) : super.getAbsPoint(index);
}
@Override
public double getGridSize() {
return 1.0;
}
@Override
protected String getTextureFileName() {
return null;
}
@Override
public ReadOnlyVector3 getNormal() {
return normal;
}
public void move(final Vector3 d, final ArrayList<Vector3> houseMoveStartPoints) {
final List<Vector3> orgPoints = new ArrayList<Vector3>(points.size());
for (int i = 0; i < points.size(); i++)
orgPoints.add(points.get(i));
final ReadOnlyVector3 d_rel = toRelative(getAbsPoint(0).subtract(d, null)).subtractLocal(points.get(0)).negateLocal();
for (int i = 0; i < points.size(); i++) {
final Vector3 newP = houseMoveStartPoints.get(i).add(d_rel, null);
points.set(i, newP);
}
if (container instanceof Wall && !((Wall) container).fits(this))
for (int i = 0; i < points.size(); i++)
points.set(i, orgPoints.get(i));
draw();
container.draw();
}
public void setStyle(final int style) {
this.style = style;
}
public int getStyle() {
return style;
}
public void setSolarHeatGainCoefficient(final double shgc) {
solarHeatGainCoefficient = shgc;
}
public double getSolarHeatGainCoefficient() {
return solarHeatGainCoefficient;
}
@Override
protected void computeArea() {
if (isDrawCompleted()) {
final Vector3 p0 = getAbsPoint(0);
final Vector3 p1 = getAbsPoint(1);
final Vector3 p2 = getAbsPoint(2);
final double C = 100.0;
final double annotationScale = Scene.getInstance().getAnnotationScale();
area = Math.round(Math.round(p2.subtract(p0, null).length() * annotationScale * C) / C * Math.round(p1.subtract(p0, null).length() * annotationScale * C) / C * C) / C;
} else
area = 0.0;
}
public void moveTo(final HousePart target) {
final double w1 = target.getAbsPoint(0).distance(target.getAbsPoint(2));
final double h1 = target.getAbsPoint(0).distance(target.getAbsPoint(1));
final double w2 = container.getAbsPoint(0).distance(container.getAbsPoint(2));
final double h2 = container.getAbsPoint(0).distance(container.getAbsPoint(1));
final double ratioW = w2 / w1;
final double ratioH = h2 / h1;
final Vector3 v0 = points.get(0);
final Vector3 v1 = points.get(1);
v1.setX(v0.getX() + (v1.getX() - v0.getX()) * ratioW);
v1.setY(v0.getY() + (v1.getY() - v0.getY()) * ratioW);
v1.setZ(v0.getZ() + (v1.getZ() - v0.getZ()) * ratioH);
final Vector3 v2 = points.get(2);
v2.setX(v0.getX() + (v2.getX() - v0.getX()) * ratioW);
v2.setY(v0.getY() + (v2.getY() - v0.getY()) * ratioW);
v2.setZ(v0.getZ() + (v2.getZ() - v0.getZ()) * ratioH);
final Vector3 v3 = points.get(3);
v3.setX(v0.getX() + (v3.getX() - v0.getX()) * ratioW);
v3.setY(v0.getY() + (v3.getY() - v0.getY()) * ratioW);
v3.setZ(v0.getZ() + (v3.getZ() - v0.getZ()) * ratioH);
setContainer(target);
}
@Override
public boolean isCopyable() {
return true;
}
/** tolerance is a fraction relative to the width of a window */
private boolean overlap(double tolerance) {
tolerance *= getAbsPoint(0).distance(getAbsPoint(2));
final Vector3 center = getAbsCenter();
for (final HousePart p : Scene.getInstance().getParts()) {
if (p instanceof Window && p != this && p.getContainer() == container) {
if (p.getAbsCenter().distance(center) < tolerance)
return true;
}
}
return false;
}
@Override
public HousePart copy(final boolean check) {
final Window c = (Window) super.copy(false);
if (check) {
if (container instanceof Wall) {
final double s = Math.signum(toRelative(container.getAbsCenter()).subtractLocal(toRelative(Scene.getInstance().getOriginalCopy().getAbsCenter())).dot(Vector3.UNIT_X));
final double shift = s * (points.get(0).distance(points.get(2)) + 0.01); // give it a small gap
final int n = c.getPoints().size();
for (int i = 0; i < n; i++) {
final double newX = points.get(i).getX() + shift;
if (newX > 1 - shift / 2 || newX < shift / 2) // reject it if out of range
return null;
}
for (int i = 0; i < n; i++) {
c.points.get(i).setX(points.get(i).getX() + shift);
}
if (c.overlap(0.1)) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "Sorry, your new window is too close to an existing one.", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
} else if (container instanceof Roof) {
if (normal == null) {
// don't remove this error message just in case this happens again
JOptionPane.showMessageDialog(MainFrame.getInstance(), "Normal of window [" + c + "] is null. Please try again.", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
final Vector3 d = normal.cross(Vector3.UNIT_Z, null);
d.normalizeLocal();
if (Util.isZero(d.length()))
d.set(1, 0, 0);
final Vector3 d0 = d.clone();
final double shift = getAbsPoint(0).distance(getAbsPoint(2)) + 0.01; // give it a small gap
d.multiplyLocal(shift);
d.addLocal(getContainerRelative().getPoints().get(0));
final Vector3 v = toRelative(d);
final Vector3 originalCenter = Scene.getInstance().getOriginalCopy().getAbsCenter();
final double s = Math.signum(container.getAbsCenter().subtractLocal(originalCenter).dot(d0));
final int n = c.getPoints().size();
for (int i = 0; i < n; i++) {
c.points.get(i).setX(points.get(i).getX() + s * v.getX());
c.points.get(i).setY(points.get(i).getY() + s * v.getY());
c.points.get(i).setZ(points.get(i).getZ() + s * v.getZ());
}
final Roof roof = (Roof) c.container;
boolean outsideWalls = false;
for (int i = 0; i < n; i++) {
if (!roof.insideWallsPolygon(c.getAbsPoint(i))) {
outsideWalls = true;
break;
}
}
if (outsideWalls) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "Sorry, you are not allowed to paste a window outside a roof.", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
if (c.overlap(0.1)) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "Sorry, your new window is too close to an existing one.", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
}
}
return c;
}
@Override
public void setColor(final ReadOnlyColorRGBA color) {
glassColor = color;
if (mesh != null)
mesh.setDefaultColor(glassColor);
}
@Override
public ReadOnlyColorRGBA getColor() {
return glassColor;
}
@Override
public void setUValue(final double uValue) {
this.uValue = uValue;
}
@Override
public double getUValue() {
return uValue;
}
@Override
public void setVolumetricHeatCapacity(final double volumetricHeatCapacity) {
this.volumetricHeatCapacity = volumetricHeatCapacity;
}
@Override
public double getVolumetricHeatCapacity() {
return volumetricHeatCapacity;
}
@Override
protected HousePart getContainerRelative() {
return container instanceof Roof ? container.getContainerRelative() : container;
}
public void setRoofIndex(final int index) {
this.roofIndex = index;
}
public int getRoofIndex() {
return roofIndex;
}
@Override
public Spatial getCollisionSpatial() {
return collisionMesh;
}
@Override
public Mesh getRadiationMesh() {
return collisionMesh;
}
@Override
public Spatial getRadiationCollisionSpatial() {
return getRadiationMesh();
}
}
|
package org.jhove2.module.format.tiff;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.jhove2.annotation.ReportableProperty;
import org.jhove2.config.ConfigInfo;
import org.jhove2.core.JHOVE2;
import org.jhove2.core.JHOVE2Exception;
import org.jhove2.core.Message;
import org.jhove2.core.Message.Context;
import org.jhove2.core.Message.Severity;
import org.jhove2.core.io.Input;
import org.jhove2.core.reportable.AbstractReportable;
import org.jhove2.module.format.Validator.Validity;
/**
* @author mstrong
*
*/
public abstract class IFD
extends AbstractReportable {
/** IFD Entries in the IFD */
protected List<IFDEntry> entries = new ArrayList<IFDEntry>();
/** True if this is the first IFD. */
private boolean first;
/** the input source of the TIFF */
protected Input input;
/** validity of IFD */
protected Validity isValid;
/** offset to the next IFD */
protected long nextIFD;
/** number of IFD Entries in the IFD */
protected int numEntries;
/** offset of the IFD */
protected long offset;
/** value of the previous tag */
private static int prevTag = 0;
/** True if this is the "thumbnail" IFD. */
private boolean thumbnail;
/** TIFF version determined by data in IFDEntry */
private int version;
/** Tag sort order error message */
private Message TagSortOrderErrorMessage;
/** Message for Zero IFD Entries */
private Message zeroIFDEntriesMessage;
/** Byte offset not word aligned message */
private Message ByteOffsetNotWordAlignedMessage;
private Message ValueOffsetReferenceLocationFileMessage;
private Message UnknownTypeMessage;
protected static Properties tiffTagProps;
protected static Properties tiffTypeProps;
/**
* Instantiate an IFD Class with the Input source
* @param input
*/
public IFD(Input input) {
super();
this.input = input;
}
@ReportableProperty(order = 3, value="IFD entries.")
public List<IFDEntry> getIFDEntries() {
return entries;
}
@ReportableProperty(order = 4, value = "Offset of next IFD.")
public long getNextIFD() {
return nextIFD;
}
@ReportableProperty (order = 2, value = "Number of IFD entries.")
public int getNumEntries() {
return numEntries;
}
@ReportableProperty(order = 1, value = "Byte offset of IFD.")
public long getOffset() {
return offset;
}
/**
* Parse a source unit input. Implicitly set the start and end elapsed time.
*
* @param input
* JHOVE2 framework
* @param input
* Input
* @return Number of bytes consumed
* @throws EOFException
* If End-of-File is reached reading the source unit
* @throws IOException
* If an I/O exception is raised reading the source unit
* @throws JHOVE2Exception
*/
public void parse(JHOVE2 jhove2, Input input, long offset) throws EOFException,
IOException, JHOVE2Exception {
this.isValid = Validity.Undetermined;
/* Read the first byte. */
input.setPosition(offset);
numEntries = input.readUnsignedShort();
if (numEntries < 1){
this.isValid = Validity.False;
Object[]messageArgs = new Object[]{0, input.getPosition(), numEntries};
this.zeroIFDEntriesMessage = new Message(Severity.ERROR,
Context.OBJECT,
"org.jhove2.module.format.tiff.IFD.zeroIFDEntriesMessage",
messageArgs, jhove2.getConfigInfo());
}
/* parse through the list of IFDs */
for (int i=0; i<numEntries; i++) {
int tag = input.readUnsignedShort();
if (tag > prevTag)
prevTag = tag;
else {
Object[]messageArgs = new Object[]{tag, input.getPosition()};
this.TagSortOrderErrorMessage = (new Message(Severity.ERROR,
Context.OBJECT,
"org.jhove2.module.format.tiff.IFDEntry.TagSortOrderErrorMessage",
messageArgs, jhove2.getConfigInfo()));
}
int type = input.readUnsignedShort();
/* Skip over tags with unknown type; those outside of defined range. */
if (type < TiffType.types.first().getNum() || type > TiffType.types.last().getNum()) {
Object[]messageArgs = new Object[]{type, offset };
this.UnknownTypeMessage = (new Message(Severity.ERROR,
Context.OBJECT,
"org.jhove2.module.format.tiff.IFDEntry.UnknownTypeMessage",
messageArgs, jhove2.getConfigInfo()));
}
else {
int count = (int) input.readUnsignedInt();
/* keep track of the value offset in the file */
long valueOffset = input.getPosition();
long value = input.readUnsignedInt();
if (calcValueSize(type, count) > 4) {
/* the value is the offset to the value */
long size = input.getSize();
/* test that the value offset is within the file */
if (value > size) {
Object[]messageArgs = new Object[]{tag, value, size};
this.ValueOffsetReferenceLocationFileMessage = (new Message(Severity.ERROR,
Context.OBJECT,
"org.jhove2.module.format.tiff.IFDEntry.ValueOffsetReferenceLocationFileMessage",
messageArgs, jhove2.getConfigInfo()));
}
/* test off set is word aligned */
if ((value & 1) != 0){
Object[]messageArgs = new Object[]{0, input.getPosition(), valueOffset};
this.ByteOffsetNotWordAlignedMessage = (new Message(Severity.ERROR,
Context.OBJECT,
"org.jhove2.module.format.tiff.IFDEntry.ValueByteOffsetNotWordAlignedMessage",
messageArgs, jhove2.getConfigInfo()));
}
}
else {
/* the value is the actual value */
value = valueOffset;
}
IFDEntry ifdEntry = new IFDEntry(tag, type, count, value);
ifdEntry.validateEntry(jhove2);
getValues(jhove2, ifdEntry);
version = ifdEntry.getVersion();
entries.add(ifdEntry);
}
}
}
public void parse(long offset) {
this.isValid = Validity.Undetermined;
}
/** get the value(s) for an IFD entry
* @throws IOException */
public abstract void getValues (JHOVE2 jhove2, IFDEntry entry) throws JHOVE2Exception, IOException;
/**
* Get the tag sort order error message
*
* @return the tagSortOrderErrorMessage
*/
@ReportableProperty(order=8, value = "tag sort order error message.")
public Message getTagSortOrderErrorMessage() {
return TagSortOrderErrorMessage;
}
/**
* Get byte offset not word aligned message
*
* @return the byteOffsetNotWordAlignedMessage
*/
@ReportableProperty(order=6, value = "Byte offset not word aligned message.")
public Message getByteOffsetNotWordAlignedMessage() {
return ByteOffsetNotWordAlignedMessage;
}
/**
* Get the value offset reference location file message
*
* @return the valueOffsetReferenceLocationFileMessage
*/
@ReportableProperty(order=9, value = "value offset reference location file message.")
public Message getValueOffsetReferenceLocationFileMessage() {
return ValueOffsetReferenceLocationFileMessage;
}
/**
* Get the unknown type message
*
* @return the unknownTypeMessage
*/
@ReportableProperty(order=10, value = "unknown type message.")
public Message getUnknownTypeMessage() {
return UnknownTypeMessage;
}
public int getVersion() {
// TODO Auto-generated method stub
return this.version;
}
public void setFirst(boolean first) {
this.first = first;
}
public boolean isFirst() {
return first;
}
public void setThumbnail(boolean thumbnail) {
this.thumbnail = thumbnail;
}
public boolean isThumbnail() {
return thumbnail;
}
public void setOffset(long offset) {
this.offset = offset;
}
/**
* Calculate how many bytes a given number of fields of a given
* type will require.
* @param type Field type
* @param count Field count
*/
public static long calcValueSize (int type, long count)
{
int fieldSize = 0;
fieldSize = TiffType.getType(type).getSize();
return count*fieldSize;
}
/**
* @return Properties the Tiff Tag Properties stored in the Java Properties file
*/
public static Properties getTiffTags(ConfigInfo config) throws JHOVE2Exception {
if (tiffTagProps==null){
tiffTagProps = config.getProperties("TiffTag");
}
return tiffTagProps;
}
/**
* @return Properties the Tiff Type Properties stored in the Java Properties file
*/
public static Properties getTiffType(ConfigInfo config) throws JHOVE2Exception {
if (tiffTypeProps==null){
tiffTypeProps = config.getProperties("TiffType");
}
return tiffTypeProps;
}
}
|
package org.lightmare.cache;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.persistence.EntityManagerFactory;
import org.apache.log4j.Logger;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.MetaCreator;
import org.lightmare.ejb.exceptions.BeanInUseException;
import org.lightmare.ejb.exceptions.BeanNotDeployedException;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.WatchUtils;
/**
* Container class to save {@link MetaData} for bean interface {@link Class},
* connections ({@link EntityManagerFactory}) for unit names and
* {@link Configuration}s for distinct deployments
*
* @author Levan Tsinadze
* @since 0.0.45-SNAPSHOT
*/
public class MetaContainer {
// Cached instance of MetaCreator
private static MetaCreator creator;
// Configurations cache for server
public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>();
// Cached bean meta data
private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>();
// Cached bean class name by its URL for undeploy processing
private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>();
private static final Logger LOG = Logger.getLogger(MetaContainer.class);
/**
* Gets cached {@link MetaCreator} object
*
* @return {@link MetaCreator}
*/
public static MetaCreator getCreator() {
return creator;
}
/**
* Caches {@link MetaCreator} object
*
* @param metaCreator
*/
public static void setCreator(MetaCreator metaCreator) {
synchronized (MetaContainer.class) {
creator = metaCreator;
}
}
/**
* Caches {@link Configuration} for specific {@link URL} array
*
* @param archives
* @param config
*/
public static void putConfig(URL[] archives, Configuration config) {
if (CollectionUtils.valid(archives)) {
boolean containsPath;
for (URL archive : archives) {
String path = WatchUtils.clearPath(archive.getFile());
containsPath = CONFIGS.containsKey(path);
if (ObjectUtils.notTrue(containsPath)) {
CONFIGS.put(path, config);
}
}
}
}
/**
* Gets {@link Configuration} from cache for specific {@link URL} array
*
* @param archives
* @param config
*/
public static Configuration getConfig(URL[] archives) {
Configuration config;
URL archive = CollectionUtils.getFirst(archives);
if (ObjectUtils.notNull(archive)) {
String path = WatchUtils.clearPath(archive.getFile());
config = CONFIGS.get(path);
} else {
config = null;
}
return config;
}
/**
* Adds {@link MetaData} to cache on specified bean name if absent and
* returns previous value on this name or null if such value does not exists
*
* @param beanName
* @param metaData
* @return
*/
public static MetaData addMetaData(String beanName, MetaData metaData) {
return EJBS.putIfAbsent(beanName, metaData);
}
/**
* Check if {@link MetaData} is ceched for specified bean name if true
* throws {@link BeanInUseException}
*
* @param beanName
* @param metaData
* @throws BeanInUseException
*/
public static void checkAndAddMetaData(String beanName, MetaData metaData)
throws BeanInUseException {
MetaData tmpMeta = addMetaData(beanName, metaData);
if (ObjectUtils.notNull(tmpMeta)) {
throw BeanInUseException.get(beanName);
}
}
/**
* Checks if bean with associated name deployed and if it is, then checks if
* deployment is in progress
*
* @param beanName
* @return boolean
*/
public static boolean checkMetaData(String beanName) {
boolean check;
MetaData metaData = EJBS.get(beanName);
check = metaData == null;
if (ObjectUtils.notTrue(check)) {
check = metaData.isInProgress();
}
return check;
}
/**
* Checks if bean with associated name is already deployed
*
* @param beanName
* @return boolean
*/
public boolean checkBean(String beanName) {
return EJBS.containsKey(beanName);
}
/**
* Waits while passed {@link MetaData} instance is in progress
*
* @param inProgress
* @param metaData
* @throws IOException
*/
private static void awaitProgress(boolean inProgress, MetaData metaData)
throws IOException {
while (inProgress) {
try {
metaData.wait();
inProgress = metaData.isInProgress();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
/**
* Waits while {@link MetaData#isInProgress()} is true (and if it is calls
* {@link MetaContainer#awaitProgress(boolean, MetaData)} method)
*
* @param metaData
* @throws IOException
*/
public static void awaitMetaData(MetaData metaData) throws IOException {
boolean inProgress = metaData.isInProgress();
if (inProgress) {
synchronized (metaData) {
awaitProgress(inProgress, metaData);
}
}
}
/**
* Gets deployed bean {@link MetaData} by name without checking deployment
* progress
*
* @param beanName
* @return {@link MetaData}
*/
public static MetaData getMetaData(String beanName) {
return EJBS.get(beanName);
}
/**
* Check if {@link MetaData} with associated name deployed and if it is
* waits while {@link MetaData#isInProgress()} true before return it
*
* @param beanName
* @return {@link MetaData}
* @throws IOException
*/
public static MetaData getSyncMetaData(String beanName) throws IOException {
MetaData metaData = getMetaData(beanName);
if (metaData == null) {
throw BeanNotDeployedException.get(beanName);
}
awaitMetaData(metaData);
return metaData;
}
/**
* Gets bean name by containing archive {@link URL} address
*
* @param url
* @return {@link Collection}<code><String></code>
*/
public static Collection<String> getBeanNames(URL url) {
Collection<String> urls;
synchronized (MetaContainer.class) {
urls = EJB_URLS.get(url);
}
return urls;
}
/**
* Checks containing archive {@link URL} address
*
* @param url
* @return <code>boolean</code>
*/
public static boolean chackDeployment(URL url) {
boolean containsKey;
synchronized (MetaContainer.class) {
containsKey = EJB_URLS.containsKey(url);
}
return containsKey;
}
/**
* Removes cached EJB bean names {@link Collection} by containing file
* {@link URL} as key
*
* @param url
*/
public static void removeBeanNames(URL url) {
synchronized (MetaContainer.class) {
EJB_URLS.remove(url);
}
}
/**
* Caches EJB bean name by {@link URL} of jar ear or any file
*
* @param beanName
*/
public static void addBeanName(URL url, String beanName) {
synchronized (MetaContainer.class) {
Collection<String> beanNames = EJB_URLS.get(url);
if (CollectionUtils.invalid(beanNames)) {
beanNames = new HashSet<String>();
EJB_URLS.put(url, beanNames);
}
beanNames.add(beanName);
}
}
/**
* Lists {@link Set} for deployed application {@link URL}'s
*
* @return {@link Set}<URL>
*/
public static Set<URL> listApplications() {
Set<URL> apps = EJB_URLS.keySet();
return apps;
}
/**
* Clears connection from cache for passed {@link MetaData} instance
*
* @param metaData
* @throws IOException
*/
private static void clearConnection(MetaData metaData) throws IOException {
Collection<ConnectionData> connections = metaData.getConnections();
if (CollectionUtils.valid(connections)) {
for (ConnectionData connection : connections) {
// Gets connection to clear
String unitName = connection.getUnitName();
ConnectionSemaphore semaphore = connection.getConnection();
if (semaphore == null) {
semaphore = ConnectionContainer.getConnection(unitName);
}
if (ObjectUtils.notNull(semaphore)
&& semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) {
ConnectionContainer.removeConnection(unitName);
}
}
}
}
/**
* Removes EJB bean (removes it's {@link MetaData} from cache) by bean class
* name
*
* @param beanName
* @throws IOException
*/
public static void undeployBean(String beanName) throws IOException {
MetaData metaData;
try {
metaData = getSyncMetaData(beanName);
} catch (IOException ex) {
LogUtils.error(LOG, ex, "Could not get bean resources %s cause %s",
beanName, ex.getMessage());
metaData = null;
}
// Removes MetaData from cache
removeMeta(beanName);
if (ObjectUtils.notNull(metaData)) {
// Removes appropriated resource class from REST service
if (RestContainer.hasRest()) {
RestProvider.remove(metaData.getBeanClass());
}
clearConnection(metaData);
ClassLoader loader = metaData.getLoader();
LibraryLoader.closeClassLoader(loader);
metaData = null;
}
}
/**
* Removes EJB bean (removes it's {@link MetaData} from cache) by
* {@link URL} of archive file
*
* @param url
* @throws IOException
*/
public static boolean undeploy(URL url) throws IOException {
boolean valid;
synchronized (MetaContainer.class) {
Collection<String> beanNames = getBeanNames(url);
valid = CollectionUtils.valid(beanNames);
if (valid) {
for (String beanName : beanNames) {
undeployBean(beanName);
}
}
removeBeanNames(url);
}
return valid;
}
/**
* Removes EJB bean (removes it's {@link MetaData} from cache) by
* {@link File} of archive file
*
* @param file
* @throws IOException
*/
public static boolean undeploy(File file) throws IOException {
boolean valid;
URL url = file.toURI().toURL();
valid = undeploy(url);
return valid;
}
/**
* Removes EJB bean (removes it's {@link MetaData} from cache) by
* {@link File} path of archive file
*
* @param path
* @throws IOException
*/
public static boolean undeploy(String path) throws IOException {
boolean valid;
File file = new File(path);
valid = undeploy(file);
return valid;
}
/**
* Removed {@link MetaData} from cache by EJB bean name
*
* @param beanName
*/
public static void removeMeta(String beanName) {
EJBS.remove(beanName);
}
/**
* Gets {@link java.util.Iterator}<MetaData> over all cached
* {@link org.lightmare.cache.MetaData} objects
*
* @return {@link java.util.Iterator}<MetaData>
*/
public static Iterator<MetaData> getBeanClasses() {
return EJBS.values().iterator();
}
/**
* Clears {@link MetaCreator} instance
*/
private static void clearMetaCreator() {
if (ObjectUtils.notNull(creator)) {
creator.clear();
creator = null;
}
}
/**
* Removes all cached resources
*/
public static void clear() {
if (ObjectUtils.notNull(creator)) {
synchronized (MetaContainer.class) {
clearMetaCreator();
}
}
CONFIGS.clear();
EJBS.clear();
EJB_URLS.clear();
}
}
|
package org.made.neohabitat.mods;
import org.elkoserver.foundation.json.JSONMethod;
import org.elkoserver.foundation.json.OptInteger;
import org.elkoserver.json.EncodeControl;
import org.elkoserver.json.JSONLiteral;
import org.elkoserver.server.context.User;
import org.made.neohabitat.HabitatMod;
/**
* Habitat Die Mod
*
* The fake gun works like the real gun, except when you shoot
* with it a flag that says "BANG!" comes out instead of actually
* shooting somebody.
*
* @author TheCarlSaganExpress
*/
public class Fake_gun extends HabitatMod
{
public int HabitatClass() {
return CLASS_FAKE_GUN;
}
public String HabitatModName() {
return "Fake_gun";
}
public int capacity() {
return 0;
}
public int pc_state_bytes() {
return 1;
};
public boolean known() {
return true;
}
public boolean opaque_container() {
return false;
}
public boolean filler() {
return false;
}
public int state = 0; //See struct_fake_gun.incl.pl1
public static final int FAKE_GUN_READY = 0; //Same as %replace FAKE_GUN_READY by 0;
public static final int FAKE_GUN_FIRED = 1; //Same as %replace FAKE_GUN_FIRED by 1;
public boolean success = false;
@JSONMethod({ "style", "x", "y", "orientation", "gr_state", "state" })
public Fake_gun(OptInteger style, OptInteger x, OptInteger y, OptInteger orientation, OptInteger gr_state, int state) {
super(style, x, y, orientation, gr_state);
this.state = state;
}
@Override
public JSONLiteral encode(EncodeControl control) {
JSONLiteral result = super.encodeCommon(new JSONLiteral(HabitatModName(), control));
result.addParameter("state", state);
result.finish();
return result;
}
@JSONMethod
public void HELP(User from) {
generic_HELP(from);
}
@JSONMethod
public void GET(User from) {
generic_GET(from);
}
@JSONMethod({ "containerNoid", "x", "y", "orientation" })
public void PUT(User from, OptInteger containerNoid, OptInteger x, OptInteger y, OptInteger orientation) {
generic_PUT(from, containerNoid.value(THE_REGION), avatar(from).x, avatar(from).y, avatar(from).orientation);
}
@JSONMethod({ "target", "x", "y" })
public void THROW(User from, int target, int x, int y) {
generic_THROW(from, target, x, y);
}
@JSONMethod
public void FAKESHOOT(User from) {
Avatar curAvatar = avatar(from);
if (holding(curAvatar, this) && (state == FAKE_GUN_READY)){
state = FAKE_GUN_FIRED;
gr_state = FAKE_GUN_FIRED;
gen_flags[MODIFIED] = true;
send_neighbor_msg(from, noid, "FAKESHOOT$", "state", state); //n_msg_0(selfptr, FAKESHOOT$);
success = true;
}
else
success = false;
send_reply_msg(from, noid, "FAKESHOOT_SUCCESS", (success) ? TRUE : FALSE); //r_msg_1(success);
}
@JSONMethod
public void RESET(User from) {
Avatar curAvatar = avatar(from);
if (holding(curAvatar, this) && (state == FAKE_GUN_FIRED)){
state = FAKE_GUN_READY;
gr_state = FAKE_GUN_READY;
gen_flags[MODIFIED] = true;
send_neighbor_msg(from, noid, "RESET$", "state", state); //n_msg_0(selfptr, RESET$);
success = true;
}
else
success = false;
send_reply_msg(from, noid, "RESET_SUCCESS", (success) ? TRUE : FALSE); //call r_msg_1(success);
}
}
|
package org.mastercoin.rpc;
import com.google.bitcoin.core.Address;
import java.math.BigDecimal;
/**
* Balance data for a specific Mastercoin CurrencyID in a single Bitcoin address
*
* A Java representation of the JSON entry returned by getallbalancesforid_MP
*/
public class MPBalanceEntry {
private Address address;
private BigDecimal balance;
private BigDecimal reserved;
public MPBalanceEntry(Address address, BigDecimal balance, BigDecimal reserved) {
this.address = address;
this.balance = balance;
this.reserved = reserved;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MPBalanceEntry that = (MPBalanceEntry) o;
if (!address.equals(that.address)) return false;
if (!balance.equals(that.balance)) return false;
if (!reserved.equals(that.reserved)) return false;
return true;
}
@Override
public int hashCode() {
int result = address.hashCode();
result = 31 * result + balance.hashCode();
result = 31 * result + reserved.hashCode();
return result;
}
public Address getAddress() {
return address;
}
public BigDecimal getBalance() {
return balance;
}
public BigDecimal getReserved() {
return reserved;
}
}
|
// If we had PRIVATE packages, e.g., org.owasp.esapi.util.pvt, this would belong
// there. CipherText uses this, but doesn't expose it directly.
package org.owasp.esapi.crypto;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.StringUtilities;
import org.owasp.esapi.util.NullSafe;
/**
* Specifies all the relevant configuration data needed in constructing and
* using a {@link javax.crypto.Cipher} except for the encryption key.
* </p><p>
* The "setters" all return a reference to {@code this} so that they can be
* strung together.
* </p><p>
* Note: While this is a useful class in it's own right, it should primarily be
* regarded as an implementation class to use with ESAPI encryption, especially
* the reference implementation. It is <i>not</i> intended to be used directly
* by application developers, but rather only by those either extending ESAPI
* or in the ESAPI reference implementation. Use <i>directly</i> by application
* code is not recommended or supported.
*
* @author kevin.w.wall@gmail.com
* @since 2.0
*/
public final class CipherSpec implements Serializable {
private static final long serialVersionUID = 20090822; // 2009-08-22 version
private String cipher_xform_ = ESAPI.securityConfiguration().getCipherTransformation();
private int keySize_ = ESAPI.securityConfiguration().getEncryptionKeyLength(); // In bits
private int blockSize_ = 16; // In bytes! I.e., 128 bits!!!
private byte[] iv_ = null;
// Cipher transformation component. Format is ALG/MODE/PADDING
private enum CipherTransformationComponent { ALG, MODE, PADDING }
/**
* CTOR that explicitly sets everything.
* @param cipherXform The cipher transformation
* @param keySize The key size (in bits).
* @param blockSize The block size (in bytes).
* @param iv The initialization vector. Null if not applicable.
*/
public CipherSpec(String cipherXform, int keySize, int blockSize, final byte[] iv) {
setCipherTransformation(cipherXform);
setKeySize(keySize);
setBlockSize(blockSize);
setIV(iv);
}
/**
* CTOR that sets everything but IV.
* @param cipherXform The cipher transformation
* @param keySize The key size (in bits).
* @param blockSize The block size (in bytes).
*/
public CipherSpec(String cipherXform, int keySize, int blockSize) {
// Note: Do NOT use
// this(cipherXform, keySize, blockSize, null);
// because of assertion in setIV().
setCipherTransformation(cipherXform);
setKeySize(keySize);
setBlockSize(blockSize);
}
/** CTOR that sets everything but block size and IV. */
public CipherSpec(String cipherXform, int keySize) {
setCipherTransformation(cipherXform);
setKeySize(keySize);
}
/** CTOR that sets everything except block size. */
public CipherSpec(String cipherXform, int keySize, final byte[] iv) {
setCipherTransformation(cipherXform);
setKeySize(keySize);
setIV(iv);
}
/** CTOR that sets everything except for the cipher key size and possibly
* the IV. (IV may not be applicable--e.g., with ECB--or may not have
* been specified yet.
*/
public CipherSpec(final Cipher cipher) {
setCipherTransformation(cipher.getAlgorithm(), true);
setBlockSize(cipher.getBlockSize());
if ( cipher.getIV() != null ) {
setIV(cipher.getIV());
}
}
/** CTOR that sets everything. */
public CipherSpec(final Cipher cipher, int keySize) {
this(cipher);
setKeySize(keySize);
}
/* CTOR that sets only the IV and uses defaults for everything else. */
public CipherSpec(final byte[] iv) {
setIV(iv);
}
/**
* Default CTOR. Creates a cipher specification for 128-bit cipher
* transformation of "AES/CBC/PKCS5Padding" and a {@code null} IV.
*/
public CipherSpec() {
// All defaults
}
/**
* Set the cipher transformation for this {@code CipherSpec}.
* @param cipherXform The cipher transformation string; e.g., "DESede/CBC/PKCS5Padding".
* @return This current {@code CipherSpec} object.
*/
public CipherSpec setCipherTransformation(String cipherXform) {
setCipherTransformation(cipherXform, false);
return this;
}
/**
* Set the cipher transformation for this {@code CipherSpec}. This is only
* used by the CTOR {@code CipherSpec(Cipher)} and {@code CipherSpec(Cipher, int)}.
* @param cipherXform The cipher transformation string; e.g.,
* "DESede/CBC/PKCS5Padding".
* @param fromCipher If true, the cipher transformation was set via
* {@code Cipher.getAlgorithm()} which may only return the
* actual algorithm. In that case we check and if all 3 parts
* were not specified, then we specify the parts that were
* based on "ECB" as the default cipher mode and "NoPadding"
* as the default padding scheme.
* @return This current {@code CipherSpec} object.
*/
private CipherSpec setCipherTransformation(String cipherXform, boolean fromCipher) {
assert StringUtilities.notNullOrEmpty(cipherXform, true) : "cipherXform may not be null or empty";
int parts = cipherXform.split("/").length;
assert ( !fromCipher ? (parts == 3) : true ) :
"Malformed cipherXform (" + cipherXform + "); must have form: \"alg/mode/paddingscheme\"";
if ( fromCipher && (parts != 3) ) {
// Indicates cipherXform was set based on Cipher.getAlgorithm()
// and thus may not be a *complete* cipher transformation.
if ( parts == 1 ) {
// Only algorithm was given.
cipherXform += "/ECB/NoPadding";
} else if ( parts == 2 ) {
// Only algorithm and mode was given.
cipherXform += "/NoPadding";
} else if ( parts == 3 ) {
// All threw parts provided. Do nothing. Could happen if not compiled with
// assertions enabled.
; // Do nothing - shown only for completeness.
} else {
// Should never happen unless Cipher implementation is totally screwed up.
throw new IllegalArgumentException("Cipher transformation '" +
cipherXform + "' must have form \"alg/mode/paddingscheme\"");
}
}
assert cipherXform.split("/").length == 3 : "Implementation error setCipherTransformation()";
this.cipher_xform_ = cipherXform;
return this;
}
/**
* Get the cipher transformation.
* @return The cipher transformation {@code String}.
*/
public String getCipherTransformation() {
return cipher_xform_;
}
/**
* Set the key size for this {@code CipherSpec}.
* @param keySize The key size, in bits. Must be positive integer.
* @return This current {@code CipherSpec} object.
*/
public CipherSpec setKeySize(int keySize) {
assert keySize > 0 : "keySize must be > 0; keySize=" + keySize;
this.keySize_ = keySize;
return this;
}
/**
* Retrieve the key size, in bits.
* @return The key size, in bits, is returned.
*/
public int getKeySize() {
return keySize_;
}
/**
* Set the block size for this {@code CipherSpec}.
* @param blockSize The block size, in bytes. Must be positive integer.
* @return This current {@code CipherSpec} object.
*/
public CipherSpec setBlockSize(int blockSize) {
assert blockSize > 0 : "blockSize must be > 0; blockSize=" + blockSize;
this.blockSize_ = blockSize;
return this;
}
/**
* Retrieve the block size, in bytes.
* @return The block size, in bytes, is returned.
*/
public int getBlockSize() {
return blockSize_;
}
/**
* Retrieve the cipher algorithm.
* @return The cipher algorithm.
*/
public String getCipherAlgorithm() {
return getFromCipherXform(CipherTransformationComponent.ALG);
}
/**
* Retrieve the cipher mode.
* @return The cipher mode.
*/
public String getCipherMode() {
return getFromCipherXform(CipherTransformationComponent.MODE);
}
/**
* Retrieve the cipher padding scheme.
* @return The padding scheme is returned.
*/
public String getPaddingScheme() {
return getFromCipherXform(CipherTransformationComponent.PADDING);
}
/**
* Retrieve the initialization vector (IV).
* @return The IV as a byte array.
*/
public byte[] getIV() {
return iv_;
}
/**
* Set the initialization vector (IV).
* @param iv The byte array to set as the IV. A copy of the IV is saved.
* This parameter is ignored if the cipher mode does not
* require an IV.
* @return This current {@code CipherSpec} object.
*/
public CipherSpec setIV(final byte[] iv) {
assert requiresIV() && (iv != null && iv.length != 0) : "Required IV cannot be null or 0 length";
// Don't store a reference, but make a copy!
if ( iv != null ) { // Allow null IV for ECB mode.
iv_ = new byte[ iv.length ];
CryptoHelper.copyByteArray(iv, iv_);
}
return this;
}
/**
* Return true if the cipher mode requires an IV.
* @return True if the cipher mode requires an IV, otherwise false.
* */
public boolean requiresIV() {
String cm = getCipherMode();
// Add any other cipher modes supported by JCE but not requiring IV.
// ECB is the only one I'm aware of that doesn't. Mode is not case
// sensitive.
if ( "ECB".equalsIgnoreCase(cm) ) {
return false;
}
return true;
}
/**
* Override {@code Object.toString()} to provide something more useful.
* @return A meaningful string describing this object.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("CipherSpec: ");
sb.append( getCipherTransformation() ).append("; keysize= ").append( getKeySize() );
sb.append(" bits; blocksize= ").append( getBlockSize() ).append(" bytes");
byte[] iv = getIV();
String ivLen = null;
if ( iv != null ) {
ivLen = "" + iv.length; // Convert length to a string
} else {
ivLen = "[No IV present (not set or not required)]";
}
sb.append("; IV length = ").append( ivLen ).append(" bytes.");
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object other) {
boolean result = false;
if ( this == other )
return true;
if ( other == null )
return false;
if ( other instanceof CipherSpec) {
CipherSpec that = (CipherSpec)other;
result = (that.canEqual(this) &&
NullSafe.equals(this.cipher_xform_, that.cipher_xform_) &&
this.keySize_ == that.keySize_ &&
this.blockSize_ == that.blockSize_ &&
// Comparison safe from timing attacks.
CryptoHelper.arrayCompare(this.iv_, that.iv_) );
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
StringBuilder sb = new StringBuilder();
sb.append( getCipherTransformation() );
sb.append( "" + getKeySize() );
sb.append( "" + getBlockSize() );
byte[] iv = getIV();
if ( iv != null && iv.length > 0 ) {
String ivStr = null;
try {
ivStr = new String(iv, "UTF-8");
}
catch(UnsupportedEncodingException ex) {
// Should never happen as UTF-8 encode supported by rt.jar,
// but it it does, just use default encoding.
ivStr = new String(iv);
}
sb.append( ivStr );
}
return sb.toString().hashCode();
}
protected boolean canEqual(Object other) {
return (other instanceof CipherSpec);
}
/**
* Split the current cipher transformation and return the requested part.
* @param component The component of the cipher transformation to return.
* @return The cipher algorithm, cipher mode, or padding, as requested.
*/
private String getFromCipherXform(CipherTransformationComponent component) {
int part = component.ordinal();
String[] parts = getCipherTransformation().split("/");
assert parts.length == 3 : "Invalid cipher transformation: " + getCipherTransformation();
return parts[part];
}
}
|
package org.threeten.extra.chrono;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.YEAR;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_MONTH;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_WEEK;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_YEAR;
import static org.threeten.extra.chrono.PaxChronology.MONTHS_IN_YEAR;
import java.io.Serializable;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.ChronoPeriod;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
import java.util.Objects;
public final class PaxDate extends AbstractDate implements ChronoLocalDate, Serializable {
private static final long serialVersionUID = -2229133057743750072L;
/**
* Count of days from the start of the Pax Epoch to ISO 1970-01-01.
*/
private static final int DAYS_PAX_0000_TO_ISO_1970 = 719527;
/**
* Number of seconds in a day.
*/
private static final long SECONDS_PER_DAY = 86400;
/**
* Number of years in a decade.
*/
private static final long YEARS_IN_DECADE = 10;
/**
* Number of years in a century.
*/
private static final long YEARS_IN_CENTURY = 100;
/**
* Number of years in a millennium.
*/
private static final long YEARS_IN_MILLENNIUM = 1000;
/**
* The year.
*/
private final int year;
/**
* The month-of-year.
*/
private final short month;
/**
* The day-of-month.
*/
private final short day;
/**
* Constructor, previously validated.
*
* @param year the year to represent
* @param month the month-of-year to represent, from 1 to 14
* @param dayOfMonth the day-of-month to represent, valid for year-month, from 1 to 28
*/
private PaxDate(final int year, final int month, final int dayOfMonth) {
this.year = year;
this.month = (short) month;
this.day = (short) dayOfMonth;
}
public static PaxDate from(final TemporalAccessor temporal) {
final LocalDate date = temporal.query(TemporalQueries.localDate());
if (date == null) {
throw new DateTimeException("Unable to obtain LocalDate from TemporalAccessor: "
+ temporal + ", type " + temporal.getClass().getName());
}
return ofEpochDay(date.toEpochDay());
}
/**
* Obtains the current date from the system clock in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default time-zone to obtain the current date.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.
*
* @return the current date using the system clock and default time-zone, not null
*/
public static PaxDate now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current date from the specified clock.
* <p>
* This will query the specified clock to obtain the current date - today. Using this method allows the use of an alternate clock for testing. The alternate clock may be introduced using
* {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current date, not null
*/
public static PaxDate now(final Clock clock) {
Objects.requireNonNull(clock, "clock");
// Called once, so the instant and it's offset will use the same value
final Instant now = clock.instant();
final ZoneOffset offset = clock.getZone().getRules().getOffset(now);
final long epochSec = now.getEpochSecond() + offset.getTotalSeconds();
final long epochDay = Math.floorDiv(epochSec, SECONDS_PER_DAY);
return ofEpochDay(epochDay);
}
/**
* Obtains the current date from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date. Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current date using the system clock, not null
*/
public static PaxDate now(final ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains an instance of {@code PaxDate} from a year, month and day.
* <p>
* The day must be valid for the year and month, otherwise an exception will be thrown.
*
* @param prolepticYear the year to represent, from MIN_YEAR to MAX_YEAR
* @param month the month-of-year to represent, from 1 to 14
* @param dayOfMonth the day-of-month to represent, from 1 to 28
* @return the local date, not null
* @throws DateTimeException if the value of any field is out of range
* @throws DateTimeException if the day-of-month is invalid for the month-year
*/
public static PaxDate of(final int prolepticYear, final int month, final int dayOfMonth) {
YEAR.checkValidValue(prolepticYear);
if (month < 1 || month > MONTHS_IN_YEAR + 1) {
throw new DateTimeException("Invalid month " + month);
} else if (month == MONTHS_IN_YEAR + 1 && !PaxChronology.INSTANCE.isLeapYear(prolepticYear)) {
throw new DateTimeException("Invalid month 14 as " + prolepticYear + "is not a leap year");
}
if (dayOfMonth < 1 || dayOfMonth > DAYS_IN_MONTH) {
throw new DateTimeException("Invalid day-of-month " + dayOfMonth);
} else if (dayOfMonth > DAYS_IN_WEEK && month == MONTHS_IN_YEAR && PaxChronology.INSTANCE.isLeapYear(prolepticYear)) {
throw new DateTimeException("Invalid date during Pax as " + prolepticYear + " is a leap year");
}
return new PaxDate(prolepticYear, month, dayOfMonth);
}
public static PaxDate ofEpochDay(final long epochDay) {
// TODO Auto-generated method stub
return null;
}
/**
* Obtains an instance of {@code PaxDate} from a year and day-of-year.
* <p>
* The day-of-year must be valid for the year, otherwise an exception will be thrown.
*
* @param prolepticYear the year to represent, from MIN_YEAR to MAX_YEAR
* @param dayOfYear the day-of-year to represent, from 1 to 371
* @return the local date, not null
* @throws DateTimeException if the value of any field is out of range
* @throws DateTimeException if the day-of-year is invalid for the month-year
*/
public static PaxDate ofYearDay(final int prolepticYear, final int dayOfYear) {
YEAR.checkValidValue(prolepticYear);
if (dayOfYear < 1 || dayOfYear > DAYS_IN_YEAR + DAYS_IN_WEEK) {
throw new DateTimeException("Inavlid date 'DayOfYear " + dayOfYear + "'");
}
final boolean leap = PaxChronology.INSTANCE.isLeapYear(prolepticYear);
if (dayOfYear > DAYS_IN_YEAR && !leap) {
throw new DateTimeException("Invalid date 'DayOfYear " + dayOfYear + "' as '" + prolepticYear + "' is not a leap year");
}
int month = (dayOfYear - 1) / MONTHS_IN_YEAR;
// In leap years, the leap-month is shorter than the following month, so needs to be adjusted.
if (month == MONTHS_IN_YEAR + 1
&& dayOfYear < DAYS_IN_YEAR - DAYS_IN_MONTH + DAYS_IN_WEEK + 1) {
month
}
// Subtract days-at-start-of-month from days in year
int dayOfMonth = dayOfYear - (month - 1) * DAYS_IN_MONTH;
// Adjust for shorter inserted leap-month.
if (month == MONTHS_IN_YEAR + 1) {
dayOfMonth += DAYS_IN_MONTH - DAYS_IN_WEEK;
}
return of(prolepticYear, month, dayOfMonth);
}
/**
* The Pax day-of-week is aligned to Sunday, not Monday as in the ISO calendar.
*
* @param dayOfWeek The Pax day-of-week, where 1 is Sunday and 7 is Saturday.
* @return The ISO day-of-week, where 1 is Monday and 7 is Sunday.
*/
private static long getISODayOfWeek(final int dayOfWeek) {
return dayOfWeek == 1 ? DAYS_IN_WEEK : dayOfWeek - 1;
}
/**
* Get the count of leap months since proleptic month 0.
* <p>
* This number is negative if the month is prior to Pax year 0.
*
* @param prolepticMonth The month.
* @return The number of leap months since proleptic month 0.
*/
@SuppressWarnings("checkstyle:magicnumber")
private static long getLeapMonthsBefore(final long prolepticMonth) {
// need to return a non-negative number.
final long absMonth = Math.abs(prolepticMonth);
// See getLeapYearsBefore for the reasoning behind the calculation.
// return Long.signum(prolepticMonth) * (17 * (absMonth / (100 * MONTHS_IN_YEAR + getLeapYearsbefore(100))) + ((absMonth - 1) / (100 * MONTHS_IN_YEAR +
// getLeapYearsbefore(100))) - ((absMonth - 1) / (400 * MONTHS_IN_YEAR + getLeapYearsbefore(400)))
// + ((absMonth % (100 * MONTHS_IN_YEAR + getLeapYearsbefore(100))) / (6 * MONTHS_IN_YEAR + 1)));
return Long.signum(prolepticMonth) * (17 * (absMonth / 1317) + ((absMonth - 1) / 1317) - ((absMonth - 1) / 5271) + ((absMonth % 1317) / 79));
}
/**
* Get the count of leap years since Pax year 0.
* <p>
* This number is negative if the year is prior to Pax year 0.
*
* @param prolepticYear The year.
* @return The number of leap years since Pax year 0.
*/
@SuppressWarnings("checkstyle:magicnumber")
private static int getLeapYearsBefore(final int prolepticYear) {
// need to return a non-negative number.
final int absYear = Math.abs(prolepticYear);
// Calculation is like this:
// - In every century (years X00 - X99), there are 17 leap years (multiples of 6 and at 99).
// - Every century is a leap year...
// - ... except every 400 years.
// - Count the elapsed multiples of 6 since the start of the century.
return Integer.signum(prolepticYear) * (17 * (absYear / 100) + ((absYear - 1) / 100) - ((absYear - 1) / 400) + ((absYear % 100) / 6));
}
/**
* Resolves the date, resolving days past the end of month, or non-existent months.
*
* @param year the year to represent, validated from MIN_YEAR to MAX_YEAR
* @param month the month-of-year to represent, validated from 1 to 14
* @param day the day-of-month to represent, validated from 1 to 28
* @return the resolved date, not null
*/
private static PaxDate resolvePreviousValid(final int year, final int month, final int day) {
final int monthR = Math.min(month, MONTHS_IN_YEAR + (PaxChronology.INSTANCE.isLeapYear(year) ? 1 : 0));
final int dayR = Math.min(day, month == MONTHS_IN_YEAR && PaxChronology.INSTANCE.isLeapYear(year) ? DAYS_IN_WEEK : DAYS_IN_MONTH);
return PaxDate.of(year, monthR, dayR);
}
@Override
public PaxChronology getChronology() {
return PaxChronology.INSTANCE;
}
/**
* Gets the day-of-month field.
* <p>
* This method returns the primitive {@code int} value for the day-of-month.
*
* @return the day-of-month, from 1 to 28
*/
@Override
public int getDayOfMonth() {
return day;
}
/**
* Get the day of the year.
*
* @return The day of the year, from 1 to 371.
*/
@Override
public int getDayOfYear() {
return (getMonth() - 1) * DAYS_IN_MONTH
- (getMonth() == MONTHS_IN_YEAR + 1 ? DAYS_IN_MONTH + DAYS_IN_WEEK : 0) + getDayOfMonth();
}
/**
* Gets the month-of-year field from 1 to 14.
* <p>
* This method returns the month as an {@code int} from 1 to 14.
*
* @return the month-of-year, from 1 to 14
*/
@Override
public int getMonth() {
return month;
}
/**
* Gets the year field.
* <p>
* This method returns the primitive {@code int} value for the year.
* <p>
* The year returned by this method is proleptic as per {@code get(YEAR)}. To obtain the year-of-era, use {@code get(YEAR_OF_ERA}.
*
* @return the year
*/
public int getYear() {
return year;
}
@Override
public int lengthOfMonth() {
return month == MONTHS_IN_YEAR && isLeapYear() ? DAYS_IN_WEEK : DAYS_IN_MONTH;
}
@Override
public int lengthOfYear() {
return DAYS_IN_YEAR + (isLeapYear() ? DAYS_IN_WEEK : 0);
}
/**
* Returns a copy of this {@code PaxDate} with the specified number of days subtracted.
* <p>
* This method subtracts the specified amount from the days field decrementing the month and year fields as necessary to ensure the result remains valid. The result is only invalid if the
* maximum/minimum year is exceeded.
* <p>
* For example, 2009-01-01 minus one day would result in 2008-13-28.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param daysToSubtract the days to subtract, may be negative
* @return a {@code PaxDate} based on this date with the days subtracted, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
public PaxDate minusDays(final long daysToSubtract) {
return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in months subtracted.
* <p>
* This method subtracts the specified amount from the months field in three steps:
* <ol>
* <li>Subtract the input months to the month-of-year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day-of-month to the last valid day if necessary</li>
* </ol>
* <p>
* For example, 2006-14-09 minus one month would result in the invalid date 2006-13-09. Instead of returning an invalid result, the last valid day of the leap week, 2006-13-07, is selected
* instead.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthsToSubtract the months to subtract, may be negative
* @return a {@code PaxDate} based on this date with the months subtracted, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
public PaxDate minusMonths(final long monthsToSubtract) {
return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract));
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in weeks subtracted.
* <p>
* This method subtracts the specified amount in weeks from the days field decrementing the month and year fields as necessary to ensure the result remains valid. The result is only invalid if the
* maximum/minimum year is exceeded.
* <p>
* For example, 2009-01-07 minus one week would result in 2008-13-28.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param weeksToSubtract the weeks to subtract, may be negative
* @return a {@code PaxDate} based on this date with the weeks subtracted, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
public PaxDate minusWeeks(final long weeksToSubtract) {
return (weeksToSubtract == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeksToSubtract));
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in years subtracted.
* <p>
* This method subtracts the specified amount from the years field in two steps:
* <ol>
* <li>Subtract the input years to the year field</li>
* <li>If necessary, shift the index to account for the inserted/deleted leap-month.</li>
* </ol>
* <p>
* In the Pax Calendar, the month of December is 13th in non-leap-years, and 14th in leap years. Shifting the index of the month thus means the month would still be the same.
* <p>
* In the case of moving from the inserted leap-month (destination year is non-leap), the month index is retained. This has the effect of retaining the same day-of-year.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToSubtract the years to subtract, may be negative
* @return a {@code PaxDate} based on this date with the years subtracted, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
public PaxDate minusYears(final long yearsToSubtract) {
return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
}
/**
* Returns a copy of this {@code PaxDate} with the specified number of days added.
* <p>
* This method adds the specified amount to the days field incrementing the month and year fields as necessary to ensure the result remains valid. The result is only invalid if the maximum/minimum
* year is exceeded.
* <p>
* For example, 2008-13-28 plus one day would result in 2009-01-01.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param daysToAdd the days to add, may be negative
* @return a {@code PaxDate} based on this date with the days added, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
@Override
public PaxDate plusDays(final long daysToAdd) {
if (daysToAdd == 0) {
return this;
}
final long epochOffset = Math.addExact(toEpochDay(), daysToAdd);
return PaxDate.ofEpochDay(epochOffset);
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in months added.
* <p>
* This method adds the specified amount to the months field in three steps:
* <ol>
* <li>Add the input months to the month-of-year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day-of-month to the last valid day if necessary</li>
* </ol>
* <p>
* For example, 2006-12-13 plus one month would result in the invalid date 2006-13-13. Instead of returning an invalid result, the last valid day of the month, 2006-13-07, is selected instead.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthsToAdd the months to add, may be negative
* @return a {@code PaxDate} based on this date with the months added, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
@Override
public PaxDate plusMonths(final long monthsToAdd) {
if (monthsToAdd == 0) {
return this;
}
final long calcMonths = getProlepticMonth() + monthsToAdd;
// "Regularize" the month count, as if years were all 13 months long.
final long monthsRegularized = calcMonths - getLeapMonthsBefore(calcMonths);
final int newYear = YEAR.checkValidIntValue(Math.floorDiv(monthsRegularized, MONTHS_IN_YEAR));
final int newMonth = (int) calcMonths - (newYear * MONTHS_IN_YEAR + getLeapYearsBefore(newYear));
return resolvePreviousValid(newYear, newMonth, getDayOfMonth());
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in weeks added.
* <p>
* This method adds the specified amount in weeks to the days field incrementing the month and year fields as necessary to ensure the result remains valid. The result is only invalid if the
* maximum/minimum year is exceeded.
* <p>
* For example, 2008-12-28 plus one week would result in 2009-01-07.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param weeksToAdd the weeks to add, may be negative
* @return a {@code PaxDate} based on this date with the weeks added, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
public PaxDate plusWeeks(final long weeksToAdd) {
return plusDays(Math.multiplyExact(weeksToAdd, DAYS_IN_WEEK));
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in years added.
* <p>
* This method adds the specified amount to the years field in two steps:
* <ol>
* <li>Add the input years to the year field</li>
* <li>If necessary, shift the index to account for the inserted/deleted leap-month.</li>
* </ol>
* <p>
* In the Pax Calendar, the month of December is 13th in non-leap-years, and 14th in leap years. Shifting the index of the month thus means the month would still be the same.
* <p>
* In the case of moving from the inserted leap-month (destination year is non-leap), the month index is retained. This has the effect of retaining the same day-of-year.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
* @return a {@code PaxDate} based on this date with the years added, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
@Override
public PaxDate plusYears(final long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
final int newYear = YEAR.checkValidIntValue(getYear() + yearsToAdd);
// Retain actual month (not index) in the case where a leap month is to be inserted.
if (getMonth() == MONTHS_IN_YEAR && !isLeapYear() && PaxChronology.INSTANCE.isLeapYear(newYear)) {
return of(newYear, getMonth() + 1, getDayOfMonth());
}
// Otherwise, one of the following is true:
// 1 - Before the leap month, nothing to do (most common)
// 2 - Both source and destination in leap-month, nothing to do
// 3 - Both source and destination after leap month in leap year, nothing to do
// 4 - Source in leap month, but destination year not leap. Retain month index, preserving day-of-year.
// 5 - Source after leap month, but destination year not leap. Move month index back.
return resolvePreviousValid(newYear, month, day);
}
@Override
public ValueRange range(final TemporalField field) {
if (field instanceof ChronoField) {
if (isSupported(field)) {
switch ((ChronoField) field) {
case ALIGNED_WEEK_OF_MONTH:
return ValueRange.of(1, (lengthOfMonth() - 1) / DAYS_IN_WEEK);
case ALIGNED_WEEK_OF_YEAR:
return ValueRange.of(1, (lengthOfYear() - 1) / DAYS_IN_WEEK);
case DAY_OF_MONTH:
return ValueRange.of(1, lengthOfMonth());
case DAY_OF_YEAR:
return ValueRange.of(1, lengthOfYear());
case MONTH_OF_YEAR:
return ValueRange.of(1, MONTHS_IN_YEAR + (isLeapYear() ? 1 : 0));
default:
return field.range();
}
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.rangeRefinedBy(this);
}
@Override
public long toEpochDay() {
final long days = getYear() * DAYS_IN_YEAR + getLeapYearsBefore(getYear()) * DAYS_IN_WEEK + (getMonth() - 1) * DAYS_IN_MONTH + getDayOfMonth() - 1;
// Adjust for short leap month if after, then rebase to ISO 1970.
return days - (getMonth() == MONTHS_IN_YEAR + 1 ? DAYS_IN_MONTH - DAYS_IN_WEEK : 0) - DAYS_PAX_0000_TO_ISO_1970;
}
@Override
public ChronoPeriod until(final ChronoLocalDate endDate) {
final PaxDate end = PaxDate.from(endDate);
final long years = yearsUntil(end);
// Get to the same "whole" year.
final PaxDate sameYearEnd = end.plusYears(years);
final int months = (int) monthsUntil(sameYearEnd);
final int days = (int) daysUntil(sameYearEnd.plusMonths(months));
return Period.of(Math.toIntExact(years), months, days);
}
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit) {
final PaxDate end = PaxDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case DAYS:
return daysUntil(end);
case WEEKS:
return daysUntil(end) / DAYS_IN_WEEK;
case MONTHS:
return monthsUntil(end);
case YEARS:
return yearsUntil(end);
case DECADES:
return yearsUntil(end) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(end) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(end) / YEARS_IN_MILLENNIUM;
case ERAS:
return end.getLong(ERA) - getLong(ERA);
default:
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
}
return unit.between(this, end);
}
@Override
public PaxDate with(TemporalAdjuster adjuster) {
return (PaxDate) adjuster.adjustInto(this);
}
@Override
public PaxDate with(final TemporalField field, final long newValue) {
if (field == ChronoField.YEAR) {
return plusYears(newValue - getYear());
}
return (PaxDate) super.with(field, newValue);
}
/**
* Returns a copy of this date with the day-of-month altered. If the resulting date is invalid, an exception is thrown.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param newDayOfMonth the day-of-month to set in the result, from 1 to 7 or 28
* @return a {@code PaxDate} based on this date with the requested day, not null
* @throws DateTimeException if the day-of-month value is invalid
* @throws DateTimeException if the day-of-month is invalid for the month-year
*/
public PaxDate withDayOfMonth(final int newDayOfMonth) {
if (getDayOfMonth() == newDayOfMonth) {
return this;
}
return of(getYear(), getMonth(), newDayOfMonth);
}
/**
* Returns a copy of this date with the day-of-year altered. If the resulting date is invalid, an exception is thrown.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param dayOfYear the day-of-year to set in the result, from 1 to 364 or 371
* @return a {@code PaxDate} based on this date with the requested day, not null
* @throws DateTimeException if the day-of-year value is invalid
* @throws DateTimeException if the day-of-year is invalid for the year
*/
@Override
public PaxDate withDayOfYear(final int dayOfYear) {
if (this.getDayOfYear() == dayOfYear) {
return this;
}
return ofYearDay(year, dayOfYear);
}
/**
* Get the number of days from this date to the given day.
*
* @param end The end date.
* @return The number of days from this date to the given day.
*/
private long daysUntil(final PaxDate end) {
return end.toEpochDay() - toEpochDay();
}
/**
* Get the proleptic month from the start of the epoch (Pax 0000).
*
* @return The proleptic month.
*/
@Override
long getProlepticMonth() {
return getYear() * MONTHS_IN_YEAR + getLeapYearsBefore(getYear()) + getMonth() - 1;
}
/**
* Get the number of months from this date to the given day.
*
* @param end The end date.
* @return The number of months from this date to the given day.
*/
private long monthsUntil(final PaxDate end) {
// Multiplying by the days-in-month (+1) makes the propleptic count a "place" (ie, the 10's place).
// This means that if the starting date is before, it moves the count to the prior unit (24 - 8 = 16, and we only care about the 10's place).
final long startMonth = getProlepticMonth() * (DAYS_IN_MONTH + 1) + getDayOfMonth();
final long endMonth = end.getProlepticMonth() * (DAYS_IN_MONTH + 1) + end.getDayOfMonth();
return (endMonth - startMonth) / (DAYS_IN_MONTH + 1);
}
/**
* Get the number of years from this date to the given day.
*
* @param end The end date.
* @return The number of years from this date to the given day.
*/
private long yearsUntil(final PaxDate end) {
// TODO: Correct this to deal with moving from/into leap months (!)
// Multiplying by the (maximum) months-in-year (+1) makes the propleptic count a "place" (ie, the 10's place).
// This means that if the starting date is before, it moves the count to the prior unit (24 - 8 = 16, and we only care about the 10's place).
final long startYear = getYear() * (MONTHS_IN_YEAR + 1 + 1) + getMonth();
final long endYear = end.getYear() * (MONTHS_IN_YEAR + 1 + 1) + end.getMonth();
return (endYear - startYear) / (MONTHS_IN_YEAR + 1 + 1);
}
@Override
public boolean isSupported(TemporalUnit arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isSupported(TemporalField arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public Temporal adjustInto(Temporal arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int compareTo(ChronoLocalDate arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
int getProlepticYear() {
// TODO Auto-generated method stub
return 0;
}
@Override
ValueRange rangeAlignedWeekOfMonth() {
// TODO Auto-generated method stub
return null;
}
@Override
AbstractDate resolvePrevious(int newYear, int newMonth, int dayOfMonth) {
// TODO Auto-generated method stub
return null;
}
}
|
package org.wyona.webapp.mail;
import com.sun.mail.smtp.SMTPMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.wyona.webapp.interfaces.EmailValidation;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Value;
@Component
public class EmailSender {
private final Session session;
private final EmailValidation emailValidation;
@Value("${from.email.address}")
private String fromEmail;
@Autowired
public EmailSender(EmailSenderCofig config, EmailValidation emailValidation){
this.emailValidation = emailValidation;
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", true);
// TODO: Seems to cause trouble, when the mail server uses a self-signed certificate
//props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", config.getHost());
props.put("mail.smtp.port", config.getPort());
session = Session.getInstance(
props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(config.getUsername(), config.getPassword());
}
}
);
}
/**
* Send greetings by email
*/
public void sendEmailGreeting(String email, String subject, String text, boolean isHTMLMessage, MultipartFile attachment) throws MessagingException {
validateParameters(email, subject, text);
Message message = composeMessage(email, subject, text, isHTMLMessage, attachment);
Transport.send(message);
}
private void validateParameters(String email, String subject, String text) {
// I like to validate input parameters of service public methods, to ensure that each client sends all the needed parameters.
// I send runtime exceptions in this case, not forcing the clients to handle specific checked exceptions.
Assert.isTrue(!StringUtils.isEmpty(email), "Email recipient must be specified");
Assert.isTrue(emailValidation.isEmailValid(email), "Email recipient not in valid format");
Assert.isTrue(!StringUtils.isEmpty(subject), "Email subject must be specified");
Assert.isTrue(!StringUtils.isEmpty(text), "Email content must be specified");
}
private Message composeMessage(String email, String subject, String text, boolean isHTMLMessage, MultipartFile attachment) throws MessagingException {
Message message = new SMTPMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
message.setSubject(subject);
Multipart multipart = new MimeMultipart();
String mimeType = "text/plain";
if (isHTMLMessage) {
mimeType = "text/html";
}
BodyPart messageText = new MimeBodyPart();
messageText.setContent(text, mimeType);
multipart.addBodyPart(messageText);
if (attachment != null) {
try {
ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getInputStream(), attachment.getContentType());
MimeBodyPart messageAttachment = new MimeBodyPart();
messageAttachment.setDataHandler(new DataHandler(dataSource));
messageAttachment.setFileName(attachment.getOriginalFilename());
multipart.addBodyPart(messageAttachment);
} catch (IOException e) {
throw new MessagingException(e.getMessage(), e);
}
}
message.setContent(multipart);
return message;
}
}
|
package org.xtx.ut4converter.t3d;
import org.xtx.ut4converter.MapConverter;
import org.xtx.ut4converter.UTGames;
/**
* A mover is a brush that moves in level.
*
* @author XtremeXp
*/
public class T3DMover extends T3DBrush {
/**
* Common properties of basic mover
*/
MoverProperties moverProperties;
/**
*
* @param mc
* @param t3dClass
*/
public T3DMover(MapConverter mc, String t3dClass) {
super(mc, t3dClass);
moverProperties = new MoverProperties(this);
}
@Override
public boolean analyseT3DData(String line) {
if (moverProperties.analyseT3DData(line)) {
} else {
return super.analyseT3DData(line);
}
return true;
}
@Override
public void scale(Double newScale) {
moverProperties.scale(newScale);
super.scale(newScale);
}
/**
*
* @return
*/
@Override
public String toString() {
if (mapConverter.getOutputGame() == UTGames.UTGame.UT4) {
sbf.append(moverProperties.toString(sbf));
// TODO for UT4 make converter from brush to .fbx Autodesk file and
// transform into StaticMesh
// TODO for UT3 make converter from brush to .ase file and transform
// into StaticMesh
// Write the mover as brush as well so we can convert it in
// staticmesh in UE4 Editor ...
String originalName = this.name;
this.brushClass = BrushClass.Brush;
this.name += "_Brush";
String x = super.toString();
// put back original name (might be used later for linked actors .
// e.g: liftexit)
this.name = originalName;
return x;
}
// TODO write mover UT UE<=3
else {
return super.toString();
}
}
@Override
public void convert() {
if (mapConverter.convertSounds()) {
moverProperties.convert();
}
super.convert();
}
public MoverProperties getMoverProperties() {
return moverProperties;
}
}
|
package org.zendesk.client.v2.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import java.util.List;
/**
* @author stephenc
* @since 05/04/2013 12:03
*/
public class Field {
private Long id;
private String url;
private String type;
private String title;
private String rawTitle;
private String description;
private String rawDescription;
private Integer position;
private Boolean active;
private Boolean required;
private Boolean collapsedForAgents;
private String regexpForValidation;
private String titleInPortal;
private String rawTitleInPortal;
private Boolean visibleInPortal;
private Boolean editableInPortal;
private Boolean requiredInPortal;
private String tag;
private Date createdAt;
private Date updatedAt;
private List<Option> systemFieldOptions;
private List<Option> customFieldOptions;
private Boolean removable;
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
@JsonProperty("collapsed_for_agents")
public Boolean getCollapsedForAgents() {
return collapsedForAgents;
}
public void setCollapsedForAgents(Boolean collapsedForAgents) {
this.collapsedForAgents = collapsedForAgents;
}
@JsonProperty("created_at")
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
@JsonProperty("custom_field_options")
public List<Option> getCustomFieldOptions() {
return customFieldOptions;
}
public void setCustomFieldOptions(List<Option> customFieldOptions) {
this.customFieldOptions = customFieldOptions;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@JsonProperty("editable_in_portal")
public Boolean getEditableInPortal() {
return editableInPortal;
}
public void setEditableInPortal(Boolean editableInPortal) {
this.editableInPortal = editableInPortal;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
@JsonProperty("raw_description")
public String getRawDescription() {
return rawDescription;
}
public void setRawDescription(String rawDescription) {
this.rawDescription = rawDescription;
}
@JsonProperty("raw_title")
public String getRawTitle() {
return rawTitle;
}
public void setRawTitle(String rawTitle) {
this.rawTitle = rawTitle;
}
@JsonProperty("raw_title_in_portal")
public String getRawTitleInPortal() {
return rawTitleInPortal;
}
public void setRawTitleInPortal(String rawTitleInPortal) {
this.rawTitleInPortal = rawTitleInPortal;
}
@JsonProperty("regexp_for_validation")
public String getRegexpForValidation() {
return regexpForValidation;
}
public void setRegexpForValidation(String regexpForValidation) {
this.regexpForValidation = regexpForValidation;
}
public Boolean getRemovable() {
return removable;
}
public void setRemovable(Boolean removable) {
this.removable = removable;
}
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
@JsonProperty("required_in_portal")
public Boolean getRequiredInPortal() {
return requiredInPortal;
}
public void setRequiredInPortal(Boolean requiredInPortal) {
this.requiredInPortal = requiredInPortal;
}
@JsonProperty("system_field_options")
public List<Option> getSystemFieldOptions() {
return systemFieldOptions;
}
public void setSystemFieldOptions(List<Option> systemFieldOptions) {
this.systemFieldOptions = systemFieldOptions;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@JsonProperty("title_in_portal")
public String getTitleInPortal() {
return titleInPortal;
}
public void setTitleInPortal(String titleInPortal) {
this.titleInPortal = titleInPortal;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@JsonProperty("updated_at")
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@JsonProperty("visible_in_portal")
public Boolean getVisibleInPortal() {
return visibleInPortal;
}
public void setVisibleInPortal(Boolean visibleInPortal) {
this.visibleInPortal = visibleInPortal;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Field");
sb.append("{active=").append(active);
sb.append(", id=").append(id);
sb.append(", url='").append(url).append('\'');
sb.append(", type='").append(type).append('\'');
sb.append(", title='").append(title).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", position=").append(position);
sb.append(", required=").append(required);
sb.append(", collapsedForAgents=").append(collapsedForAgents);
sb.append(", regexpForValidation='").append(regexpForValidation).append('\'');
sb.append(", titleInPortal='").append(titleInPortal).append('\'');
sb.append(", visibleInPortal=").append(visibleInPortal);
sb.append(", editableInPortal=").append(editableInPortal);
sb.append(", requiredInPortal=").append(requiredInPortal);
sb.append(", tag='").append(tag).append('\'');
sb.append(", createdAt=").append(createdAt);
sb.append(", updatedAt=").append(updatedAt);
sb.append(", customFieldOptions=").append(customFieldOptions);
sb.append('}');
return sb.toString();
}
public static class Option {
private String name;
private String value;
private Option() {
}
private Option(String name, String value) {
this.name = name;
this.value = value;
}
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;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Option");
sb.append("{name='").append(name).append('\'');
sb.append(", value='").append(value).append('\'');
sb.append('}');
return sb.toString();
}
}
}
|
package ru.carabi.server.kernel;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.xml.ws.Holder;
import org.apache.commons.codec.digest.DigestUtils;
import ru.carabi.server.CarabiException;
import ru.carabi.server.entities.CarabiUser;
import ru.carabi.server.entities.ConnectionSchema;
import ru.carabi.server.RegisterException;
import ru.carabi.server.Settings;
import ru.carabi.server.UserLogon;
import ru.carabi.server.entities.CarabiAppServer;
import ru.carabi.server.entities.UserServerEnter;
import ru.carabi.server.kernel.oracle.QueryParameter;
import ru.carabi.server.kernel.oracle.SqlQueryBean;
import ru.carabi.server.logging.CarabiLogging;
import ru.carabi.server.soap.GuestSesion;
import ru.carabi.server.soap.SoapUserInfo;
@Stateless
public class GuestBean {
private static final Logger logger = Logger.getLogger("ru.carabi.server.kernel.GuestBean");
Context ctx;
private AuthorizeBean authorize;
@EJB private UsersControllerBean uc;
@EJB private SqlQueryBean sqlQueryBean;
@PersistenceContext(unitName = "ru.carabi.server_carabiserver-kernel")
private EntityManager em;
private static final ResourceBundle messages = ResourceBundle.getBundle("ru.carabi.server.soap.Messages");
public GuestBean() throws NamingException {
ctx = new InitialContext();
}
public String getWebUserId(UserLogon ul) throws RegisterException
{
logger.log(Level.INFO, "ru.carabi.server.kernel.GuestBean.getWebUserId called with param: UserLogon={0}",
ul.toString());
// prepare sql request
String script =
"begin\n" +
" documents.REGISTER_USER("+String.valueOf(ul.getId())+",2);\n"+
" :result := appl_web_user.get_web_user_id(documents.GET_USER_ID);\n"+
"end;";
QueryParameter qp = new QueryParameter();
qp.setName("result");
qp.setType(QueryParameter.Type.NUMBER);
qp.setIsIn(QueryParameter.FALSE);
qp.setIsOut(QueryParameter.TRUE);
Holder<ArrayList<QueryParameter>> params = new Holder<>();
params.value = new ArrayList<>();
params.value.add(qp);
// try to read webuserId from db
final int execRes = sqlQueryBean.executeScript(ul, script, params, 1);
if (execRes < 0) {
final RegisterException e = new RegisterException(RegisterException.MessageCode.ORACLE_ERROR);
logger.log(Level.SEVERE, "Sql поиска веб-пользователя возвратил код ошибки: "+ execRes, e);
throw e;
}
final String webuserId = qp.getValue();
if (null == webuserId || "".equals(webuserId)) {
final String msg = "Sql поиска веб-пользователя возвратил пустой результат. "
+"Веб-пользователь не найден для данного караби-пользователя.";
final RegisterException e = new RegisterException(RegisterException.MessageCode.NO_WEBUSER);
logger.log(Level.SEVERE, msg, e);
throw e;
}
return webuserId; // success, we have it
}
public int wellcomeNN(
final String login,
String version,
int vc,
int schemaID,
final String schemaName,
Holder<String> timestamp,
GuestSesion guestSesion
) throws RegisterException {
guestSesion.setLogin(login);
timestamp.value = "";
guestSesion.setTimeStamp("");
guestSesion.setSchemaName(schemaName.trim());
guestSesion.setSchemaID(schemaID);
// try {
boolean versionControl = vc != 0;
if ((!Settings.projectVersion.equals(version)) && versionControl) {
logger.log(Level.INFO, messages.getString("versionNotFitInfo"), login);
throw new RegisterException(RegisterException.MessageCode.VERSION_MISMATCH);
}
int cnt = (int)(Math.random() * 1000 + 1000);
StringBuilder timestampBuilder = new StringBuilder(cnt);
for (int i=0; i<cnt; i++) {
timestampBuilder.append((char)(Math.random() * 90 + 32));
}
timestampBuilder.append(DateFormat.getInstance().format(new Date()));
timestamp.value = timestampBuilder.toString();
guestSesion.setTimeStamp(Settings.projectName + "1024" + Settings.serverName + timestamp.value);
// } catch (Exception e) {
// logger.log(Level.INFO, messages.getString("welcomeError"), login);
// logger.log(Level.SEVERE, "", e);
// return Settings.SQL_ERROR;
return 0;
}
public String getWebUserInfo(UserLogon ul) throws CarabiException {
return String.format("{\"login\":\"%s\", \"idCarabiUser\":\"%d\", \"idWebUser\":\"%s\"}",
ul.userLogin(),
ul.getId(),
getWebUserId(ul)
);
}
public int registerUser(
CarabiUser user,
String passwordTokenClient,
Properties connectionProperties,
String version,
int vc,
Holder<Integer> schemaID,
Holder<SoapUserInfo> info,
GuestSesion guestSesion
) throws CarabiException, RegisterException {
String login = user.getLogin();
try {
authorize = (AuthorizeBean) ctx.lookup("java:module/AuthorizeBean");
boolean versionControl = vc != 0;
if ((!Settings.projectVersion.equals(version)) && versionControl) {
logger.log(Level.INFO, messages.getString("versionNotFitInfo"), login);
throw new RegisterException(RegisterException.MessageCode.VERSION_MISMATCH);
}
logger.log(Level.INFO, messages.getString("registerStart"), login);
UserLogon userLogon = createUserLogon(guestSesion.getSchemaID(), guestSesion.getSchemaName(), user);
logger.log(Level.INFO, "passwordCipher: {0}", userLogon.getUser().getPassword());
logger.log(Level.INFO, "timestamp: {0}", guestSesion.getTimeStamp());
String passwordTokenServer = DigestUtils.md5Hex(userLogon.getPasswordCipher() + guestSesion.getTimeStamp());
logger.log(Level.INFO, "passwordTokenServer: {0}", passwordTokenServer);
logger.log(Level.INFO, "passwordTokenClient: {0}", passwordTokenClient);
// if (!passwordTokenClient.equalsIgnoreCase(passwordTokenServer)) {
// CarabiLogging.logError(messages.getString("registerRefusedDetailsPass"),
// new Object[]{login, "Oracle " + authorize.getSchema().getSysname(), passwordTokenServer, passwordTokenClient},
// authorize.getConnection(), true, Level.WARNING, null);
// authorize.closeConnection();
// throw new RegisterException(RegisterException.MessageCode.BAD_PASSWORD_ORACLE);
passwordTokenServer = DigestUtils.md5Hex(userLogon.getUser().getPassword() + guestSesion.getTimeStamp());
if (!passwordTokenClient.equalsIgnoreCase(passwordTokenServer)) {
throw new RegisterException(RegisterException.MessageCode.BAD_PASSWORD_DERBY);
}
userLogon.setGreyIpAddr(connectionProperties.getProperty("ipAddrGrey"));
userLogon.setWhiteIpAddr(connectionProperties.getProperty("ipAddrWhite"));
userLogon.setServerContext(connectionProperties.getProperty("serverContext"));
String token = authorize.authorizeUser(true);
SoapUserInfo soapUserInfo = new SoapUserInfo();//authorize.createSoapUserInfo();
soapUserInfo.token = token;
info.value = soapUserInfo;
schemaID.value = -1;//currentUser.getSchema().getId();
} catch (CarabiException e) {
if (!RegisterException.class.isInstance(e)) {
CarabiLogging.logError("GuestService.registerUser failed with Exception. ", null, null, false, Level.SEVERE, e);
}
throw e;
} catch (NamingException | SQLException e) {
CarabiLogging.logError("GuestService.registerUser failed with Exception. ", null, null, false, Level.SEVERE, e);
throw new CarabiException(e);
} catch (Exception e) {
CarabiLogging.logError("GuestService.registerUser failed with UNKNOWN Exception. ", null, null, false, Level.SEVERE, e);
throw new CarabiException(e);
} finally {
if (authorize != null) authorize.remove();
authorize = null;
}
return 0;
}
public int registerUserLight(
CarabiUser user,
String passwordCipherClient,
boolean requireSession,
Properties connectionProperties,
Holder<String> schemaName,
Holder<String> token
) throws CarabiException {
logger.log(Level.INFO,
"GuestService.registerUserLight called with params: user={0}, password={1}, "
+"requireSession={2}, schemaName={3}",
new Object[]{user.getLogin(), passwordCipherClient, requireSession, schemaName.value});
try {
String login = user.getLogin();
authorize = (AuthorizeBean) ctx.lookup("java:module/AuthorizeBean");
if (schemaName.value == null || schemaName.value.isEmpty()) {
final ConnectionSchema defaultSchema = user.getDefaultSchema();
if (defaultSchema == null || defaultSchema.getSysname() == null || defaultSchema.getSysname().isEmpty()) {
throw new RegisterException(RegisterException.MessageCode.NO_SCHEMA);
}
schemaName.value = defaultSchema.getSysname();
logger.log(Level.INFO, "User {0} got schema {1} as default", new Object[] {login, schemaName.value});
}
if (!user.getPassword().equalsIgnoreCase(passwordCipherClient)) {
CarabiLogging.logError(messages.getString("registerRefusedDetailsPass"),
new Object[]{login, "Apache Derby", user.getPassword(), passwordCipherClient},
null, false, Level.WARNING, null);
throw new RegisterException(RegisterException.MessageCode.BAD_PASSWORD_DERBY);
}
UserLogon logon = createUserLogon(-1, schemaName.value, user);
logon.setGreyIpAddr(connectionProperties.getProperty("ipAddrGrey"));
logon.setWhiteIpAddr(connectionProperties.getProperty("ipAddrWhite"));
logon.setServerContext(connectionProperties.getProperty("serverContext"));
logger.log(Level.INFO, "По имени схемы и логину ({0}, {1}) получен пользователь: {2}",
new Object[] {schemaName, login, String.valueOf(logon)});
if (!passwordCipherClient.equalsIgnoreCase(logon.getPasswordCipher())) {
CarabiLogging.logError(messages.getString("registerRefusedDetailsPass"),
new Object[]{login, "Oracle " + authorize.getSchema().getSysname(), logon.getPasswordCipher(), passwordCipherClient},
authorize.getConnection(), true, Level.SEVERE, null);
authorize.closeConnection();
throw new RegisterException(RegisterException.MessageCode.BAD_PASSWORD_ORACLE);
}
token.value = authorize.authorizeUser(requireSession);
logger.log(Level.INFO, "Пользователю выдан токен: {0}", token.value);
return logon.getId();
} catch (CarabiException ex) {
if (RegisterException.class.isInstance(ex)) {
throw ex;
}
CarabiLogging.logError("GuestService.registerUserLight failed with Exception. ", null, null, false, Level.SEVERE, ex);
throw ex;
} catch (Exception ex) {
CarabiLogging.logError("GuestService.registerUserLight failed with Exception. ", null, null, false, Level.SEVERE, ex);
throw new CarabiException(ex);
} finally {
if (authorize != null) authorize.remove();
authorize = null;
}
}
public int registerGuestUser(
CarabiUser user,
String passwordCipherClient,
Holder<String> token
) throws RegisterException, CarabiException {
logger.log(Level.INFO,
"GuestService.registerGuestUser called with params: user={0}, password={1}",
new Object[]{user.getLogin(), passwordCipherClient});
try {
String login = user.getLogin();
if (!user.getPassword().equalsIgnoreCase(passwordCipherClient)) {
CarabiLogging.logError(messages.getString("registerRefusedDetailsPass"),
new Object[]{login, "Apache Derby", user.getPassword(), passwordCipherClient},
null, false, Level.WARNING, null);
throw new RegisterException(RegisterException.MessageCode.BAD_PASSWORD_DERBY);
}
UserLogon logon = new UserLogon();
logon.setUser(user);
logon.setDisplay(user.getFirstname() + " " + user.getMiddlename() + " " + user.getLastname());
logon.setAppServer(Settings.getCurrentServer());
logon.setRequireSession(false);
logon.updateLastActive();
logon = uc.addUser(logon);
token.value = logon.getToken();
logger.log(Level.INFO, "Пользователю выдан токен: {0}", token.value);
return logon.getId();
} catch (CarabiException ex) {
CarabiLogging.logError("GuestService.registerUserLight failed with Exception. ", null, null, false, Level.SEVERE, ex);
throw ex;
} catch (Exception ex) {
CarabiLogging.logError("GuestService.registerUserLight failed with Exception. ", null, null, false, Level.SEVERE, ex);
} finally {
if (authorize != null) authorize.remove();
authorize = null;
}
return 0;
}
private UserLogon createUserLogon(int schemaID, String schemaName, CarabiUser user) throws CarabiException, NamingException, SQLException {
// logger.info("try to connect");
//authorize.connectToDatabase(schemaID, schemaName, user);
authorize.setCurrentUser(user);
// logger.info("connected to Oracle");
boolean userExists = authorize.searchCurrentUser();
if (!userExists) {
logger.log(Level.INFO, messages.getString("registerRefused"), user.getLogin());
CarabiLogging.logError(messages.getString("registerRefusedDetailsBase"),
new Object[]{user.getLogin(), "Oracle " + authorize.getSchema().getSysname()},
authorize.getConnection(), true, Level.WARNING, null);
// authorize.closeConnection();
throw new RegisterException(RegisterException.MessageCode.NO_LOGIN_ORACLE);
}
return authorize.createUserLogon();
}
public CarabiUser searchUserInDerby(String login) throws RegisterException {
CarabiUser user;
try {
TypedQuery<CarabiUser> activeUser = em.createNamedQuery("getUserInfo", CarabiUser.class);
activeUser.setParameter("login", login);
user = activeUser.getSingleResult();
} catch (NoResultException ex) {
CarabiLogging.logError(messages.getString("registerRefusedDetailsBase"),
new Object[]{login, "Apache Derby"},
null, false, Level.INFO, null);
throw new RegisterException(RegisterException.MessageCode.NO_LOGIN_DERBY);
}
return user;
}
public CarabiUser checkCurrentServer(CarabiUser user) {
final CarabiAppServer currentServer = Settings.getCurrentServer();
TypedQuery<UserServerEnter> getUserServerEnter = em.createNamedQuery("getUserServerEnter", UserServerEnter.class);
getUserServerEnter.setParameter("user", user);
getUserServerEnter.setParameter("server", currentServer);
List<UserServerEnter> userServerEnterList = getUserServerEnter.getResultList();
UserServerEnter userServerEnter;
if (userServerEnterList.isEmpty()) {
userServerEnter = new UserServerEnter();
userServerEnter.setUser(user);
userServerEnter.setServer(currentServer);
} else {
userServerEnter = userServerEnterList.get(0);
}
userServerEnter.increment();
em.merge(userServerEnter);
if (user.getMainServer() == null) {
user.setMainServer(currentServer);
user = em.merge(user);
}
em.flush();
return user;
}
}
|
package rxbroadcast;
import rxbroadcast.time.Clock;
import rxbroadcast.time.LamportClock;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Consumer;
public final class SingleSourceFifoOrder<T> implements BroadcastOrder<Timestamped<T>, T> {
public enum SingleSourceFifoOrderQueueOption {
DROP,
QUEUE,
}
@SuppressWarnings("WeakerAccess")
public static final SingleSourceFifoOrderQueueOption DROP_LATE = SingleSourceFifoOrderQueueOption.DROP;
private final Clock clock = new LamportClock();
private final Map<Sender, SortedSet<Timestamped<T>>> pendingSets;
private final Map<Sender, Long> expectedTimestamps;
private final boolean dropLateMessages;
public SingleSourceFifoOrder() {
this(SingleSourceFifoOrderQueueOption.QUEUE);
}
@SuppressWarnings("WeakerAccess")
public SingleSourceFifoOrder(final SingleSourceFifoOrderQueueOption queueOpt) {
this.pendingSets = new HashMap<>();
this.expectedTimestamps = new HashMap<>();
this.dropLateMessages = queueOpt == SingleSourceFifoOrderQueueOption.DROP;
}
@Override
public Timestamped<T> prepare(final T value) {
return clock.tick(time -> new Timestamped<>(time, value));
}
@Override
public void receive(final Sender sender, final Consumer<T> consumer, final Timestamped<T> value) {
expectedTimestamps.putIfAbsent(sender, 1L);
if (dropLateMessages) {
if (Long.compareUnsigned(value.timestamp, expectedTimestamps.get(sender)) >= 0) {
consumer.accept(value.value);
expectedTimestamps.compute(sender, (k, v) -> value.timestamp + 1);
}
return;
}
final SortedSet<Timestamped<T>> pendingSet = pendingSets.computeIfAbsent(sender, k -> new TreeSet<>());
pendingSet.add(value);
final Iterator<Timestamped<T>> iterator = pendingSet.iterator();
while (iterator.hasNext()) {
final Timestamped<T> tv = iterator.next();
if (tv.timestamp < expectedTimestamps.get(sender)) {
iterator.remove();
continue;
}
if (tv.timestamp > expectedTimestamps.get(sender)) {
break;
}
consumer.accept(tv.value);
expectedTimestamps.compute(sender, (k, v) -> tv.timestamp + 1);
iterator.remove();
}
}
int queueSize() {
return pendingSets.values().stream().mapToInt(SortedSet::size).sum();
}
}
|
package seedu.taskitty.model;
import javafx.beans.value.ObservableValue;
import javafx.collections.transformation.FilteredList;
import seedu.taskitty.commons.core.ComponentManager;
import seedu.taskitty.commons.core.LogsCenter;
import seedu.taskitty.commons.core.UnmodifiableObservableList;
import seedu.taskitty.commons.events.model.TaskManagerChangedEvent;
import seedu.taskitty.commons.exceptions.NoPreviousValidCommandException;
import seedu.taskitty.commons.exceptions.NoRecentUndoCommandException;
import seedu.taskitty.commons.util.DateUtil;
import seedu.taskitty.commons.util.StringUtil;
import seedu.taskitty.logic.commands.AddCommand;
import seedu.taskitty.logic.commands.ClearCommand;
import seedu.taskitty.logic.commands.DeleteCommand;
import seedu.taskitty.logic.commands.DoneCommand;
import seedu.taskitty.logic.commands.EditCommand;
import seedu.taskitty.model.tag.Tag;
import seedu.taskitty.model.task.ReadOnlyTask;
import seedu.taskitty.model.task.Task;
import seedu.taskitty.model.task.UniqueTaskList;
import seedu.taskitty.model.task.UniqueTaskList.DuplicateMarkAsDoneException;
import seedu.taskitty.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.taskitty.model.task.UniqueTaskList.TaskNotFoundException;
import java.time.LocalDate;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
* Represents the in-memory model of the task manager data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final TaskManager taskManager;
private final FilteredList<Task> allTasks;
private FilteredList<Task> filteredTodos;
private FilteredList<Task> filteredDeadlines;
private FilteredList<Task> filteredEvents;
private ObservableValue<String> date;
private final CommandHistoryManager undoHistory;
private final CommandHistoryManager redoHistory;
/**
* Initializes a ModelManager with the given TaskManager
* TaskManager and its variables should not be null
*/
public ModelManager(TaskManager src, UserPrefs userPrefs) {
super();
assert src != null;
assert userPrefs != null;
logger.fine("Initializing with task manager: " + src + " and user prefs " + userPrefs);
taskManager = new TaskManager(src);
allTasks = new FilteredList<Task>(taskManager.getAllTasks());
filteredTodos = new FilteredList<Task>(taskManager.getFilteredTodos());
filteredDeadlines = new FilteredList<Task>(taskManager.getFilteredDeadlines());
filteredEvents = new FilteredList<Task>(taskManager.getFilteredEvents());
undoHistory = new CommandHistoryManager();
redoHistory = new CommandHistoryManager();
taskManager.sortList();
}
public ModelManager() {
this(new TaskManager(), new UserPrefs());
}
public ModelManager(ReadOnlyTaskManager initialData, UserPrefs userPrefs) {
taskManager = new TaskManager(initialData);
allTasks = new FilteredList<Task>(taskManager.getAllTasks());
filteredTodos = new FilteredList<Task>(taskManager.getFilteredTodos());
filteredDeadlines = new FilteredList<Task>(taskManager.getFilteredDeadlines());
filteredEvents = new FilteredList<Task>(taskManager.getFilteredEvents());
undoHistory = new CommandHistoryManager();
redoHistory = new CommandHistoryManager();
taskManager.sortList();
}
@Override
public void resetData(ReadOnlyTaskManager newData) {
taskManager.resetData(newData);
indicateTaskManagerChanged();
}
@Override
public ReadOnlyTaskManager getTaskManager() {
return taskManager;
}
/** Raises an event to indicate the model has changed */
private void indicateTaskManagerChanged() {
raise(new TaskManagerChangedEvent(taskManager));
}
//@@author A0139052L
@Override
public synchronized void deleteTasks(List<ReadOnlyTask> taskList) throws TaskNotFoundException {
for (ReadOnlyTask targetTask: taskList) {
taskManager.removeTask(targetTask);
}
indicateTaskManagerChanged();
}
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
taskManager.addTask(task);
indicateTaskManagerChanged();
}
//@@author A0130853L
@Override
public synchronized void markTasksAsDone(List<ReadOnlyTask> taskList) throws UniqueTaskList.TaskNotFoundException, DuplicateMarkAsDoneException{
for (ReadOnlyTask targetTask: taskList) {
taskManager.markTaskAsDoneTask(targetTask);
}
indicateTaskManagerChanged();
}
//@@author A0135793W
@Override
public synchronized void editTask(ReadOnlyTask target, Task task) throws UniqueTaskList.TaskNotFoundException, UniqueTaskList.DuplicateTaskException {
taskManager.addTask(task);
indicateTaskManagerChanged();
taskManager.removeTask(target);
indicateTaskManagerChanged();
}
//@@author A0139052L
@Override
public synchronized void storeAddCommandInfo(ReadOnlyTask addedTask, String commandText) {
undoHistory.storeCommandWord(AddCommand.COMMAND_WORD);
undoHistory.storeTask(addedTask);
undoHistory.storeCommandText(AddCommand.COMMAND_WORD + commandText);
redoHistory.clear();
}
@Override
public synchronized void storeEditCommandInfo(ReadOnlyTask taskBeforeEdit, ReadOnlyTask taskAfterEdit, String commandText) {
undoHistory.storeCommandWord(EditCommand.COMMAND_WORD);
undoHistory.storeTask(taskAfterEdit);
undoHistory.storeTask(taskBeforeEdit);
undoHistory.storeCommandText(EditCommand.COMMAND_WORD + commandText);
redoHistory.clear();
}
@Override
public synchronized void storeDeleteCommandInfo(List<ReadOnlyTask> deletedTasks, String commandText) {
undoHistory.storeCommandWord(DeleteCommand.COMMAND_WORD);
undoHistory.storeListOfTasks(deletedTasks);
undoHistory.storeCommandText(DeleteCommand.COMMAND_WORD + commandText);
redoHistory.clear();
}
@Override
public synchronized void storeDoneCommandInfo(List<ReadOnlyTask> markedTasks, String commandText) {
undoHistory.storeCommandWord(DoneCommand.COMMAND_WORD);
undoHistory.storeListOfTasks(markedTasks);
undoHistory.storeCommandText(DoneCommand.COMMAND_WORD + commandText);
redoHistory.clear();
}
@Override
public synchronized void storeClearCommandInfo() {
undoHistory.storeCommandWord(ClearCommand.COMMAND_WORD);
undoHistory.storeTaskManager(new TaskManager(taskManager));
undoHistory.storeCommandText(ClearCommand.COMMAND_WORD);
redoHistory.clear();
}
@Override
public synchronized String undo() throws NoPreviousValidCommandException {
if (!undoHistory.hasPreviousValidCommand()) {
throw new NoPreviousValidCommandException(null);
}
return revertBackPreviousState(undoHistory, redoHistory, false);
}
@Override
public synchronized String redo() throws NoRecentUndoCommandException {
if (!redoHistory.hasPreviousValidCommand()) {
throw new NoRecentUndoCommandException(null);
}
return revertBackPreviousState(redoHistory, undoHistory, true);
}
//@@author
@Override
public UnmodifiableObservableList<ReadOnlyTask> getTaskList() {
return new UnmodifiableObservableList<>(allTasks);
}
//@@author A0139930B
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTodoList() {
return new UnmodifiableObservableList<>(filteredTodos);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredDeadlineList() {
return new UnmodifiableObservableList<>(filteredDeadlines);
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredEventList() {
return new UnmodifiableObservableList<>(filteredEvents);
}
//@@author
@Override
public void updateFilteredListToShowAll() {
allTasks.setPredicate(null);
filteredTodos.setPredicate(null);
filteredDeadlines.setPredicate(null);
filteredEvents.setPredicate(null);
}
@Override
public void updateFilteredTaskList(Set<String> keywords){
updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)));
}
//@@author A0130853L
@Override
public void updateFilteredDoneList() {
updateFilteredTaskList(new PredicateExpression(p -> p.getIsDone() == true));
}
/**
* Updates list to show uncompleted and upcoming tasks only.
*/
@Override
public void updateToDefaultList() {
allTasks.setPredicate(p -> !p.getIsDone() && (p.isTodo() || p.isDeadline() || isEventAndIsNotBeforeToday(p)));
filteredTodos.setPredicate(p -> !p.getIsDone());
filteredDeadlines.setPredicate(p -> !p.getIsDone());
filteredEvents.setPredicate(p -> !p.getIsDone() && isEventAndIsNotBeforeToday(p));
}
/**
* Updates list to show deadlines on and before the specified date and events within the date.
*/
@Override
public void updateFilteredDateTaskList(LocalDate date) {
allTasks.setPredicate(p -> isDateRelevantDeadlinesAndEvents(p, date));
filteredTodos.setPredicate(null);
filteredDeadlines.setPredicate(p -> isDeadlineAndIsNotAfterDate(p, date));
filteredEvents.setPredicate(p -> isEventAndDateIsWithinEventPeriod(p, date));
}
//@@author
private void updateFilteredTaskList(Expression expression) {
allTasks.setPredicate(expression::satisfies);
filteredTodos.setPredicate(expression::satisfies);
filteredDeadlines.setPredicate(expression::satisfies);
filteredEvents.setPredicate(expression::satisfies);
}
interface Expression {
boolean satisfies(ReadOnlyTask person);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask person) {
return qualifier.run(person);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask person);
String toString();
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
//@@author A0130853L
@Override
public boolean run(ReadOnlyTask task) {
return nameKeyWords.stream()
.filter(keyword -> containsByType(task, keyword))
.findAny()
.isPresent();
}
//@@author A0139930B
/**
* Check if a task contains the given keyword.
* Tags will be used to compare if keyword contains TAG_PREFIX
* Returns true if keyword is found in task
*
* @param task to be checked
* @param keyword to look for in task
*/
private boolean containsByType(ReadOnlyTask task, String keyword) {
assert task != null;
assert keyword != null && !keyword.isEmpty();
String toCompare = task.getName().fullName;
if (keyword.contains(Tag.TAG_PREFIX)) {
toCompare = task.tagsString();
}
return StringUtil.containsIgnoreCase(toCompare, keyword);
}
//@@author
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
//@@author A0130853L
/**
* Evaluates if the task is a deadline and is not after the specified date.
* @param task
* @param date
* @return the evaluated boolean expression
*/
private boolean isDeadlineAndIsNotAfterDate(Task task, LocalDate date) {
return task.isDeadline() && !task.getPeriod().getEndDate().getDate().isAfter(date);
}
/**
* Evaluates if the task is an event and the specified date is within the event period.
* @param a valid task in the task manager
* @param the date that the user requested to search for
* @return the evaluated boolean expression
*/
private boolean isEventAndDateIsWithinEventPeriod(Task task, LocalDate date) {
boolean relEndDate = isEventAndIsNotBeforeDate(task, date);
boolean relStartDate = isEventAndIsNotAfterDate(task, date);
return relEndDate && relStartDate;
}
/**
* A helper method to shorten the evaluated boolean expression that is otherwise longer.
* Evaluates if the task is an event and event is from `date` onwards.
* @param a valid task in the task manager
*@return the evaluated boolean expression
*/
private boolean isEventAndIsNotBeforeDate(Task task, LocalDate date) {
return task.isEvent() && !(task.getPeriod().getEndDate().getDate().isBefore(date));
}
/**
* A helper method to shorten the evaluated boolean expression that is otherwise longer.
* Evaluates if the task is an event and event is either on `date` or before it.
* @param a valid task in the task manager
*@return the evaluated boolean expression
*/
private boolean isEventAndIsNotAfterDate(Task task, LocalDate date) {
return task.isEvent() && !(task.getPeriod().getStartDate().getDate().isAfter(date));
}
/**
* Evaluates if the task is an event and event is from today onwards.
* @param a valid task in the task manager
*@return the evaluated boolean expression
*/
private boolean isEventAndIsNotBeforeToday(Task task) {
LocalDate today = DateUtil.createCurrentDate();
return isEventAndIsNotBeforeDate(task, today);
}
/**
* Abstracted boolean expression method for filtering according to the function `view date`.
* @param a valid task in the task manager
* @param the date that the user requested to search for
* @return the combined boolean expression from the 3 respective task-derived expressions.
*/
private boolean isDateRelevantDeadlinesAndEvents(Task p, LocalDate date) {
boolean todos = p.isTodo();
boolean relDeadlines = isDeadlineAndIsNotAfterDate(p, date);
boolean relEvents = isEventAndDateIsWithinEventPeriod(p, date);
return todos || relDeadlines || relEvents;
}
//@@author A0139052L
/**
* Reverts back to the previous state by undoing/redoing the previous action
* @param toGetInfo the storage in which to get the info from
* @param toStoreInfo the storage in which to store the info into
* @param isRedo check if it is undo/redo calling this method
* @return the commandText string for result message in Undo/Redo Command
*/
private String revertBackPreviousState(CommandHistoryManager toGetInfo, CommandHistoryManager toStoreInfo, boolean isRedo) {
String commandWord = toGetInfo.getCommandWord();
toStoreInfo.storeCommandWord(commandWord);
try {
switch(commandWord) {
case AddCommand.COMMAND_WORD:
revertAddCommand(toGetInfo, toStoreInfo, isRedo);
break;
case DeleteCommand.COMMAND_WORD:
revertDeleteCommand(toGetInfo, toStoreInfo, isRedo);
break;
case EditCommand.COMMAND_WORD:
revertEditCommand(toGetInfo, toStoreInfo, isRedo);
break;
case ClearCommand.COMMAND_WORD:
revertClearCommand(toGetInfo, toStoreInfo, isRedo);
break;
case DoneCommand.COMMAND_WORD:
revertDoneCommand(toGetInfo, toStoreInfo, isRedo);
break;
default:
assert false: "Should not have an invalid Command Word";
break;
}
} catch (Exception e) {
assert false: "Should not be unable to undo/redo previous command action";
}
String commandText = toGetInfo.getCommandText();
toStoreInfo.storeCommandText(commandText);
indicateTaskManagerChanged();
return commandText;
}
/**
* Reverts an AddCommand depending on whether is redo/undo calling it
*/
private void revertAddCommand(CommandHistoryManager toGetInfo, CommandHistoryManager toStoreInfo, boolean isRedo)
throws DuplicateTaskException, TaskNotFoundException {
ReadOnlyTask taskAdded = toGetInfo.getTask();
if (isRedo) {
taskManager.addTask((Task) taskAdded);
} else {
taskManager.removeTask(taskAdded);
}
toStoreInfo.storeTask(taskAdded);
}
/**
* Reverts a DeleteCommand depending on whether is redo/undo calling it
*/
private void revertDeleteCommand(CommandHistoryManager toGetInfo, CommandHistoryManager toStoreInfo, boolean isRedo)
throws TaskNotFoundException, DuplicateTaskException {
List<ReadOnlyTask> listOfDeletedTasks = toGetInfo.getListOfTasks();
toStoreInfo.storeListOfTasks(listOfDeletedTasks);
if (isRedo) {
for (ReadOnlyTask taskDeleted: listOfDeletedTasks) {
taskManager.removeTask(taskDeleted);
}
} else {
for (ReadOnlyTask taskDeleted: listOfDeletedTasks) {
taskManager.addTask((Task) taskDeleted);
}
}
}
/**
* Reverts an EditCommand depending on whether is redo/undo calling it
*/
private void revertEditCommand(CommandHistoryManager toGetInfo, CommandHistoryManager toStoreInfo, boolean isRedo)
throws DuplicateTaskException, TaskNotFoundException {
ReadOnlyTask taskBeforeEdit = toGetInfo.getTask();
ReadOnlyTask taskAfterEdit = toGetInfo.getTask();
if (isRedo) {
taskManager.addTask((Task) taskAfterEdit);
taskManager.removeTask(taskBeforeEdit);
} else {
taskManager.addTask((Task) taskBeforeEdit);
taskManager.removeTask(taskAfterEdit);
}
toStoreInfo.storeTask(taskAfterEdit);
toStoreInfo.storeTask(taskBeforeEdit);
}
/**
* Reverts a ClearCommand depending on whether is redo/undo calling it
*/
private void revertClearCommand(CommandHistoryManager toGetInfo, CommandHistoryManager toStoreInfo,
boolean isRedo) {
ReadOnlyTaskManager previousTaskManager = toGetInfo.getTaskManager();
if (isRedo) {
resetData(TaskManager.getEmptyTaskManager());
} else {
resetData(previousTaskManager);
}
toStoreInfo.storeTaskManager(previousTaskManager);
}
/**
* Reverts a DoneCommand depending on whether is redo/undo calling it
*/
private void revertDoneCommand(CommandHistoryManager toGetInfo, CommandHistoryManager toStoreInfo, boolean isRedo)
throws DuplicateMarkAsDoneException, TaskNotFoundException {
List<ReadOnlyTask> listOfTasksMarked = toGetInfo.getListOfTasks();
toStoreInfo.storeListOfTasks(listOfTasksMarked);
if (isRedo) {
for (ReadOnlyTask taskToRevertMark: listOfTasksMarked) {
taskManager.markTaskAsDoneTask(taskToRevertMark);
}
} else {
for (ReadOnlyTask taskToRevertMark: listOfTasksMarked) {
taskManager.unMarkTaskAsDoneTask(taskToRevertMark);
}
}
}
}
//@@author A0139052L unused
// swap over to different undo function
// * returns true is there is a previous valid command input by user
// * and false otherwise
// private boolean hasPreviousValidCommand() {
// return !historyCommands.isEmpty();
// /**
// * returns the Task Manager from the previous state
// */
// private ReadOnlyTaskManager getPreviousTaskManager() {
// return historyTaskManagers.pop();
// /**
// * returns the Predicate from the previous state
// */
// private Predicate getPreviousPredicate() {
// return historyPredicates.pop();
// /**
// * returns the previous valid command input by the user
// */
// private String getPreviousValidCommand() {
// return historyCommands.pop();
// public synchronized void saveState(String command) {
// historyTaskManagers.push(new TaskManager(taskManager));
// historyCommands.push(command);
// historyPredicates.push(filteredTodos.getPredicate());
// public synchronized void removeUnchangedState() {
// historyTaskManagers.pop();
// historyCommands.pop();
// historyPredicates.pop();
// public synchronized String undo() throws NoPreviousValidCommandException {
// if (!hasPreviousValidCommand()) {
// throw new NoPreviousValidCommandException(null);
// assert !historyPredicates.isEmpty() && !historyTaskManagers.isEmpty();
// resetData(getPreviousTaskManager());
// updateFilteredTaskList(getPreviousPredicate());
// return getPreviousValidCommand();
|
package sssj.index;
import static sssj.base.Commons.*;
import it.unimi.dsi.fastutil.BidirectionalIterator;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap.Entry;
import it.unimi.dsi.fastutil.ints.Int2ReferenceMap;
import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.longs.Long2DoubleMap;
import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.util.FastMath;
import sssj.base.CircularBuffer;
import sssj.base.StreamingMaxVector;
import sssj.base.StreamingResiduals;
import sssj.base.Vector;
import sssj.index.L2APIndex.L2APPostingEntry;
import com.google.common.primitives.Doubles;
public class StreamingPureL2APIndex implements Index {
private final Int2ReferenceMap<StreamingL2APPostingList> idx = new Int2ReferenceOpenHashMap<>();
private final StreamingResiduals resList = new StreamingResiduals();
private final Long2DoubleOpenHashMap ps = new Long2DoubleOpenHashMap();
private final Long2DoubleOpenHashMap accumulator = new Long2DoubleOpenHashMap();
private final Long2DoubleOpenHashMap matches = new Long2DoubleOpenHashMap();
private final double theta;
private final double lambda;
private final double tau;
private int size;
private int maxLength;
public StreamingPureL2APIndex(double theta, double lambda) {
this.theta = theta;
this.lambda = lambda;
this.tau = tau(theta, lambda);
System.out.println("Tau = " + tau);
precomputeFFTable(lambda, (int) Math.ceil(tau));
}
@Override
public Map<Long, Double> queryWith(final Vector v, final boolean addToIndex) {
accumulator.clear();
matches.clear();
/* candidate generation */
generateCandidates(v);
/* candidate verification */
verifyCandidates(v);
/* index building */
if (addToIndex) {
Vector residual = addToIndex(v);
resList.add(residual);
}
return matches;
}
private final void generateCandidates(final Vector v) {
double l2remscore = 1, // rs4
rst = 1, squaredQueryPrefixMagnitude = 1;
boolean keepFiltering = true;
for (BidirectionalIterator<Entry> vecIter = v.int2DoubleEntrySet().fastIterator(v.int2DoubleEntrySet().last()); vecIter
.hasPrevious();) { // iterate over v in reverse order
final Entry e = vecIter.previous();
final int dimension = e.getIntKey();
final double queryWeight = e.getDoubleValue();
// forgetting factor applied directly to the l2prefix bound
final double rscore = l2remscore;
squaredQueryPrefixMagnitude -= queryWeight * queryWeight;
StreamingL2APPostingList list;
if ((list = idx.get(dimension)) != null) {
// TODO possibly size filtering: remove entries from the posting list with |y| < minsize (need to save size in the posting list)
for (Iterator<L2APPostingEntry> listIter = list.iterator(); listIter.hasNext();) {
final L2APPostingEntry pe = listIter.next();
final long targetID = pe.getID();
final int oldLength = list.size();
// time filtering
boolean filtered = false;
final long deltaT = v.timestamp() - targetID;
if (Doubles.compare(deltaT, tau) > 0 && keepFiltering) {
listIter.remove();
size
filtered = true;
continue;
}
keepFiltering &= filtered; // keep filtering only if we have just filtered
if (oldLength >= maxLength) // heuristic to efficiently maintain the max length
maxLength = list.size();
final double ff = forgettingFactor(lambda, deltaT);
if (accumulator.containsKey(targetID) || Double.compare(rscore, theta) >= 0) {
final double targetWeight = pe.getWeight();
final double additionalSimilarity = queryWeight * targetWeight; // x_j * y_j
accumulator.addTo(targetID, additionalSimilarity); // A[y] += x_j * y_j
final double l2bound = accumulator.get(targetID) + FastMath.sqrt(squaredQueryPrefixMagnitude)
* pe.magnitude; // A[y] + ||x'_j|| * ||y'_j||
// forgetting factor applied directly to the l2sum bound
if (Double.compare(l2bound * ff, theta) < 0)
accumulator.remove(targetID); // prune this candidate (early verification)
}
}
rst -= queryWeight * queryWeight; // rs_t -= x_j^2
l2remscore = FastMath.sqrt(rst); // rs_4 = sqrt(rs_t)
}
}
}
private final void verifyCandidates(final Vector v) {
for (Long2DoubleMap.Entry e : accumulator.long2DoubleEntrySet()) {
// TODO possibly use size filtering (sz_3)
final long candidateID = e.getLongKey();
final long deltaT = v.timestamp() - candidateID;
if (deltaT > tau) // time pruning
continue;
final double ff = forgettingFactor(lambda, deltaT);
if (Double.compare((e.getDoubleValue() + ps.get(candidateID)) * ff, theta) < 0) // A[y] = dot(x, y")
continue; // l2 pruning
final long lowWatermark = (long) Math.floor(v.timestamp() - tau);
final Vector residual = resList.getAndPrune(candidateID, lowWatermark); // TODO prune also ps?
assert (residual != null) : "Residual not found. TS=" + v.timestamp() + " candidateID=" + candidateID;
final double dpscore = e.getDoubleValue()
+ Math.min(v.maxValue() * residual.size(), residual.maxValue() * v.size());
if (Double.compare(dpscore * ff, theta) < 0)
continue; // dpscore, eq. (5)
double score = e.getDoubleValue() + Vector.similarity(v, residual); // dot(x, y) = A[y] + dot(x, y')
score *= ff; // apply forgetting factor
if (Double.compare(score, theta) >= 0) // final check
matches.put(candidateID, score);
}
}
private final Vector addToIndex(final Vector v) {
double bt = 0, b3 = 0, pscore = 0;
boolean psSaved = false;
final Vector residual = new Vector(v.timestamp());
// upper bound on the forgetting factor w.r.t. the maximum vector
// TODO can be tightened with a deltaT per dimension
// final long maxDeltaT = v.timestamp() - maxVector.timestamp();
// final double maxff = forgettingFactor(lambda, maxDeltaT);
// FIXME maxDeltaT can be larger than tau. How do we use it?
for (Entry e : v.int2DoubleEntrySet()) {
final int dimension = e.getIntKey();
final double weight = e.getDoubleValue();
pscore = b3;
bt += weight * weight;
b3 = FastMath.sqrt(bt);
// forgetting factor applied directly bounds
if (Double.compare(b3, theta) >= 0) { // bound larger than threshold, start indexing
if (!psSaved) {
ps.put(v.timestamp(), pscore);
psSaved = true;
}
StreamingL2APPostingList list;
if ((list = idx.get(dimension)) == null) {
list = new StreamingL2APPostingList();
idx.put(dimension, list);
}
list.add(v.timestamp(), weight, b3);
size++;
maxLength = Math.max(list.size(), maxLength);
} else {
residual.put(dimension, weight);
}
}
return residual;
}
@Override
public int size() {
return size;
}
@Override
public int maxLength() {
return maxLength;
}
@Override
public String toString() {
return "StreamingL2APIndex [idx=" + idx + ", resList=" + resList + ", ps=" + ps + "]";
}
public static class StreamingL2APPostingList implements Iterable<L2APPostingEntry> {
private final CircularBuffer ids = new CircularBuffer(); // longs
private final CircularBuffer weights = new CircularBuffer(); // doubles
private final CircularBuffer magnitudes = new CircularBuffer(); // doubles
public void add(long vectorID, double weight, double magnitude) {
ids.pushLong(vectorID);
weights.pushDouble(weight);
magnitudes.pushDouble(magnitude);
}
public int size() {
return ids.size();
}
@Override
public String toString() {
return "[ids=" + ids + ", weights=" + weights + ", magnitudes=" + magnitudes + "]";
}
@Override
public Iterator<L2APPostingEntry> iterator() {
return new Iterator<L2APPostingEntry>() {
private final L2APPostingEntry entry = new L2APPostingEntry();
private int i = 0;
@Override
public boolean hasNext() {
return i < ids.size();
}
@Override
public L2APPostingEntry next() {
entry.setID(ids.peekLong(i));
entry.setWeight(weights.peekDouble(i));
entry.setMagnitude(magnitudes.peekDouble(i));
i++;
return entry;
}
@Override
public void remove() {
i
assert (i == 0); // removal always happens at the head
ids.popLong();
weights.popDouble();
magnitudes.popDouble();
}
};
}
}
}
|
package thredds.server.sos.util;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
public class TimeUtils
{
// time rules
// twice
/**
* <p>A {@link Comparator} that compares {@link DateTime} objects based only
* on their millisecond instant values. This can be used for
* {@link Collections#sort(java.util.List, java.util.Comparator) sorting} or
* {@link Collections#binarySearch(java.util.List, java.lang.Object,
* java.util.Comparator) searching} {@link List}s of {@link DateTime} objects.</p>
* <p>The ordering defined by this Comparator is <i>inconsistent with equals</i>
* because it ignores the Chronology of the DateTime instants.</p>
* <p><i>(Note: The DateTime object inherits from Comparable, not
* Comparable<DateTime>, so we can't use the methods in Collections
* directly. However we can reuse the {@link DateTime#compareTo(java.lang.Object)}
* method.)</i></p>
*/
public static final Comparator<DateTime> DATE_TIME_COMPARATOR =
new Comparator<DateTime>()
{
@Override
public int compare(DateTime dt1, DateTime dt2) {
return dt1.compareTo(dt2);
}
};
/**
* Searches the given list of timesteps for the nearest date-time of the
* specified date-time using the binary search algorithm.
* Matches are found based only upon the millisecond instant of the target
* DateTime, not its Chronology.
* @param target The timestep to search for.
* @return the index of the search key, if it is contained in the list;
* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
* <i>insertion point</i> is defined as the point at which the
* key would be inserted into the list: the index of the first
* element greater than the key, or <tt>list.size()</tt> if all
* elements in the list are less than the specified key. Note
* that this guarantees that the return value will be >= 0 if
* and only if the key is found. If this Layer does not have a time
* axis this method will return -1.
*/
public static int findNearestTimeIndex(List<DateTime> dtList, DateTime target)
{
int index = Collections.binarySearch(dtList, target, DATE_TIME_COMPARATOR);
if (index < 0)
{
// No exact match, but we have the insertion point, i.e. the index of
// the first element that is greater than the target value
int insertionPoint = -(index + 1);
// Deal with the extremes
if (insertionPoint == 0) {
index = 0;
} else if (insertionPoint == dtList.size()) {
index = dtList.size() - 1;
} else {
// We need to work out which index is closer: insertionPoint or
// (insertionPoint - 1)
long mils = DateTimeUtils.getInstantMillis(target);
long d1 = Math.abs(mils - DateTimeUtils.getInstantMillis(dtList.get(insertionPoint)));
long d2 = Math.abs(mils - DateTimeUtils.getInstantMillis(dtList.get(insertionPoint - 1)));
if (d1 < d2) index = insertionPoint;
else index = insertionPoint - 1;
}
}
return index;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.