answer
stringlengths 17
10.2M
|
|---|
package lesson5;
public class Square {
public int m = 0;
public int[][] arr;
public void fillArray () {
for ( int i = 0; i < arr.length; i++) {
for ( int j = 0; j < arr.length; j++) {
arr[i][j] = j;
}
}
}
public void output(int[][] arr) {
for ( int i = 0; i < arr.length; i++) {
for ( int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
public void expand () {
int[][] pilot = new int[m][m];
for (int i = 0; i < arr.length; i++) {
for (int j = 0, p = arr.length - 1; j < arr.length; j++, p
pilot[i][p] = arr[j][i];
}
}
arr = pilot;
}
public Square(int m) {
this.m = m;
arr = new int[m][m];
}
public static void main(String[] args) {
Square square = new Square(Integer.parseInt(args[0]));
square.fillArray();
square.output(square.arr);
square.expand();
square.output(square.arr);
}
}
|
package org.slc.sli.api.security.resolve;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slc.sli.api.init.RoleInitializer;
import org.slc.sli.api.security.enums.Right;
import org.slc.sli.api.security.resolve.impl.DefaultRolesToRightsResolver;
import org.slc.sli.api.security.roles.RoleBuilder;
import org.slc.sli.api.security.roles.RoleRightAccess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Verifies that {@link DefaultRolesToRightsResolver} filters out SLI Admins properly if
* not coming from a valid admin realm.
*
* @author pwolf
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext-test.xml" })
@DirtiesContext
public class SliAdminRoleResolveTest {
@Autowired
private DefaultRolesToRightsResolver resolver;
private static final String ADMIN_REALM_NAME = "dc=adminrealm,dc=org";
private static final String NON_ADMIN_REALM_NAME = "dc=sea,dc=org";
private List<String> rolesContainingAdmin = null;
private List<String> rolesNotContainingAdmin = null;
@Before
public void setUp() throws Exception {
SliAdminValidator validator = mock(SliAdminValidator.class);
resolver.setSliAdminValidator(validator);
when(validator.isSliAdminRealm(ADMIN_REALM_NAME)).thenReturn(true);
when(validator.isSliAdminRealm("")).thenReturn(false);
RoleRightAccess rra = mock(RoleRightAccess.class);
//Define educator per RoleInitializer
when(rra.getDefaultRole(RoleInitializer.EDUCATOR)).thenReturn(
RoleBuilder.makeRole(RoleInitializer.EDUCATOR).addRights(new Right[] { Right.AGGREGATE_READ, Right.READ_GENERAL })
.build());
//Define sli admin per RoleInitializer
when(rra.getDefaultRole(RoleInitializer.SLI_ADMINISTRATOR)).thenReturn(
RoleBuilder.makeRole(RoleInitializer.SLI_ADMINISTRATOR).addRights(new Right[] { Right.READ_ROLES }).build());
resolver.setRoleRightAccess(rra);
rolesContainingAdmin = new ArrayList<String>();
rolesContainingAdmin.add(RoleInitializer.EDUCATOR);
rolesContainingAdmin.add(RoleInitializer.SLI_ADMINISTRATOR);
rolesNotContainingAdmin = new ArrayList<String>();
rolesNotContainingAdmin.add(RoleInitializer.EDUCATOR);
}
@Test
public void testAdminInAdminRealm() {
Set<GrantedAuthority> roles = resolver.resolveRoles(ADMIN_REALM_NAME, rolesContainingAdmin);
Assert.assertTrue(roles.contains(Right.READ_ROLES));
}
@Test
public void testAdminNotInAdminRealm() {
Set<GrantedAuthority> roles = resolver.resolveRoles(NON_ADMIN_REALM_NAME, rolesNotContainingAdmin);
Assert.assertFalse(roles.contains(Right.READ_ROLES));
}
@Test
public void testNonAdminInAdminRealm() {
Set<GrantedAuthority> roles = resolver.resolveRoles(ADMIN_REALM_NAME, rolesNotContainingAdmin);
Assert.assertFalse(roles.contains(Right.READ_ROLES));
}
@Test
public void testNonAdminNotInAdminRealm() {
Set<GrantedAuthority> roles = resolver.resolveRoles(NON_ADMIN_REALM_NAME, rolesNotContainingAdmin);
Assert.assertFalse(roles.contains(Right.READ_ROLES));
}
}
|
package com.jme.input.joystick.lwjgl;
import java.util.ArrayList;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Controllers;
import com.jme.input.joystick.DummyJoystickInput;
import com.jme.input.joystick.Joystick;
import com.jme.input.joystick.JoystickInput;
import com.jme.input.joystick.JoystickInputListener;
/**
* LWJGL Implementation of {@link JoystickInput}.
*/
public class LWJGLJoystickInput extends JoystickInput {
private ArrayList<LWJGLJoystick> joysticks;
private DummyJoystickInput.DummyJoystick dummyJoystick;
/**
*
* @throws RuntimeException if initialization failed
*/
protected LWJGLJoystickInput() throws RuntimeException {
try {
Controllers.create();
updateJoystickList();
} catch ( LWJGLException e ) {
throw new RuntimeException( "Initalizing joystick support failed", e );
}
}
private void updateJoystickList() {
joysticks = new ArrayList<LWJGLJoystick>();
for ( int i = 0; i < Controllers.getControllerCount(); i++ ) {
joysticks.add( new LWJGLJoystick( Controllers.getController( i ) ) );
}
}
public void update() {
Controllers.poll();
while ( Controllers.next() ) {
if ( listeners != null && listeners.size() > 0 ) {
Joystick joystick = getJoystick( Controllers.getEventSource().getIndex() );
int controlIndex = Controllers.getEventControlIndex();
if ( Controllers.isEventButton() ) {
boolean buttonPressed = joystick.isButtonPressed( controlIndex );
for ( int i = 0; i < listeners.size(); i++ ) {
JoystickInputListener listener = listeners.get( i );
listener.onButton( joystick, controlIndex, buttonPressed );
}
}
else if ( Controllers.isEventAxis() ) {
float axisValue = joystick.getAxisValue( controlIndex );
for ( int i = 0; i < listeners.size(); i++ ) {
JoystickInputListener listener = listeners.get( i );
listener.onAxis( joystick, controlIndex, axisValue );
}
}
}
}
}
public int getJoystickCount() {
int numJoysticks = joysticks.size();
if ( numJoysticks != Controllers.getControllerCount() )
{
updateJoystickList();
}
return numJoysticks;
}
public Joystick getJoystick( int index ) {
return joysticks.get( index );
}
public Joystick getDefaultJoystick() {
if ( getJoystickCount() > 0 )
{
return getJoystick( getJoystickCount()-1 );
}
if ( dummyJoystick == null )
{
dummyJoystick = new DummyJoystickInput.DummyJoystick();
}
return dummyJoystick;
}
protected void destroy() {
Controllers.destroy();
}
@Override
public ArrayList<Joystick> findJoysticksByAxis(String... axis) {
ArrayList<Joystick> rVal = new ArrayList<Joystick>();
for (int i = 0; i < getJoystickCount(); i++) {
Joystick test = getJoystick(i);
boolean add = true;
for (String aName : axis) {
int aIndex = test.findAxis(aName);
if (aIndex == -1) {
add = false;
break;
}
try {
test.getAxisValue(aIndex);
} catch (Exception e) {
add = false;
break;
}
}
if (add)
rVal.add(test);
}
return rVal;
}
}
|
package gov.nih.nci.cananolab.ui.protocol;
import gov.nih.nci.cananolab.dto.common.AccessibilityBean;
import gov.nih.nci.cananolab.dto.common.DataReviewStatusBean;
import gov.nih.nci.cananolab.dto.common.ProtocolBean;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.service.common.LookupService;
import gov.nih.nci.cananolab.service.protocol.ProtocolService;
import gov.nih.nci.cananolab.service.protocol.helper.ProtocolServiceHelper;
import gov.nih.nci.cananolab.service.protocol.impl.ProtocolServiceLocalImpl;
import gov.nih.nci.cananolab.service.security.SecurityService;
import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.StringUtils;
import java.util.List;
import java.util.SortedSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 org.apache.struts.validator.DynaValidatorForm;
/**
* Create or update protocol file and protocol
*
* @author pansu
*
*/
public class ProtocolAction extends BaseAnnotationAction {
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
DynaValidatorForm theForm = (DynaValidatorForm) form;
ProtocolBean protocolBean = (ProtocolBean) theForm.get("protocol");
Boolean newProtocol = true;
if (protocolBean.getDomain().getId() != null) {
newProtocol = false;
}
UserBean user = (UserBean) request.getSession().getAttribute("user");
ProtocolService service = this.setServiceInSession(request);
protocolBean
.setupDomain(Constants.FOLDER_PROTOCOL, user.getLoginName());
InitProtocolSetup.getInstance().persistProtocolDropdowns(request,
protocolBean);
service.saveProtocol(protocolBean);
// retract from public if updating an existing public record and not
// curator
if (!newProtocol && !user.isCurator()) {
retractFromPublic(theForm, request, protocolBean.getDomain()
.getId().toString(), protocolBean.getDomain().getName(),
"protocol");
ActionMessages messages = new ActionMessages();
ActionMessage msg = null;
msg = new ActionMessage("message.updateProtocol.retractFromPublic");
messages.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, messages);
setupDynamicDropdowns(request, protocolBean);
return mapping.findForward("inputPage");
}
ActionMessages msgs = new ActionMessages();
if (!newProtocol) {
ActionMessage msg = new ActionMessage("message.updateProtocol",
protocolBean.getDisplayName());
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
} else {
ActionMessage msg = new ActionMessage("message.submitProtocol",
protocolBean.getDisplayName());
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
}
saveMessages(request, msgs);
forward = mapping.findForward("success");
return forward;
}
// for retaining user selected values during validation
public ActionForward input(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
InitProtocolSetup.getInstance().setProtocolDropdowns(request);
DynaValidatorForm theForm = (DynaValidatorForm) form;
ProtocolBean protocolBean = ((ProtocolBean) theForm.get("protocol"));
this.setServiceInSession(request);
InitProtocolSetup.getInstance().persistProtocolDropdowns(request,
protocolBean);
setupDynamicDropdowns(request, protocolBean);
return mapping.findForward("inputPage");
}
private void setupDynamicDropdowns(HttpServletRequest request,
ProtocolBean protocolBean) throws Exception {
String selectedProtocolType = protocolBean.getDomain().getType();
String selectedProtocolName = protocolBean.getDomain().getName();
ProtocolServiceLocalImpl protocolService = (ProtocolServiceLocalImpl) (ProtocolService) request
.getSession().getAttribute("protocolService");
ProtocolServiceHelper helper = protocolService.getHelper();
// retrieve user entered protocol names that haven't been saved as
// protocols
SortedSet<String> otherNames = LookupService.findLookupValues(
selectedProtocolType + " protocol type", "otherName");
if (!StringUtils.isEmpty(selectedProtocolType)) {
SortedSet<String> protocolNames = helper
.getProtocolNamesBy(selectedProtocolType);
protocolNames.addAll(otherNames);
request.getSession().setAttribute("protocolNamesByType",
protocolNames);
} else {
request.getSession()
.setAttribute("protocolNamesByType", otherNames);
}
// retrieve user entered protocol versions that haven't been saved
// as protocols
SortedSet<String> otherVersions = LookupService.findLookupValues(
selectedProtocolType + " protocol type", "otherVersion");
if (!StringUtils.isEmpty(selectedProtocolName)) {
SortedSet<String> protocolVersions = helper.getProtocolVersionsBy(
selectedProtocolType, selectedProtocolName);
protocolVersions.addAll(otherVersions);
request.getSession().setAttribute("protocolVersionsByTypeName",
protocolVersions);
} else {
request.getSession().setAttribute("protocolVersionsByTypeName",
otherVersions);
}
}
public ActionForward setupNew(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
request.getSession().removeAttribute("protocolForm");
setServiceInSession(request);
InitProtocolSetup.getInstance().setProtocolDropdowns(request);
request.getSession().removeAttribute("protocolNamesByType");
request.getSession().removeAttribute("protocolVersionsByTypeName");
request.getSession().removeAttribute("updateProtocol");
return mapping.findForward("inputPage");
}
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
InitProtocolSetup.getInstance().setProtocolDropdowns(request);
DynaValidatorForm theForm = (DynaValidatorForm) form;
String protocolId = request.getParameter("protocolId");
ProtocolService service = this.setServiceInSession(request);
ProtocolBean protocolBean = service.findProtocolById(protocolId);
theForm.set("protocol", protocolBean);
setupDynamicDropdowns(request, protocolBean);
request.getSession().setAttribute("updateProtocol", "true");
setUpSubmitForReviewButton(request, protocolBean.getDomain().getId()
.toString(), protocolBean.getPublicStatus());
return mapping.findForward("inputPage");
}
private void setAccesses(HttpServletRequest request,
ProtocolBean protocolBean) throws Exception {
ProtocolService service = this.setServiceInSession(request);
List<AccessibilityBean> groupAccesses = service
.findGroupAccessibilities(protocolBean.getDomain().getId()
.toString());
List<AccessibilityBean> userAccesses = service
.findUserAccessibilities(protocolBean.getDomain().getId()
.toString());
protocolBean.setUserAccesses(userAccesses);
protocolBean.setGroupAccesses(groupAccesses);
}
/**
* Delete a protocol from Protocol update form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
ProtocolBean protocolBean = (ProtocolBean) theForm.get("protocol");
ProtocolService service = this.setServiceInSession(request);
service.deleteProtocol(protocolBean.getDomain());
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.deleteProtocol",
protocolBean.getDisplayName());
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
return mapping.findForward("success");
}
private ProtocolService setServiceInSession(HttpServletRequest request)
throws Exception {
SecurityService securityService = super
.getSecurityServiceFromSession(request);
ProtocolService protocolService = new ProtocolServiceLocalImpl(
securityService);
request.getSession().setAttribute("protocolService", protocolService);
return protocolService;
}
public ActionForward saveAccess(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
ProtocolBean protocol = (ProtocolBean) theForm.get("protocol");
AccessibilityBean theAccess = protocol.getTheAccess();
ProtocolService service = this.setServiceInSession(request);
service.assignAccessibility(theAccess, protocol.getDomain());
// if protocol is public, the access is not public, retract public
// privilege would be handled in the service method
service.assignAccessibility(theAccess, protocol.getDomain());
// update status to retracted if the access is not public and protocol
// is public
if (theAccess.getGroupName().equals(AccessibilityBean.CSM_PUBLIC_GROUP)
&& protocol.getPublicStatus()) {
updateReviewStatusTo(DataReviewStatusBean.RETRACTED_STATUS,
request, protocol.getDomain().getId().toString(), protocol
.getDomain().getName(), "protocol");
}
// if access is public, pending review status, update review
// status to public
if (theAccess.getGroupName().equals(AccessibilityBean.CSM_PUBLIC_GROUP)) {
this.switchPendingReviewToPublic(request, protocol.getDomain()
.getId().toString());
}
if (protocol.getDomain().getId() == null) {
UserBean user = (UserBean) request.getSession()
.getAttribute("user");
protocol
.setupDomain(Constants.FOLDER_PROTOCOL, user.getLoginName());
service.saveProtocol(protocol);
}
this.setAccesses(request, protocol);
return input(mapping, form, request, response);
}
public ActionForward deleteAccess(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
ProtocolBean protocol = (ProtocolBean) theForm.get("protocol");
AccessibilityBean theAccess = protocol.getTheAccess();
ProtocolService service = this.setServiceInSession(request);
service.removeAccessibility(theAccess, protocol.getDomain());
this.setAccesses(request, protocol);
return input(mapping, form, request, response);
}
protected void removePublicAccess(DynaValidatorForm theForm,
HttpServletRequest request) throws Exception {
ProtocolBean protocol = (ProtocolBean) theForm.get("protocol");
ProtocolService service = this.setServiceInSession(request);
service.removeAccessibility(AccessibilityBean.CSM_PUBLIC_ACCESS,
protocol.getDomain());
}
public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ProtocolService service = (ProtocolService) (request.getSession()
.getAttribute("protocolService"));
return downloadFile(service, mapping, form, request, response);
}
}
|
package com.mebigfatguy.fbcontrib.collect;
public class StatisticsKey {
private String className;
private String methodName;
private String signature;
public StatisticsKey(String clsName, String mName, String sig) {
className = clsName;
methodName = mName;
signature = sig;
}
public String getClassName() {
return className;
}
public String getMethodName() {
return methodName;
}
public String getSignature() {
return signature;
}
@Override
public int hashCode() {
return className.hashCode() ^ methodName.hashCode() ^ signature.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof StatisticsKey)) {
return false;
}
StatisticsKey that = (StatisticsKey) o;
return className.equals(that.className) && methodName.equals(that.methodName) && signature.equals(that.signature);
}
@Override
public String toString() {
return "StatisticsKey[className=" + className + ", methodName=" + methodName + ", signature=" + signature + "]";
}
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.Type;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.OpcodeUtils;
import com.mebigfatguy.fbcontrib.utils.SignatureUtils;
import com.mebigfatguy.fbcontrib.utils.TernaryPatcher;
import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue;
import edu.umd.cs.findbugs.OpcodeStack.Item;
import edu.umd.cs.findbugs.ba.ClassContext;
/**
* looks for uses of log4j or slf4j where the class specified when creating the
* logger is not the same as the class in which this logger is used. Also looks
* for using concatenation with slf4j logging rather than using the
* parameterized interface.
*/
@CustomUserValue
public class LoggerOddities extends BytecodeScanningDetector {
private static JavaClass THROWABLE_CLASS;
static {
try {
THROWABLE_CLASS = Repository.lookupClass("java/lang/Throwable");
} catch (ClassNotFoundException cnfe) {
THROWABLE_CLASS = null;
}
}
private static final Set<String> LOGGER_METHODS = UnmodifiableSet.create(
"trace",
"debug",
"info",
"warn",
"error",
"fatal"
);
private static final Pattern BAD_FORMATTING_ANCHOR = Pattern.compile("\\{[0-9]\\}");
private static final Pattern FORMATTER_ANCHOR = Pattern.compile("\\{\\}");
private final BugReporter bugReporter;
private OpcodeStack stack;
private String nameOfThisClass;
/**
* constructs a LO detector given the reporter to report bugs on.
*
* @param bugReporter
* the sync of bug reports
*/
public LoggerOddities(final BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* implements the visitor to discover what the class name is if it is a
* normal class, or the owning class, if the class is an anonymous class.
*
* @param classContext
* the context object of the currently parsed class
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
stack = new OpcodeStack();
nameOfThisClass = classContext.getJavaClass().getClassName();
int subclassIndex = nameOfThisClass.indexOf('$');
while (subclassIndex >= 0) {
String simpleName = nameOfThisClass.substring(subclassIndex + 1);
try {
Integer.parseInt(simpleName);
nameOfThisClass = nameOfThisClass.substring(0, subclassIndex);
subclassIndex = nameOfThisClass.indexOf('$');
} catch (NumberFormatException nfe) {
subclassIndex = -1;
}
}
nameOfThisClass = nameOfThisClass.replace('.', '/');
super.visitClassContext(classContext);
} finally {
stack = null;
}
}
/**
* implements the visitor to reset the stack
*
* @param obj
* the context object of the currently parsed code block
*/
@Override
public void visitCode(Code obj) {
stack.resetForMethodEntry(this);
Method m = getMethod();
if (Values.CONSTRUCTOR.equals(m.getName())) {
Type[] types = Type.getArgumentTypes(m.getSignature());
for (Type t : types) {
String parmSig = t.getSignature();
if ("Lorg/slf4j/Logger;".equals(parmSig) || "Lorg/apache/log4j/Logger;".equals(parmSig) || "Lorg/apache/commons/logging/Log;".equals(parmSig)) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this));
}
}
}
super.visitCode(obj);
}
/**
* implements the visitor to look for calls to Logger.getLogger with the
* wrong class name
*
* @param seen
* the opcode of the currently parsed instruction
*/
@Override
public void sawOpcode(int seen) {
String ldcClassName = null;
String seenMethodName = null;
int exMessageReg = -1;
Integer arraySize = null;
try {
stack.precomputation(this);
if ((seen == LDC) || (seen == LDC_W)) {
Constant c = getConstantRefOperand();
if (c instanceof ConstantClass) {
ConstantPool pool = getConstantPool();
ldcClassName = ((ConstantUtf8) pool.getConstant(((ConstantClass) c).getNameIndex())).getBytes();
}
} else if (seen == INVOKESTATIC) {
lookForSuspectClasses();
} else if (((seen == INVOKEVIRTUAL) || (seen == INVOKEINTERFACE)) && (THROWABLE_CLASS != null)) {
String mthName = getNameConstantOperand();
if ("getName".equals(mthName)) {
if (stack.getStackDepth() >= 1) {
// Foo.class.getName() is being called, so we pass the
// name of the class to the current top of the stack
// (the name of the class is currently on the top of the
// stack, but won't be on the stack at all next opcode)
Item stackItem = stack.getStackItem(0);
ldcClassName = (String) stackItem.getUserValue();
}
} else if ("getMessage".equals(mthName)) {
String callingClsName = getClassConstantOperand();
JavaClass cls = Repository.lookupClass(callingClsName);
if (cls.instanceOf(THROWABLE_CLASS)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item exItem = stack.getStackItem(0);
exMessageReg = exItem.getRegisterNumber();
}
}
} else if (LOGGER_METHODS.contains(mthName)) {
checkForProblemsWithLoggerMethods();
} else if ("toString".equals(mthName)) {
String callingClsName = getClassConstantOperand();
if (("java/lang/StringBuilder".equals(callingClsName) || "java/lang/StringBuffer".equals(callingClsName))) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
// if the stringbuilder was previously stored, don't
// report it
if (item.getRegisterNumber() < 0) {
seenMethodName = mthName;
}
}
}
}
} else if (seen == INVOKESPECIAL) {
checkForLoggerParam();
} else if (seen == ANEWARRAY) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item sizeItem = stack.getStackItem(0);
Object con = sizeItem.getConstant();
if (con instanceof Integer) {
arraySize = (Integer) con;
}
}
} else if (seen == AASTORE) {
if (stack.getStackDepth() >= 3) {
OpcodeStack.Item arrayItem = stack.getStackItem(2);
Integer size = (Integer) arrayItem.getUserValue();
if ((size != null) && (size.intValue() > 0)) {
if (hasExceptionOnStack()) {
arrayItem.setUserValue(Integer.valueOf(-size.intValue()));
}
}
}
} else if (OpcodeUtils.isAStore(seen)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
if ("toString".equals(item.getUserValue())) {
item.setUserValue(null);
}
}
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
} finally {
TernaryPatcher.pre(stack, seen);
stack.sawOpcode(this, seen);
TernaryPatcher.post(stack, seen);
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
if (ldcClassName != null) {
item.setUserValue(ldcClassName);
} else if (seenMethodName != null) {
item.setUserValue(seenMethodName);
} else if (exMessageReg >= 0) {
item.setUserValue(Integer.valueOf(exMessageReg));
} else if (arraySize != null) {
item.setUserValue(arraySize);
}
}
}
}
private void checkForProblemsWithLoggerMethods() throws ClassNotFoundException {
String callingClsName = getClassConstantOperand();
if (callingClsName.endsWith("Log") || (callingClsName.endsWith("Logger"))) {
String sig = getSigConstantOperand();
if ("(Ljava/lang/String;Ljava/lang/Throwable;)V".equals(sig) || "(Ljava/lang/Object;Ljava/lang/Throwable;)V".equals(sig)) {
if (stack.getStackDepth() >= 2) {
OpcodeStack.Item exItem = stack.getStackItem(0);
OpcodeStack.Item msgItem = stack.getStackItem(1);
Object exReg = msgItem.getUserValue();
if (exReg instanceof Integer) {
if (((Integer) exReg).intValue() == exItem.getRegisterNumber()) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_STUTTERED_MESSAGE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(this));
}
}
}
} else if ("(Ljava/lang/Object;)V".equals(sig)) {
if (stack.getStackDepth() > 0) {
final JavaClass clazz = stack.getStackItem(0).getJavaClass();
if ((clazz != null) && clazz.instanceOf(THROWABLE_CLASS)) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_LOGGER_LOST_EXCEPTION_STACK_TRACE.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
}
}
} else if ("org/slf4j/Logger".equals(callingClsName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/String;)V".equals(signature) || "(Ljava/lang/String;Ljava/lang/Object;)V".equals(signature)
|| "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V".equals(signature)
|| "(Ljava/lang/String;[Ljava/lang/Object;)V".equals(signature)) {
int numParms = Type.getArgumentTypes(signature).length;
if (stack.getStackDepth() >= numParms) {
OpcodeStack.Item formatItem = stack.getStackItem(numParms - 1);
Object con = formatItem.getConstant();
if (con instanceof String) {
Matcher m = BAD_FORMATTING_ANCHOR.matcher((String) con);
if (m.find()) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_INVALID_FORMATTING_ANCHOR.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
} else {
int actualParms = getSLF4JParmCount(signature);
if (actualParms != -1) {
int expectedParms = countAnchors((String) con);
boolean hasEx = hasExceptionOnStack();
if ((!hasEx && (expectedParms != actualParms))
|| (hasEx && ((expectedParms != (actualParms - 1)) && (expectedParms != actualParms)))) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_INCORRECT_NUMBER_OF_ANCHOR_PARAMETERS.name(), NORMAL_PRIORITY)
.addClass(this).addMethod(this).addSourceLine(this).addString("Expected: " + expectedParms)
.addString("Actual: " + actualParms));
}
}
}
} else if ("toString".equals(formatItem.getUserValue())) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_APPENDED_STRING_IN_FORMAT_STRING.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
}
}
}
}
}
}
private void checkForLoggerParam() {
if (Values.CONSTRUCTOR.equals(getNameConstantOperand())) {
String cls = getClassConstantOperand();
if ((cls.startsWith("java/") || cls.startsWith("javax/")) && cls.endsWith("Exception")) {
String sig = getSigConstantOperand();
Type[] types = Type.getArgumentTypes(sig);
if (types.length <= stack.getStackDepth()) {
for (int i = 0; i < types.length; i++) {
if ("Ljava/lang/String;".equals(types[i].getSignature())) {
OpcodeStack.Item item = stack.getStackItem(types.length - i - 1);
String cons = (String) item.getConstant();
if ((cons != null) && cons.contains("{}")) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_EXCEPTION_WITH_LOGGER_PARMS.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
break;
}
}
}
}
}
}
}
private void lookForSuspectClasses() {
String callingClsName = getClassConstantOperand();
String mthName = getNameConstantOperand();
String loggingClassName = null;
int loggingPriority = NORMAL_PRIORITY;
if ("org/slf4j/LoggerFactory".equals(callingClsName) && "getLogger".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/slf4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/slf4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
} else if ("org/apache/log4j/Logger".equals(callingClsName) && "getLogger".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
Object userValue = item.getUserValue();
if (loggingClassName != null) {
// first look at the constant passed in
loggingClassName = loggingClassName.replace('.', '/');
loggingPriority = LOW_PRIORITY;
} else if (userValue instanceof String) {
// try the user value, which may have been set by a call
// to Foo.class.getName()
loggingClassName = (String) userValue;
loggingClassName = loggingClassName.replace('.', '/');
}
}
} else if ("(Ljava/lang/String;Lorg/apache/log4j/spi/LoggerFactory;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 1) {
OpcodeStack.Item item = stack.getStackItem(1);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
} else if ("org/apache/commons/logging/LogFactory".equals(callingClsName) && "getLog".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/apache/commons/logging/Log;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/apache/commons/logging/Log;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
}
if (loggingClassName != null) {
if (stack.getStackDepth() > 0) {
if (!loggingClassName.equals(nameOfThisClass)) {
boolean isPrefix = nameOfThisClass.startsWith(loggingClassName);
boolean isAnonClassPrefix;
if (isPrefix) {
String anonClass = nameOfThisClass.substring(loggingClassName.length());
isAnonClassPrefix = anonClass.matches("(\\$\\d+)+");
} else {
isAnonClassPrefix = false;
}
if (!isAnonClassPrefix) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_CLASS.name(), loggingPriority).addClass(this).addMethod(this)
.addSourceLine(this).addString(loggingClassName).addString(nameOfThisClass));
}
}
}
}
}
/**
* returns the number of anchors {} in a string
*
* @param formatString
* the format string
* @return the number of anchors
*/
private static int countAnchors(String formatString) {
Matcher m = FORMATTER_ANCHOR.matcher(formatString);
int count = 0;
int start = 0;
while (m.find(start)) {
++count;
start = m.end();
}
return count;
}
/**
* returns the number of parameters slf4j is expecting to inject into the
* format string
*
* @param signature
* the method signature of the error, warn, info, debug statement
* @return the number of expected parameters
*/
private int getSLF4JParmCount(String signature) {
if ("(Ljava/lang/String;Ljava/lang/Object;)V".equals(signature))
return 1;
if ("(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V".equals(signature))
return 2;
OpcodeStack.Item item = stack.getStackItem(0);
Integer size = (Integer) item.getUserValue();
if (size != null) {
return Math.abs(size.intValue());
}
return -1;
}
/**
* returns whether an exception object is on the stack slf4j will find this,
* and not include it in the parm list so i we find one, just don't report
*
* @return whether or not an exception i present
*/
private boolean hasExceptionOnStack() {
try {
for (int i = 0; i < stack.getStackDepth() - 1; i++) {
OpcodeStack.Item item = stack.getStackItem(i);
String sig = item.getSignature();
if (sig.startsWith("L")) {
String name = SignatureUtils.stripSignature(sig);
JavaClass cls = Repository.lookupClass(name);
if (cls.instanceOf(THROWABLE_CLASS))
return true;
} else if (sig.startsWith("[")) {
Integer sz = (Integer) item.getUserValue();
if ((sz != null) && (sz.intValue() < 0))
return true;
}
}
return false;
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
return true;
}
}
}
|
package com.xceptance.xlt.common.util;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang.StringUtils;
import bsh.EvalError;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.xceptance.common.util.RegExUtils;
import com.xceptance.xlt.api.util.XltLogger;
import com.xceptance.xlt.api.validators.HttpResponseCodeValidator;
import com.xceptance.xlt.common.tests.AbstractURLTestCase;
import com.xceptance.xlt.common.util.bsh.ParamInterpreter;
public class CSVBasedURLAction
{
// dynamic parameters
public static final String XPATH_GETTER_PREFIX = "xpath";
public static final String REGEXP_GETTER_PREFIX = "regexp";
public static final int DYNAMIC_GETTER_COUNT = 10;
/**
* Permitted header fields, checked to avoid accidental incorrect spelling
*/
private final static Set<String> PERMITTEDHEADERFIELDS = new HashSet<String>();
public static final String GET = "GET";
public static final String POST = "POST";
public static final String TYPE = "Type";
public static final String TYPE_ACTION = "A";
public static final String TYPE_STATIC = "S";
public static final String NAME = "Name";
public static final String URL = "URL";
public static final String METHOD = "Method";
public static final String PARAMETERS = "Parameters";
public static final String RESPONSECODE = "ResponseCode";
public static final String XPATH = "XPath";
public static final String REGEXP = "RegExp";
public static final String TEXT = "Text";
public static final String ENCODED = "Encoded";
static
{
PERMITTEDHEADERFIELDS.add(TYPE);
PERMITTEDHEADERFIELDS.add(NAME);
PERMITTEDHEADERFIELDS.add(URL);
PERMITTEDHEADERFIELDS.add(METHOD);
PERMITTEDHEADERFIELDS.add(PARAMETERS);
PERMITTEDHEADERFIELDS.add(RESPONSECODE);
PERMITTEDHEADERFIELDS.add(XPATH);
PERMITTEDHEADERFIELDS.add(REGEXP);
PERMITTEDHEADERFIELDS.add(TEXT);
PERMITTEDHEADERFIELDS.add(ENCODED);
for (int i = 1; i <= DYNAMIC_GETTER_COUNT; i++)
{
PERMITTEDHEADERFIELDS.add(XPATH_GETTER_PREFIX + i);
PERMITTEDHEADERFIELDS.add(REGEXP_GETTER_PREFIX + i);
}
}
private final String type;
private final String name;
private final URL url;
private final String urlString;
private final String method;
private final List<NameValuePair> parameters;
private final HttpResponseCodeValidator httpResponseCodeValidator;
private final String xPath;
private final String regexpString;
private final Pattern regexp;
private final String text;
private final boolean encoded;
private final List<String> xpathGetterList = new ArrayList<String>(DYNAMIC_GETTER_COUNT);
private final List<String> regexpGetterList = new ArrayList<String>(DYNAMIC_GETTER_COUNT);
/**
* Our bean shell
*/
private final ParamInterpreter interpreter;
/**
* Constructor based upon read CSV data
*
* @param record the record to process
* @param interpreter the bean shell interpreter to use
*
* @throws UnsupportedEncodingException
* @throws MalformedURLException
*/
public CSVBasedURLAction(final CSVRecord record, final ParamInterpreter interpreter) throws UnsupportedEncodingException, MalformedURLException
{
// no bean shell, so we do not do anything, satisfy final here
this.interpreter = interpreter;
// the header is record 1, so we have to subtract one, for autonaming
this.name = StringUtils.defaultIfBlank(record.get(NAME), "Action-" + (record.getRecordNumber() - 1));
// take care of type
String _type = StringUtils.defaultIfBlank(record.get(TYPE), TYPE_ACTION);
if (!_type.equals(TYPE_ACTION) && !_type.equals(TYPE_STATIC))
{
XltLogger.runTimeLogger.warn(MessageFormat.format("Unknown type '{0}' in line {1}, defaulting to 'A'", _type, record.getRecordNumber()));
_type = TYPE_ACTION;
}
this.type = _type;
// we need at least an url, stop here of not given
this.urlString = record.get(URL);
if (this.urlString == null)
{
throw new IllegalArgumentException(MessageFormat.format("No url given in record in line {0}. Need at least that.", record.getRecordNumber()));
}
this.url = interpreter == null ? new URL(this.urlString) : null;
// take care of method
String _method = StringUtils.defaultIfBlank(record.get(METHOD), GET);
if (!_method.equals(GET) && !_method.equals(POST))
{
XltLogger.runTimeLogger.warn(MessageFormat.format("Unknown method '{0}' in line {1}, defaulting to 'GET'", _method, record.getRecordNumber()));
_method = GET;
}
this.method = _method;
// get the response code validator
this.httpResponseCodeValidator = StringUtils.isNotBlank(record.get(RESPONSECODE)) ? new HttpResponseCodeValidator(Integer.parseInt(record.get(RESPONSECODE))) : HttpResponseCodeValidator.getInstance();
// compile pattern only, if no interpreter shall be used
this.regexpString = StringUtils.isNotEmpty(record.get(REGEXP)) ? record.get(REGEXP) : null;
if (interpreter == null)
{
this.regexp = StringUtils.isNotEmpty(regexpString) ? RegExUtils.getPattern(regexpString) : null;
}
else
{
this.regexp = null;
}
this.xPath = StringUtils.isNotBlank(record.get(XPATH)) ? record.get(XPATH) : null;
this.text = StringUtils.isNotEmpty(record.get(TEXT)) ? record.get(TEXT) : null;
this.encoded = StringUtils.isNotBlank(record.get(ENCODED)) ? Boolean.parseBoolean(record.get(ENCODED)) : false;
// ok, get all the parameters
for (int i = 1; i <= DYNAMIC_GETTER_COUNT; i++)
{
xpathGetterList.add(StringUtils.isNotBlank(record.get(XPATH_GETTER_PREFIX + i)) ? record.get(XPATH_GETTER_PREFIX + i) : null);
regexpGetterList.add(StringUtils.isNotBlank(record.get(REGEXP_GETTER_PREFIX + i)) ? record.get(REGEXP_GETTER_PREFIX + i) : null);
}
// ok, this is the tricky part
this.parameters = StringUtils.isNotEmpty(record.get(PARAMETERS)) ? setupParameters(record.get(PARAMETERS)) : null;
}
/**
* Constructor based upon read CSV data
* @param record
* @throws UnsupportedEncodingException
* @throws MalformedURLException
*/
public CSVBasedURLAction(final CSVRecord record) throws UnsupportedEncodingException, MalformedURLException
{
this(record, null);
}
/**
* Takes the list of parameters and turns it into name value pairs for later usage.
*
* @param paramers the csv definition string of parameters
* @return a list with parsed key value pairs
* @throws UnsupportedEncodingException
*/
private List<NameValuePair> setupParameters(final String parameters) throws UnsupportedEncodingException
{
final List<NameValuePair> list = new ArrayList<NameValuePair>();
// ok, turn them into & split strings
final StringTokenizer tokenizer = new StringTokenizer(parameters, "&");
while (tokenizer.hasMoreTokens())
{
final String token = tokenizer.nextToken();
// the future pair
String key = null;
String value = null;
// split it into key and value at =
final int pos = token.indexOf("=");
if (pos >= 0)
{
key = token.substring(0, pos);
if (pos < token.length() - 1)
{
value = token.substring(pos + 1);
}
}
else
{
key = token;
}
// ok, if this is encoded, we have to decode it again, because the httpclient will encode it
// on its own later on
if (encoded)
{
key = key != null ? URLDecoder.decode(key, "UTF-8") : null;
value = value != null ? URLDecoder.decode(value, "UTF-8") : "";
}
if (key != null)
{
list.add(new NameValuePair(key, value));
}
}
return list;
}
// /**
// * Is this static content or dynamic stuff, important for the downloader and concurrency
// *
// * @return it is either A or S
// */
// public String getType()
// return type;
/**
* Returns if this is static content to be downloaded
*
* @return true if this is static content
*/
public boolean isStaticContent()
{
return type.equals(TYPE_STATIC);
}
/**
* Returns true if this is an action to be executed
*
* @return true if this is an action
*/
public boolean isAction()
{
return type.equals(TYPE_ACTION);
}
/**
* Returns the name of this line.
*
* @return the name of this line
*/
public String getName(final AbstractURLTestCase testCase)
{
return interpreter != null ? interpreter.processDynamicData(testCase, name) : name;
}
public String getName()
{
return getName(null);
}
/**
* Returns the url of that action. Is required.
*
* @param testCase for the correct data resulution
* @return the url with data resolution
* @throws MalformedURLException
*/
public URL getURL(final AbstractURLTestCase testCase) throws MalformedURLException
{
// process bean shell part
return interpreter != null ? new URL(interpreter.processDynamicData(testCase, urlString)) : url;
}
public URL getURL() throws MalformedURLException
{
return getURL(null);
}
public HttpMethod getMethod()
{
if (this.method.equals(POST))
{
return HttpMethod.POST;
}
else
{
return HttpMethod.GET;
}
}
public List<NameValuePair> getParameters(final AbstractURLTestCase testCase)
{
// process bean shell part
if (interpreter != null && parameters != null)
{
// create new list
final List<NameValuePair> result = new ArrayList<NameValuePair>(parameters.size());
// process all
for (final NameValuePair pair : parameters)
{
final String name = interpreter.processDynamicData(testCase, pair.getName());
String value = pair.getValue();
value = value != null ? interpreter.processDynamicData(testCase, value) : value;
result.add(new NameValuePair(name, value));
}
return result;
}
else
{
return parameters;
}
}
public List<NameValuePair> getParameters()
{
return getParameters(null);
}
public HttpResponseCodeValidator getHttpResponseCodeValidator()
{
return httpResponseCodeValidator;
}
public String getXPath(final AbstractURLTestCase testCase)
{
// process bean shell part
return interpreter != null ? interpreter.processDynamicData(testCase, xPath) : xPath;
}
public String getXPath()
{
return getXPath(null);
}
public Pattern getRegexp(final AbstractURLTestCase testCase)
{
// process bean shell part
return interpreter != null && regexpString != null? RegExUtils.getPattern(interpreter.processDynamicData(testCase, regexpString)) : regexp;
}
public Pattern getRegexp()
{
return getRegexp(null);
}
public String getText(final AbstractURLTestCase testCase)
{
// process bean shell part
return interpreter != null ? interpreter.processDynamicData(testCase, text) : text;
}
public String getText()
{
return getText(null);
}
/**
* Returns true of this data is already html encoded for transfer
*
* @return true if parameters and url is encoded
*/
public boolean isEncoded()
{
return encoded;
}
/**
* Returns the active interpreter. Important for testing.
*
* @return The active bean interpreter.
*/
public ParamInterpreter getInterpreter()
{
return interpreter;
}
/**
* Returns the list of optional getters
*
* @return list of xpath getters
* TODO test it
*/
public List<String> getXPathGetterList(final AbstractURLTestCase testCase)
{
// do not do anything when there is not interpreter
if (interpreter == null)
{
return xpathGetterList;
}
final List<String> result = new ArrayList<String>(xpathGetterList.size());
for (int i = 0; i < xpathGetterList.size(); i++)
{
final String s = xpathGetterList.get(i);
result.add(interpreter.processDynamicData(testCase, s));
}
return result;
}
/**
* Returns the list of regexp patterns
*
* @return the list of regexp getter patterns
* TODO test it
*/
public List<Pattern> getRegExpGetterList(final AbstractURLTestCase testCase)
{
final List<Pattern> result = new ArrayList<Pattern>(regexpGetterList.size());
for (int i = 0; i < regexpGetterList.size(); i++)
{
final String s = regexpGetterList.get(i);
if (interpreter != null)
{
result.add(s != null ? RegExUtils.getPattern(interpreter.processDynamicData(testCase, s)) : null);
}
else
{
result.add(s != null ? RegExUtils.getPattern(s) : null);
}
}
return result;
}
/**
* Take back the evaluation results to spice up the interpreter
*
* @param xpathGettersResults a list of results
*
* TODO test it
*/
public void setXPathGetterResult(final List<Object> results)
{
// of course, we do that only with an interpreter running
if (interpreter != null)
{
for (int i = 1; i <= results.size(); i++)
{
try
{
interpreter.set(XPATH_GETTER_PREFIX + i, results.get(i - 1));
}
catch (final EvalError e)
{
XltLogger.runTimeLogger.warn("Unable to take in the result of an xpath evaluation.", e);
}
}
}
}
/**
* Take back the evaluation results to spice up the interpreter
*
* @param xpathGettersResults a list of results
* TODO test it
*/
public void setRegExpGetterResult(final List<Object> results)
{
// of course, we do that only with an interpreter running
if (interpreter != null)
{
for (int i = 1; i <= results.size(); i++)
{
try
{
interpreter.set(REGEXP_GETTER_PREFIX + i, results.get(i - 1));
}
catch (final EvalError e)
{
XltLogger.runTimeLogger.warn("Unable to take in the result of a regexp evaluation.", e);
}
}
}
}
/**
* Returns true of header field is value, false otherwise.
* @param fieldName header field to check
* @return true if valid field, false otherwise
* TODO test it
*/
public static boolean isPermittedHeaderField(final String fieldName)
{
return PERMITTEDHEADERFIELDS.contains(fieldName);
}
}
|
package de.lmu.ifi.dbs.elki.database.relation;
import de.lmu.ifi.dbs.elki.data.type.SimpleTypeInformation;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.result.AbstractHierarchicalResult;
import de.lmu.ifi.dbs.elki.utilities.iterator.IterableIterator;
import de.lmu.ifi.dbs.elki.utilities.iterator.IterableUtil;
/**
* A virtual partitioning of the database. For the accepted DBIDs, access is
* passed on to the wrapped representation.
*
* @author Erich Schubert
*
* @param <O> Object type
*/
public class ProxyView<O> extends AbstractHierarchicalResult implements Relation<O> {
/**
* Our database
*/
private final Database database;
/**
* The DBIDs we contain
*/
private final DBIDs idview;
/**
* The wrapped representation where we get the IDs from.
*/
private final Relation<O> inner;
/**
* Constructor.
*
* @param idview Ids to expose
* @param inner Inner representation
*/
public ProxyView(Database database, DBIDs idview, Relation<O> inner) {
super();
this.database = database;
this.idview = DBIDUtil.makeUnmodifiable(idview);
this.inner = inner;
}
@Override
public Database getDatabase() {
return database;
}
/**
* Constructor-like static method.
*
* @param <O> Object type
* @param idview Ids to expose
* @param inner Inner representation
* @return Instance
*/
public static <O> ProxyView<O> wrap(Database database, DBIDs idview, Relation<O> inner) {
return new ProxyView<O>(database, idview, inner);
}
@Override
public O get(DBID id) {
assert (idview.contains(id)) : "Accessing object not included in view.";
return inner.get(id);
}
@Override
public void set(DBID id, O val) {
assert (idview.contains(id)) : "Accessing object not included in view.";
inner.set(id, val);
}
@Override
public void delete(DBID id) {
throw new UnsupportedOperationException("Semantics of 'delete-from-virtual-partition' are not uniquely defined. Delete from IDs or from underlying data, please!");
}
@Override
public DBIDs getDBIDs() {
return idview;
}
@Override
public IterableIterator<DBID> iterDBIDs() {
return IterableUtil.fromIterable(idview);
}
@Override
public int size() {
return idview.size();
}
@Override
public SimpleTypeInformation<O> getDataTypeInformation() {
return inner.getDataTypeInformation();
}
@Override
public String getLongName() {
return "Partition of " + inner.getLongName();
}
@Override
public String getShortName() {
return "partition";
}
}
|
package de.matthiasmann.twlthemeeditor.datamodel;
import de.matthiasmann.twl.Dimension;
import de.matthiasmann.twl.model.TreeTableNode;
import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twlthemeeditor.TestEnv;
import de.matthiasmann.twlthemeeditor.VirtualFile;
import de.matthiasmann.twlthemeeditor.datamodel.operations.CreateChildOperation;
import de.matthiasmann.twlthemeeditor.datamodel.operations.CreateNewSimple;
import de.matthiasmann.twlthemeeditor.datamodel.operations.CreateNewArea;
import de.matthiasmann.twlthemeeditor.datamodel.operations.CreateNewGradient;
import de.matthiasmann.twlthemeeditor.properties.AttributeProperty;
import de.matthiasmann.twlthemeeditor.properties.HasProperties;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Element;
/**
*
* @author Matthias Mann
*/
public class Images extends ThemeTreeNode implements HasProperties {
private Dimension textureDimensions;
private AttributeProperty commentProperty;
protected VirtualFile textureVirtualFile;
Images(TreeTableNode parent, Element element, ThemeFile themeFile) throws IOException {
super(themeFile, parent, element);
registerTextureURL();
}
final void registerTextureURL() throws IOException {
TestEnv env = themeFile.getEnv();
if(textureVirtualFile != null) {
env.unregisterFile(textureVirtualFile);
textureVirtualFile = null;
}
URL textureURL = getTextureURL();
if(textureURL != null) {
textureVirtualFile = env.registerFile(textureURL);
InputStream textureStream = textureURL.openStream();
try {
PNGDecoder decoder = new PNGDecoder(textureStream);
textureDimensions = new Dimension(decoder.getWidth(), decoder.getHeight());
} finally {
textureStream.close();
}
}
commentProperty = new AttributeProperty(element, "comment", "Comment", true);
addProperty(commentProperty);
}
public URL getTextureURL() throws MalformedURLException {
String file = getFile();
if(file != null) {
return themeFile.getURL(file);
} else {
return null;
}
}
public void updateTextureDimension(URL url, int width, int height) {
if(width != textureDimensions.getX() && height != textureDimensions.getY()) {
try {
if(url.equals(getTextureURL())) {
textureDimensions = new Dimension(width, height);
}
} catch(MalformedURLException ex) {
Logger.getLogger(Images.class.getName()).log(Level.SEVERE, "Could not compare URLs", ex);
}
}
}
public String getFile() {
return element.getAttributeValue("file");
}
public String getFormat() {
return element.getAttributeValue("format");
}
@Override
public String toString() {
return "[Images file=\""+getFile()+"\"]";
}
@Override
public String getName() {
return getFile();
}
@Override
protected String getIcon() {
return "images";
}
@Override
public String getDisplayName() {
String comment = commentProperty.getPropertyValue();
String name = getName();
if(comment != null) {
comment = comment.trim();
}
if(comment != null && comment.length() > 0) {
if(name != null) {
return comment + " (" + name + ")";
}
return comment;
} else if(name != null) {
return name;
}
return "<add comment>";
}
public Kind getKind() {
return Kind.NONE;
}
@Override
protected String getType() {
return "PNG";
}
public Dimension getTextureDimensions() {
return textureDimensions;
}
private static final String[] ALLOWED_CHILDREN = {
"area", "select", "composed", "grid", "animation", "alias", "gradient"
};
public static boolean isAllowedChildImage(String tag) {
for(String allowed : ALLOWED_CHILDREN) {
if(allowed.equals(tag)) {
return true;
}
}
return false;
}
@Override
public boolean canPasteElement(Element element) {
String tag = element.getName();
return isAllowedChildImage(tag) || "cursor".equals(tag);
}
@Override
public boolean childrenNeedName() {
return true;
}
public void addChildren() throws IOException {
addChildren(themeFile, element, Image.getImageDomWrapper(this));
}
@SuppressWarnings("unchecked")
public void addToXPP(DomXPPParser xpp) {
Utils.addToXPP(xpp, element.getName(), this, element.getAttributes());
}
@Override
public List<CreateChildOperation> getCreateChildOperations() {
List<CreateChildOperation> operations = super.getCreateChildOperations();
addCreateImageOperations(operations, this);
return operations;
}
public static void addCreateImageOperations(List<CreateChildOperation> operations, ThemeTreeNode parent) {
operations.add(new CreateNewArea(parent, parent.getDOMElement(), "area"));
operations.add(new CreateNewSimple(parent, parent.getDOMElement(), "select"));
operations.add(new CreateNewSimple(parent, parent.getDOMElement(), "composed"));
operations.add(new CreateNewSimple(parent, parent.getDOMElement(), "grid", "weightsX", "0,1,0", "weightsY", "0,1,0"));
operations.add(new CreateNewSimple(parent, parent.getDOMElement(), "animation", "timeSource", "hover"));
operations.add(new CreateNewSimple(parent, parent.getDOMElement(), "alias", "ref", "none"));
operations.add(new CreateNewGradient(parent, parent.getDOMElement()));
operations.add(new CreateNewArea(parent, parent.getDOMElement(), "cursor", "hotSpotX", "0", "hotSpotY", "0"));
operations.add(new CreateNewSimple("opNewNodeCursorAlias", parent, parent.getDOMElement(), "cursor", "ref", "none"));
}
}
|
package de.lmu.ifi.dbs.elki.visualization.visualizers.vis1d;
import org.apache.batik.util.SVGConstants;
import org.w3c.dom.Element;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil;
import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisualizer;
import de.lmu.ifi.dbs.elki.visualization.visualizers.ProjectedVisualizer;
/**
* Produces visualizations of 1-dimensional projections.
*
* @author Remigius Wojdanowski
*
* @param <NV> Type of the NumberVector being visualized.
*/
public abstract class Projection1DVisualizer<NV extends NumberVector<NV, ?>> extends AbstractVisualizer implements ProjectedVisualizer {
/**
* Setup a canvas (wrapper) element for the visualization.
*
* @param svgp Plot context
* @return Wrapper element with appropriate view box.
*/
public Element setupCanvas(SVGPlot svgp, double width, double height) {
Element layer = SVGUtil.svgElement(svgp.getDocument(), SVGConstants.SVG_SVG_TAG);
// Some default for the view box.
double xmargin = 0.1 * width;
double ymargin = 0.1 * height;
double left = -(width / 2 + xmargin);
double top = -(height / 2 + ymargin);
double vwidth = width + 2 * xmargin;
double vheight = height + 2 * ymargin;
SVGUtil.setAtt(layer, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE, left + " " + top + " " + vwidth + " " + vheight);
return layer;
}
}
|
package eu.ydp.empiria.player.client.module.colorfill.view;
import java.util.Map;
import javax.annotation.PostConstruct;
import com.google.common.collect.Maps;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import eu.ydp.empiria.player.client.module.colorfill.fill.BlackColorContourDetector;
import eu.ydp.empiria.player.client.module.colorfill.fill.CanvasImageData;
import eu.ydp.empiria.player.client.module.colorfill.fill.FloodFillScanLine;
import eu.ydp.empiria.player.client.module.colorfill.model.ColorModel;
import eu.ydp.empiria.player.client.module.colorfill.structure.Area;
import eu.ydp.empiria.player.client.module.colorfill.structure.Image;
import eu.ydp.empiria.player.client.util.position.PositionHelper;
import eu.ydp.gwtutil.client.event.factory.Command;
import eu.ydp.gwtutil.client.event.factory.UserInteractionHandlerFactory;
public class ColorfillCanvasStubImpl implements ColorfillCanvas {
@Inject
private ColorfillCanvasStubView canvasStubView;
@Inject
private UserInteractionHandlerFactory interactionHandlerFactory;
@Inject
private PositionHelper positionHelper;
private boolean canvasStubViewLoded = false;
private final Map<Area, ColorModel> colors = Maps.newHashMap();
private ColorfillAreaClickListener listener;
private CanvasImageData imageData;
@PostConstruct
public void postConstruct() {
canvasStubView.setImageLoadHandler(new LoadHandler() {
@Override
public void onLoad(LoadEvent event) {
canvasStubViewLoded = true;
bindView();
}
});
}
void bindView() {
reloadImageData();
for (Map.Entry<Area, ColorModel> areaColor : colors.entrySet()) {
setColorOnCanvas(areaColor.getKey(), areaColor.getValue());
}
colors.clear();
if (listener != null) {
addAreaClickListener(listener);
}
flushImageToCanvas();
}
void reloadImageData() {
imageData = new CanvasImageData(canvasStubView.getCanvas().getContext2d(), canvasStubView.getWidth(), canvasStubView.getHeight());
}
@Override
public void setImage(final Image image) {
canvasStubView.setImageUrl(image.getSrc(), image.getWidth(), image.getHeight());
}
@Override
public void setColor(final Area area, final ColorModel color) {
if (canvasStubViewLoded) {
setColorOnCanvas(area, color);
flushImageToCanvas();
} else {
colors.put(area, color);
}
}
private void setColorOnCanvas(Area area, ColorModel color) {
FloodFillScanLine floodFiller = new FloodFillScanLine(imageData, new BlackColorContourDetector(), color);
floodFiller.fillArea(area.getX(), area.getY());
}
@Override
public ColorModel getColor(final Area area) {
return imageData.getRgbColor(area.getX(), area.getY());
}
@Override
public void setColors(final Map<Area, ColorModel> colors) {
if (canvasStubViewLoded) {
for (Map.Entry<Area, ColorModel> areaColor : colors.entrySet()) {
setColorOnCanvas(areaColor.getKey(), areaColor.getValue());
}
flushImageToCanvas();
} else {
colors.putAll(colors);
}
}
@Override
public void setAreaClickListener(final ColorfillAreaClickListener listener) {
if (canvasStubViewLoded) {
addAreaClickListener(listener);
} else {
this.listener = listener;
}
}
private void addAreaClickListener(final ColorfillAreaClickListener listener) {
interactionHandlerFactory.applyUserClickHandler(new Command() {
@Override
public void execute(NativeEvent event) {
event.preventDefault();
CanvasElement canvasElement = canvasStubView.getCanvas().getCanvasElement();
listener.onAreaClick(new Area(positionHelper.getPositionX(event, canvasElement), positionHelper.getPositionY(event, canvasElement)));
}
}, canvasStubView.getCanvas());
}
@Override
public void reset() {
canvasStubView.reload();
reloadImageData();
}
public void flushImageToCanvas(){
imageData.flush();
}
@Override
public Widget asWidget() {
return canvasStubView.asWidget();
}
}
|
package dk.netarkivet.harvester.harvesting;
import java.io.File;
import dk.netarkivet.common.utils.Settings;
import dk.netarkivet.harvester.HarvesterSettings;
/**
* Wraps information for an Heritrix file that should be stored in the metadata
* ARC.
*
* Defines a natural order to sort them.
*/
public class MetadataFile implements Comparable<MetadataFile> {
/**
* The available type of metadata records.
*
* @author ngiraud
*/
private enum MetadataType {
setup,
reports,
logs,
index
}
/**
* A string format that is used to build metadata URLs. Parameters are, in
* order : <ol> <li>the file type @see {@link MetadataType}</li> <li>the
* file name</li> <li>the Heritrix version</li> <li>the harvest id</li>
* <li>the job id</li> </ol>
*/
private static final String URL_FORMAT =
"metadata://netarkivet.dk/crawl/%s/%s"
+ "?heritrixVersion=%s&harvestid=%s&jobid=%s";
/**
* A pattern identifying a CDX metadata entry.
*
* @see dk.netarkivet.archive.indexserver.CDXDataCache#CDXDataCache()
*/
public static final String CDX_PATTERN =
"metadata://[^/]*/crawl/index/cdx.*";
/**
* A pattern identifying the crawl log metadata entry.
*
* @see dk.netarkivet.archive.indexserver.CrawlLogDataCache#CrawlLogDataCache()
*/
public static final String CRAWL_LOG_PATTERN =
"metadata://[^/]*/crawl/logs/crawl\\.log.*";
/**
* The pattern controlling which files in the crawl directory root should be
* stored in the metadata ARC.
*/
public static final String HERITRIX_FILE_PATTERN =
Settings.get(HarvesterSettings.METADATA_HERITRIX_FILE_PATTERN);
/**
* The pattern controlling which files in the crawl directory root should be
* stored in the metadata ARC as reports.
*/
public static final String REPORT_FILE_PATTERN =
Settings.get(HarvesterSettings.METADATA_REPORT_FILE_PATTERN);
/**
* The pattern controlling which files in the logs subdirectory of the crawl
* directory root should be stored in the metadata ARC as log files.
*/
public static final String LOG_FILE_PATTERN =
Settings.get(HarvesterSettings.METADATA_LOG_FILE_PATTERN);
/**
* The name of a domain-specific Heritrix settings file (a.k.a. override).
*/
public static final String DOMAIN_SETTINGS_FILE = "settings.xml";
private String url;
private File heritrixFile;
private MetadataType type;
/**
* Creates a metadata file and finds which metadata type it belongs to.
* First the name of a heritrixfile is tested against the reportfile
* pattern, then again the logfile pattern. If the name matches neither of
* these, it is considered a setup file.
*/
MetadataFile(
File heritrixFile,
Long harvestId,
Long jobId,
String heritrixVersion) {
this.heritrixFile = heritrixFile;
this.type = MetadataType.setup;
String name = heritrixFile.getName();
if (name.matches(REPORT_FILE_PATTERN)) {
this.type = MetadataType.reports;
this.url = makeMetadataURL(
MetadataType.reports,
heritrixFile.getName(),
harvestId, jobId, heritrixVersion);
} else if (name.matches(LOG_FILE_PATTERN)) {
this.type = MetadataType.logs;
this.url = makeMetadataURL(
MetadataType.logs,
heritrixFile.getName(),
harvestId, jobId, heritrixVersion);
} else {
this.url = makeMetadataURL(
MetadataType.setup,
heritrixFile.getName(),
harvestId, jobId, heritrixVersion);
}
}
/**
* Creates a metadata file for a domain-specific override file.
*/
MetadataFile(
File heritrixFile,
Long harvestId,
Long jobId,
String heritrixVersion,
String domain) {
this(heritrixFile, harvestId, jobId, heritrixVersion);
this.url += "&domain=" + domain;
}
/**
* Returns the metadata URL associated to this file.
* @return the metadata URL associated to this file.
*/
public String getUrl() {
return url;
}
/**
* Returns the actual file.
* @return the actual file.
*/
public File getHeritrixFile() {
return heritrixFile;
}
/** First we compare the type ordinals, then the URLs. */
public int compareTo(MetadataFile other) {
Integer thisOrdinal = this.type.ordinal();
Integer otherOrdinal = other.type.ordinal();
int ordinalCompare = thisOrdinal.compareTo(otherOrdinal);
if (ordinalCompare != 0) {
return ordinalCompare;
}
return this.url.compareTo(other.url);
}
/**
* Creates a metadata URL for this file. Metadata URLs are used to retrieve
* records in the metadata ARC file.
* @return the metadata URL for this file
*/
private String makeMetadataURL(
MetadataType type,
String name,
long harvestID,
long jobID,
String heritrixVersion) {
return String.format(
URL_FORMAT,
type.name(),
name,
heritrixVersion,
Long.toString(harvestID),
Long.toString(jobID)
);
}
}
|
package ai.elimu.rest.v2.analytics;
import ai.elimu.dao.ApplicationDao;
import ai.elimu.dao.StoryBookDao;
import ai.elimu.dao.StoryBookLearningEventDao;
import ai.elimu.model.admin.Application;
import ai.elimu.model.analytics.StoryBookLearningEvent;
import ai.elimu.model.content.StoryBook;
import ai.elimu.model.enums.Language;
import ai.elimu.model.enums.analytics.LearningEventType;
import ai.elimu.util.ConfigHelper;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Calendar;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping(value = "/rest/v2/analytics/storybook-learning-events", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class StoryBookLearningEventsRestController {
private Logger logger = Logger.getLogger(getClass());
@Autowired
private StoryBookLearningEventDao storyBookLearningEventDao;
@Autowired
private ApplicationDao applicationDao;
@Autowired
private StoryBookDao storyBookDao;
@RequestMapping(value = "/csv", method = RequestMethod.POST)
public String handleUploadCsvRequest(
@RequestParam("file") MultipartFile multipartFile,
HttpServletResponse response
) {
logger.info("handleUploadCsvRequest");
String name = multipartFile.getName();
logger.info("name: " + name);
String originalFileName = multipartFile.getOriginalFilename();
logger.info("originalFileName: " + originalFileName);
String contentType = multipartFile.getContentType();
logger.info("contentType: " + contentType);
JSONObject jsonObject = new JSONObject();
try {
byte[] bytes = multipartFile.getBytes();
logger.info("bytes.length: " + bytes.length);
// Store a backup of the original CSV file on the filesystem (in case it will be needed for debugging)
File elimuAiDir = new File(System.getProperty("user.home"), ".elimu-ai");
File languageDir = new File(elimuAiDir, "lang-" + Language.valueOf(ConfigHelper.getProperty("content.language")).toString().toLowerCase());
File analyticsDir = new File(languageDir, "analytics");
File storyBookLearningEventsDir = new File(analyticsDir, "storybook-learning-events");
storyBookLearningEventsDir.mkdirs();
File csvFile = new File(storyBookLearningEventsDir, originalFileName);
logger.info("Storing CSV file at " + csvFile);
multipartFile.transferTo(csvFile);
// Iterate each row in the CSV file
Path csvFilePath = Paths.get(csvFile.toURI());
logger.info("csvFilePath: " + csvFilePath);
Reader reader = Files.newBufferedReader(csvFilePath);
CSVFormat csvFormat = CSVFormat.DEFAULT
.withHeader(
"id", // The Room database ID
"time",
"android_id",
"package_name",
"storybook_id",
"learning_event_type"
)
.withSkipHeaderRecord();
CSVParser csvParser = new CSVParser(reader, csvFormat);
for (CSVRecord csvRecord : csvParser) {
logger.info("csvRecord: " + csvRecord);
// Convert from CSV to Java
StoryBookLearningEvent storyBookLearningEvent = new StoryBookLearningEvent();
long timeInMillis = Long.valueOf(csvRecord.get("time"));
Calendar time = Calendar.getInstance();
time.setTimeInMillis(timeInMillis);
storyBookLearningEvent.setTime(time);
String androidId = csvRecord.get("android_id");
storyBookLearningEvent.setAndroidId(androidId);
String packageName = csvRecord.get("package_name");
Language language = Language.valueOf(ConfigHelper.getProperty("content.language"));
Application application = applicationDao.readByPackageName(language, packageName);
if (application == null) {
// Return error message saying that the reporting Application has not yet been added
logger.warn("The Application " + packageName + " has not been added to the website");
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "The Application " + packageName + " has not been added to the website");
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
break;
}
storyBookLearningEvent.setApplication(application);
Long storyBookId = Long.valueOf(csvRecord.get("storybook_id"));
StoryBook storyBook = storyBookDao.read(storyBookId);
storyBookLearningEvent.setStoryBook(storyBook);
LearningEventType learningEventType = LearningEventType.valueOf(csvRecord.get("learning_event_type"));
storyBookLearningEvent.setLearningEventType(learningEventType);
// Check if the event has already been stored in the database
StoryBookLearningEvent existingStoryBookLearningEvent = storyBookLearningEventDao.read(time, androidId, application, storyBook);
logger.info("existingStoryBookLearningEvent: " + existingStoryBookLearningEvent);
if (existingStoryBookLearningEvent == null) {
// Store the event in the database
storyBookLearningEventDao.create(storyBookLearningEvent);
logger.info("Stored StoryBookLearningEvent in database with ID " + storyBookLearningEvent.getId());
jsonObject.put("result", "success");
jsonObject.put("successMessage", "The StoryBookLearningEvent was stored in the database");
} else {
// Return error message saying that the event has already been uploaded
logger.warn("The event has already been stored in the database");
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "The event has already been stored in the database");
response.setStatus(HttpStatus.CONFLICT.value());
}
}
} catch (Exception ex) {
logger.error(null, ex);
jsonObject.put("result", "error");
jsonObject.put("errorMessage", ex.getMessage());
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
}
|
package dr.app.beauti.enumTypes;
/**
* @author Alexei Drummond
* @author Walter Xie
*/
public enum PopulationSizeModelType {
CONTINUOUS_CONSTANT("Piecewise linear & constant root"),
CONTINUOUS("Piecewise linear"),
CONSTANT("Piecewise constant");
PopulationSizeModelType(String name) {
this.name = name;
}
public String toString() {
return name;
}
private final String name;
}
|
package com.alibaba.fastjson.support.spring;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public final static Charset UTF8 = Charset.forName("UTF-8");
private Charset charset = UTF8;
private SerializerFeature[] features = new SerializerFeature[0];
protected SerializeFilter[] serialzeFilters = new SerializeFilter[0];
public FastJsonHttpMessageConverter(){
super(new MediaType("application", "json", UTF8), new MediaType("application", "*+json", UTF8));
}
@Override
protected boolean supports(Class<?> clazz) {
return true;
}
public Charset getCharset() {
return this.charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public SerializerFeature[] getFeatures() {
return features;
}
public void setFeatures(SerializerFeature... features) {
this.features = features;
}
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = inputMessage.getBody();
byte[] buf = new byte[1024];
for (;;) {
int len = in.read(buf);
if (len == -1) {
break;
}
if (len > 0) {
baos.write(buf, 0, len);
}
}
byte[] bytes = baos.toByteArray();
return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(), clazz);
}
@Override
protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
OutputStream out = outputMessage.getBody();
String text = JSON.toJSONString(obj, serialzeFilters, features);
byte[] bytes = text.getBytes(charset);
out.write(bytes);
}
public void addSerializeFilter(SerializeFilter filter) {
if (filter == null) {
return;
}
SerializeFilter[] filters = new SerializeFilter[this.serialzeFilters.length + 1];
System.arraycopy(this.serialzeFilters, 0, filter, 0, this.serialzeFilters.length);
filters[filters.length - 1] = filter;
this.serialzeFilters = filters;
}
}
|
package edu.ucsb.cs56.projects.games.poker;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.lang.String;
import java.lang.System;
import java.net.URL;
import java.util.ArrayList;
public class PokerGameGui extends PokerGame{
protected JFrame
mainFrame, gameOverFrame;
protected JTextField
betTextField;
protected JButton
foldButton, betButton, checkButton, callButton, showdownButton, rulesButton, // mainFrame
overviewRulesButton, gameplayRulesButton, exampleRulesButton, //Rules Panel
gameOverButton; // gameOverFrame
protected JLabel
rulesExampleImg, rulesOverviewImg, rulesGameplayImg,
playerWinsLabel, opponentWinsLabel, // Possibly don't need these
playerChipsLabel, opponentChipsLabel,
potLabel, gameMessage, playerPrompt, // Possibly don't need these
backCardLabel1, backCardLabel2, // Not sure what these are used for
gameOverLabel; // gameOverFrame
protected JPanel
rulesPanel, rulesPart1, rulesPart2, rulesPart3,
opponentPanel, playerPanel,
centerPanel, messagePanel, optionArea,
oSubPane1, oSubPane2, oSubPane3,
pSubPane1, pSubPane2, pSubPane3,
flopPane, turnPane, riverPane, betPane,
gameOverMessage, gameOverPanel, gameOverButtonPanel; // gameOverFrame
public PokerGameGui(){
super();
}
public void layoutSubViews() {
if (!gameOver) {
Color pokerGreen = new Color(83, 157, 89);
foldButton = new JButton("FOLD");
foldButton.setEnabled(false);
foldButton.addActionListener(new foldButtonHandler());
betButton = new JButton("BET");
betButton.setEnabled(false);
betButton.addActionListener(new betButtonHandler());
betTextField = new JTextField(4);
checkButton = new JButton("CHECK");
checkButton.setEnabled(false);
checkButton.addActionListener(new checkButtonHandler());
callButton = new JButton("CALL");
callButton.setEnabled(false);
callButton.addActionListener(new callButtonHandler());
showdownButton = new JButton("SHOWDOWN");
showdownButton.addActionListener(new showdownButtonHandler());
/*putting the rules pictures into the game without adding a new window */
rulesButton = new JButton("RULES");
rulesButton.setEnabled(true);
rulesButton.addActionListener(new rulesButtonHandler());
rulesPart1 = new JPanel();
rulesPart2 = new JPanel();
rulesPart3 = new JPanel();
rulesPart1.setLayout(new BoxLayout(rulesPart1, BoxLayout.Y_AXIS));
rulesPart2.setLayout(new BoxLayout(rulesPart2, BoxLayout.Y_AXIS));
rulesPart3.setLayout(new BoxLayout(rulesPart3, BoxLayout.Y_AXIS));
rulesOverviewImg = new JLabel();
rulesGameplayImg = new JLabel();
rulesExampleImg = new JLabel();
rulesOverviewImg.setIcon(new ImageIcon("src/edu/ucsb/cs56/projects/games/poker/rules/rulesOverview.png"));
rulesGameplayImg.setIcon(new ImageIcon("src/edu/ucsb/cs56/projects/games/poker/rules/rulesGamePlay.png"));
rulesExampleImg.setIcon(new ImageIcon("src/edu/ucsb/cs56/projects/games/poker/rules/rulesExamples.png"));
rulesPart1.add(rulesOverviewImg);
rulesPart2.add(rulesGameplayImg);
rulesPart3.add(rulesExampleImg);
overviewRulesButton = new JButton("Overview");
overviewRulesButton.setEnabled(true);
overviewRulesButton.addActionListener(new overviewButtonHandler() );
gameplayRulesButton = new JButton("Gameplay");
gameplayRulesButton.setEnabled(true);
gameplayRulesButton.addActionListener(new gameplayButtonHandler() );
exampleRulesButton = new JButton("Example Hands");
exampleRulesButton.setEnabled(true);
exampleRulesButton.addActionListener(new exampleButtonHandler() );
rulesPart1.add(gameplayRulesButton);
rulesPart1.add(exampleRulesButton);
rulesPart2.add(overviewRulesButton);
rulesPart2.add(exampleRulesButton);
rulesPart3.add(overviewRulesButton);
rulesPart3.add(gameplayRulesButton);
rulesPanel = rulesPart1;
opponentPanel = new JPanel();
opponentPanel.setLayout(new BorderLayout());
oSubPane1 = new JPanel();
oSubPane1.setLayout(new BoxLayout(oSubPane1, BoxLayout.Y_AXIS));
oSubPane2 = new JPanel();
oSubPane3 = new JPanel();
oSubPane3.setLayout(new BorderLayout());
opponentChipsLabel = new JLabel(String.format("Chips: %d", opponent.getChips()));
opponentWinsLabel = new JLabel();
opponentWinsLabel.setText(String.format("Opponent wins: %d", opponent.getWins()));
playerWinsLabel = new JLabel();
playerWinsLabel.setText(String.format("Player wins: %d", player.getWins()));
oSubPane1.add(new JLabel("OPPONENT"));
oSubPane1.add(opponentChipsLabel);
oSubPane3.add(BorderLayout.NORTH, playerWinsLabel);
oSubPane3.add(BorderLayout.SOUTH, opponentWinsLabel);
opponentPanel.add(BorderLayout.WEST, oSubPane1);
opponentPanel.add(BorderLayout.CENTER, oSubPane2);
opponentPanel.add(BorderLayout.EAST, oSubPane3);
optionArea = new JPanel();
optionArea.setLayout(new BoxLayout(optionArea, BoxLayout.Y_AXIS));
optionArea.add(betButton);
optionArea.add(betTextField);
optionArea.add(callButton);
optionArea.add(checkButton);
optionArea.add(foldButton);
optionArea.add(rulesButton);
playerPanel = new JPanel();
playerPanel.setLayout(new BorderLayout());
pSubPane1 = new JPanel();
pSubPane1.setLayout(new BoxLayout(pSubPane1, BoxLayout.Y_AXIS));
pSubPane2 = new JPanel();
pSubPane3 = new JPanel();
playerChipsLabel = new JLabel(String.format("Chips: %d", player.getChips()));
pSubPane1.add(new JLabel("PLAYER"));
pSubPane1.add(playerChipsLabel);
pSubPane3.add(optionArea);
playerPanel.add(BorderLayout.WEST, pSubPane1);
playerPanel.add(BorderLayout.CENTER, pSubPane2);
playerPanel.add(BorderLayout.EAST, pSubPane3);
backCardLabel1 = new JLabel(backCardImage);
backCardLabel2 = new JLabel(backCardImage);
oSubPane2.add(backCardLabel1);
oSubPane2.add(backCardLabel2);
for (int i = 0; i < 2; i++) {
pSubPane2.add(new JLabel(getCardImage((player.getHand()).get(i))));
}
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
flopPane = new JPanel();
flopPane.add(new JLabel("Flop:"));
for (int i = 0; i < 3; i++) {
flopPane.add(new JLabel(getCardImage((table.getFlopCards()).get(i))));
}
flopPane.setVisible(false);
turnPane = new JPanel();
turnPane.add(new JLabel("Turn:"));
turnPane.add(new JLabel(getCardImage(table.getTurnCard())));
turnPane.setVisible(false);
riverPane = new JPanel();
riverPane.add(new JLabel("River:"));
riverPane.add(new JLabel(getCardImage(table.getRiverCard())));
riverPane.setVisible(false);
centerPanel.add(flopPane);
centerPanel.add(turnPane);
centerPanel.add(riverPane);
messagePanel = new JPanel();
messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.Y_AXIS));
messagePanel.add(Box.createRigidArea(new Dimension(0, 20)));
potLabel = new JLabel();
potLabel.setText(String.format("Pot: %d", pot));
messagePanel.add(potLabel);
messagePanel.add(Box.createRigidArea(new Dimension(10, 20)));
gameMessage = new JLabel(message);
messagePanel.add(Box.createRigidArea(new Dimension(10, 20)));
messagePanel.add(gameMessage);
playerPrompt = new JLabel(prompt);
messagePanel.add(playerPrompt);
messagePanel.add(Box.createRigidArea(new Dimension(10, 0)));
showdownButton.setVisible(false);
messagePanel.add(showdownButton);
messagePanel.add(Box.createRigidArea(new Dimension(0, 20)));
oSubPane1.setBackground(pokerGreen);
oSubPane2.setBackground(pokerGreen);
oSubPane3.setBackground(pokerGreen);
pSubPane1.setBackground(pokerGreen);
pSubPane2.setBackground(pokerGreen);
pSubPane3.setBackground(pokerGreen);
messagePanel.setBackground(pokerGreen);
centerPanel.setBackground(pokerGreen);
optionArea.setBackground(pokerGreen);
flopPane.setBackground(pokerGreen);
turnPane.setBackground(pokerGreen);
riverPane.setBackground(pokerGreen);
mainFrame = new JFrame("Poker Game");
mainFrame.setSize(new Dimension(1000, 600));
mainFrame.setLayout(new BorderLayout() );
mainFrame.setResizable(false);
mainFrame.setLocation(250, 250);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getContentPane().add(BorderLayout.NORTH, opponentPanel);
mainFrame.getContentPane().add(BorderLayout.SOUTH, playerPanel);
mainFrame.getContentPane().add(BorderLayout.CENTER, centerPanel);
mainFrame.getContentPane().add(BorderLayout.EAST, messagePanel);
mainFrame.getContentPane().add(BorderLayout.WEST, rulesPanel);
mainFrame.setVisible(true);
// mainFramee.add(BorderLayout.CENTER, mainFrame);
// mainFramee.getContentPane().add(BorderLayout.WEST, rulesPanel);
}
}
/**
* Method that updates the panels in the frame based on step
*/
public void updateFrame() {
if (step == Step.FLOP) {
flopPane.setVisible(true);
} else if (step == Step.TURN) {
turnPane.setVisible(true);
} else if (step == Step.RIVER) {
riverPane.setVisible(true);
}
gameMessage.setText(message);
playerPrompt.setText(prompt);
potLabel.setText(String.format("Pot: %d", pot));
opponentChipsLabel.setText(String.format("Chips: %d", opponent.getChips()));
playerChipsLabel.setText(String.format("Chips: %d", player.getChips()));
opponentPanel.revalidate();
playerPanel.revalidate();
centerPanel.revalidate();
}
/**
* Enables and disables buttons on the screen depending on turn and step
*/
protected void controlButtons() {
if (step == Step.SHOWDOWN) {
betButton.setEnabled(false);
betTextField.setEnabled(false);
checkButton.setEnabled(false);
callButton.setEnabled(false);
foldButton.setEnabled(false);
showdownButton.setVisible(true);
rulesButton.setEnabled(true);
}
else if (turn == Turn.PLAYER && responding) {
betButton.setEnabled(false);
betTextField.setEnabled(false);
checkButton.setEnabled(false);
callButton.setEnabled(true);
foldButton.setEnabled(true);
rulesButton.setEnabled(true);
} else if (turn == Turn.PLAYER) {
betButton.setEnabled(true);
betTextField.setEnabled(true);
checkButton.setEnabled(true);
callButton.setEnabled(false);
foldButton.setEnabled(true);
rulesButton.setEnabled(true);
} else {
betButton.setEnabled(false);
betTextField.setEnabled(false);
checkButton.setEnabled(false);
callButton.setEnabled(false);
foldButton.setEnabled(false);
rulesButton.setEnabled(true);
}
updateFrame();
}
/**
* Inner class that handles the betButton using ActionListener
*/
protected class betButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String inputText = betTextField.getText();
if (!inputText.equals("")) {
bet = Integer.parseInt(inputText);
if (bet<=0) {
prompt = "Enter a valid bet!";
updateFrame();
}
else if ((player.getChips()-bet>=0) && (opponent.getChips()-bet>=0)) {
betTextField.setText("");
pot += bet;
player.bet(bet);
message = "Opponent waiting for turn.";
prompt = "Player bets " + bet + ".";
betButton.setEnabled(false);
betTextField.setEnabled(false);
checkButton.setEnabled(false);
callButton.setEnabled(false);
foldButton.setEnabled(false);
responding = true;
checkPassTurnUpdate();
updateFrame();
}
else {
prompt = "Not enough chips!";
updateFrame();
}
}
else {
prompt = "Enter a number of chips to bet!";
updateFrame();
}
}
}
/**
* Inner class that handles the checkButton using ActionListener
*/
protected class checkButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
bet = 0;
message = "Opponent waiting to deal.";
prompt = "Player checks.";
betButton.setEnabled(false);
betTextField.setEnabled(false);
checkButton.setEnabled(false);
callButton.setEnabled(false);
foldButton.setEnabled(false);
rulesButton.setEnabled(true);
checkPassTurnUpdate();
updateFrame();
}
}
/**
* Inner class that handles the foldButton using ActionListener
*/
protected class foldButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
message = "Opponent waiting for turn.";
prompt = "You fold.";
player.foldHand();
}
}
/**
* Inner class that handles the callButton using ActionListener
*/
protected class callButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
pot += bet;
player.bet(bet);
message = "You call.";
prompt = "Next turn: ";
responding = false;
callButton.setEnabled(false);
foldButton.setEnabled(false);
changeTurn();
updateFrame();
}
}
/**
* Inner class that handles the showdownButton using ActionListener
*/
protected class showdownButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
determineWinner();
collectPot();
showWinnerAlert();
}
}
protected class rulesButtonHandler implements ActionListener {// rules
public void actionPerformed(ActionEvent e) {
// mainFrame.setSize(1000, 1000);
//rulesPanel.setVisible(!rulesPanel.isVisible() );
if(!rulesPanel.isVisible()){
rulesPanel.setVisible(true)
rulesPart1.setVisible(true);
rulesPanel = rulesPart1;
}
else
rulesPanel.setVisible(false);
}
}
protected class overviewButtonHandler implements ActionListener {// rules
public void actionPerformed(ActionEvent e) {
rulesPart1.setVisible(true);
rulesPart2.setVisible(false);
rulesPart3.setVisible(false);
rulesPanel = rulesPart1;
}
}
protected class gameplayButtonHandler implements ActionListener {// rules
public void actionPerformed(ActionEvent e) {
rulesPart1.setVisible(false);
rulesPart2.setVisible(true);
rulesPart3.setVisible(false);
rulesPanel = rulesPart2;
}
}
protected class exampleButtonHandler implements ActionListener {// rules
public void actionPerformed(ActionEvent e) {
// mainFrame.setSize(1000, 1000);
rulesPart1.setVisible(false);
rulesPart2.setVisible(false);
rulesPart3.setVisible(true);
rulesPanel = rulesPart3;
}
}
/**
* Function that puts up a Game Over Frame that can take us back to the Main Screen
*/
protected void gameOver(String label) {
gameOverFrame = new JFrame();
gameOverFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameOverFrame.setBackground(Color.red);
gameOverMessage = new JPanel();
gameOverMessage.setBackground(Color.red);
gameOverButtonPanel = new JPanel();
gameOverButtonPanel.setBackground(Color.red);
gameOverLabel = new JLabel(label);
gameOverButton = new JButton("Back to Main Menu");
gameOverButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
gameOverFrame.setVisible(false);
PokerMain restart = new PokerMain();
restart.go();
}
});
gameOverMessage.add(gameOverLabel);
gameOverButtonPanel.add(gameOverButton);
gameOverFrame.setSize(300, 200);
gameOverFrame.setResizable(false);
gameOverFrame.setLocation(250, 250);
gameOverFrame.getContentPane().add(BorderLayout.NORTH, gameOverMessage);
gameOverFrame.getContentPane().add(BorderLayout.SOUTH, gameOverButtonPanel);
gameOverFrame.pack();
gameOverFrame.setVisible(true);
mainFrame.dispose();
}
}
|
package com.lordmau5.ffs.network.handlers.server;
import com.lordmau5.ffs.network.NetworkHandler;
import com.lordmau5.ffs.network.ffsPacket;
import com.lordmau5.ffs.tile.TileEntityValve;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public class UpdateAutoOutput_Server extends SimpleChannelInboundHandler<ffsPacket.Server.UpdateAutoOutput> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ffsPacket.Server.UpdateAutoOutput msg) throws Exception{
World world = NetworkHandler.getPlayer(ctx).worldObj;
if(world != null) {
TileEntity tile = world.getTileEntity(msg.x, msg.y, msg.z);
if(tile != null && tile instanceof TileEntityValve) {
((TileEntityValve) tile).setAutoOutput(msg.autoOutput);
}
}
}
}
|
package com.skelril.skree.content.zone.group.catacombs;
import com.flowpowered.math.vector.Vector3i;
import com.skelril.nitro.Clause;
import com.skelril.nitro.probability.Probability;
import com.skelril.openboss.Boss;
import com.skelril.openboss.BossManager;
import com.skelril.openboss.EntityDetail;
import com.skelril.openboss.Instruction;
import com.skelril.openboss.condition.BindCondition;
import com.skelril.openboss.condition.DamageCondition;
import com.skelril.openboss.condition.DamagedCondition;
import com.skelril.skree.SkreePlugin;
import com.skelril.skree.content.zone.LegacyZoneBase;
import com.skelril.skree.content.zone.group.catacombs.instruction.CatacombsHealthInstruction;
import com.skelril.skree.content.zone.group.catacombs.instruction.bossmove.*;
import com.skelril.skree.service.HighScoreService;
import com.skelril.skree.service.internal.highscore.ScoreTypes;
import com.skelril.skree.service.internal.zone.ZoneRegion;
import com.skelril.skree.service.internal.zone.ZoneStatus;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.living.monster.Zombie;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.title.Title;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import static com.skelril.skree.service.internal.zone.PlayerClassifier.PARTICIPANT;
import static com.skelril.skree.service.internal.zone.PlayerClassifier.SPECTATOR;
public class CatacombsInstance extends LegacyZoneBase implements Runnable {
private final BossManager<Zombie, CatacombsBossDetail> bossManager;
private final BossManager<Zombie, CatacombsBossDetail> waveMobManager;
private boolean phantomClockUsed = false;
private int ticks = 0;
private int wave = 0;
private Location<World> entryPoint;
public CatacombsInstance(ZoneRegion region, BossManager<Zombie, CatacombsBossDetail> bossManager, BossManager<Zombie, CatacombsBossDetail> waveMobManager) {
super(region);
this.bossManager = bossManager;
this.waveMobManager = waveMobManager;
}
@Override
public boolean init() {
setUp();
remove();
return true;
}
@Override
public void forceEnd() {
remove(getPlayers(PARTICIPANT));
remove();
}
@Override
public Clause<Player, ZoneStatus> add(Player player) {
if (wave > 0) {
return new Clause<>(player, ZoneStatus.NO_REJOIN);
}
player.setLocation(entryPoint);
return new Clause<>(player, ZoneStatus.ADDED);
}
private void setUp() {
Vector3i min = getRegion().getMinimumPoint();
this.entryPoint = new Location<>(getRegion().getExtent(), min.getX() + 17.5, min.getY() + 2, min.getZ() + 58.5);
Task.builder().execute(this::checkedSpawnWave).delay(5, TimeUnit.SECONDS).submit(SkreePlugin.inst());
}
@Override
public void run() {
if (isEmpty()) {
expire();
return;
}
// This shouldn't be necessary, however, there seems to be an
// edge case where it is, so it's preferable to cover it rather
// than ignore the issue
if (++ticks % 60 == 0) {
checkedSpawnWave();
}
}
public void checkedSpawnWave() {
if (!hasActiveMobs()) {
spawnWave();
}
}
public boolean hasActiveMobs() {
for (Zombie zombie : getContained(Zombie.class)) {
if (waveMobManager.lookup(zombie.getUniqueId()).isPresent()) {
return true;
}
if (bossManager.lookup(zombie.getUniqueId()).isPresent()) {
return true;
}
}
return false;
}
public int getSpawnCount(int wave) {
return (int) (Math.pow(wave, 2) + (wave * 3)) / 2;
}
public int getSpeed() {
if ((wave + 1) % 5 == 0) {
return 1;
}
return phantomClockUsed ? 2 : 1;
}
public boolean hasUsedPhantomClock() {
return phantomClockUsed;
}
public void setUsedPhantomClock(boolean phantomClockUsed) {
this.phantomClockUsed = phantomClockUsed;
}
public void spawnWave() {
wave += getSpeed();
if (wave % 5 == 0) {
spawnBossWave();
} else {
spawnNormalWave();
}
for (Player player : getPlayers(SPECTATOR)) {
player.sendTitle(
Title.builder()
.title(Text.of(TextColors.RED, "Wave"))
.subtitle(Text.of(TextColors.RED, wave))
.fadeIn(20)
.fadeOut(20)
.build()
);
}
Optional<HighScoreService> optHighScores = Sponge.getServiceManager().provide(HighScoreService.class);
if (optHighScores.isPresent()) {
HighScoreService highScores = optHighScores.get();
for (Player player : getPlayers(PARTICIPANT)) {
highScores.update(player, ScoreTypes.HIGHEST_CATACOMB_WAVE, wave);
}
}
}
private void spawnBossWave() {
Zombie zombie = spawnZombie(entryPoint);
Boss<Zombie, CatacombsBossDetail> boss = new Boss<>(zombie, new CatacombsBossDetail(this, wave));
List<Instruction<DamageCondition, Boss<Zombie, CatacombsBossDetail>>> damageProcessor = boss.getDamageProcessor();
if (Probability.getChance(2)) {
damageProcessor.add(new ThorAttack());
}
if (Probability.getChance(2)) {
damageProcessor.add(new SoulReaper());
}
List<Instruction<DamagedCondition, Boss<Zombie, CatacombsBossDetail>>> damagedProcessor = boss.getDamagedProcessor();
if (Probability.getChance(4)) {
damagedProcessor.add(new BlipDefense());
}
if (Probability.getChance(3)) {
damagedProcessor.add(new ExplosiveArrowBarrage() {
@Override
public boolean activate(EntityDetail detail) {
return Probability.getChance(12);
}
});
}
if (Probability.getChance(2)) {
damagedProcessor.add(new DeathMark());
}
if (Probability.getChance(2)) {
damagedProcessor.add(new CatacombsDamageNearby());
}
if (Probability.getChance(2)) {
damagedProcessor.add(new UndeadMinionRetaliation(Probability.getRangedRandom(12, 25)));
}
bossManager.bind(boss);
}
private void spawnNormalWave() {
Vector3i min = getRegion().getMinimumPoint();
Vector3i max = getRegion().getMaximumPoint();
int minX = min.getX();
int minZ = min.getZ();
int maxX = max.getX();
int maxZ = max.getZ();
final int y = min.getY() + 2;
int needed = getSpawnCount(wave);
for (int i = needed; i > 0; --i) {
int x;
int z;
BlockType type;
BlockType aboveType;
do {
x = Probability.getRangedRandom(minX, maxX);
z = Probability.getRangedRandom(minZ, maxZ);
type = getRegion().getExtent().getBlockType(x, y, z);
aboveType = getRegion().getExtent().getBlockType(x, y + 1, z);
} while (type != BlockTypes.AIR || aboveType != BlockTypes.AIR);
spawnWaveMob(new Location<>(getRegion().getExtent(), x + .5, y, z + .5));
}
}
public void spawnWaveMob(Location<World> loc) {
Boss<Zombie, CatacombsBossDetail> waveMob;
if (Probability.getChance(25)) {
waveMob = spawnStrong(loc);
} else {
waveMob = spawnNormal(loc);
}
waveMobManager.bind(waveMob);
}
private Zombie spawnZombie(Location<World> loc) {
Zombie zombie = (Zombie) loc.getExtent().createEntity(EntityTypes.ZOMBIE, loc.getPosition());
loc.getExtent().spawnEntity(zombie, Cause.source(SpawnCause.builder().type(SpawnTypes.PLUGIN).build()).build());
return zombie;
}
private Boss<Zombie, CatacombsBossDetail> spawnStrong(Location<World> loc) {
Zombie zombie = spawnZombie(loc);
Boss<Zombie, CatacombsBossDetail> boss = new Boss<>(zombie, new CatacombsBossDetail(this, wave * 2));
List<Instruction<BindCondition, Boss<Zombie, CatacombsBossDetail>>> bindProcessor = boss.getBindProcessor();
bindProcessor.add(new CatacombsHealthInstruction(25));
bindProcessor.add(new NamedBindInstruction<>("Wrathful Zombie"));
return boss;
}
private Boss<Zombie, CatacombsBossDetail> spawnNormal(Location<World> loc) {
Zombie zombie = spawnZombie(loc);
Boss<Zombie, CatacombsBossDetail> boss = new Boss<>(zombie, new CatacombsBossDetail(this, wave));
List<Instruction<BindCondition, Boss<Zombie, CatacombsBossDetail>>> bindProcessor = boss.getBindProcessor();
bindProcessor.add(new CatacombsHealthInstruction(20));
bindProcessor.add(new NamedBindInstruction<>("Guardian Zombie"));
return boss;
}
}
|
package com.tang.intellij.lua.editor.completion;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.parser.GeneratedParserUtilBase;
import com.intellij.openapi.project.Project;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.impl.source.tree.TreeUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.ProcessingContext;
import com.intellij.util.containers.HashSet;
import com.tang.intellij.lua.highlighting.LuaSyntaxHighlighter;
import com.tang.intellij.lua.lang.LuaIcons;
import com.tang.intellij.lua.lang.LuaLanguage;
import com.tang.intellij.lua.lang.type.LuaTypeSet;
import com.tang.intellij.lua.psi.*;
import com.tang.intellij.lua.psi.index.LuaGlobalFieldIndex;
import com.tang.intellij.lua.psi.index.LuaGlobalFuncIndex;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import static com.intellij.patterns.PlatformPatterns.psiElement;
public class LuaCompletionContributor extends CompletionContributor {
private static final PsiElementPattern.Capture<PsiElement> SHOW_CLASS_METHOD = psiElement().afterLeaf(
psiElement().withText(":").withParent(LuaCallExpr.class));
private static final PsiElementPattern.Capture<PsiElement> SHOW_FIELD = psiElement().afterLeaf(
psiElement().withText(".").withParent(LuaIndexExpr.class));
private static final PsiElementPattern.Capture<PsiElement> IN_COMMENT = psiElement().inside(psiElement().withElementType(LuaTypes.DOC_COMMENT));
public LuaCompletionContributor() {
extend(CompletionType.BASIC, SHOW_CLASS_METHOD, new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement element = completionParameters.getOriginalFile().findElementAt(completionParameters.getOffset() - 1);
if (element != null) {
LuaCallExpr callExpr = (LuaCallExpr) element.getParent();
LuaTypeSet luaTypeSet = callExpr.guessPrefixType();
if (luaTypeSet != null) {
luaTypeSet.getTypes().forEach(luaType -> luaType.addMethodCompletions(completionParameters, completionResultSet));
}
}
//words in file
suggestWordsInFile(completionParameters, processingContext, completionResultSet);
}
});
extend(CompletionType.BASIC, SHOW_FIELD, new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
PsiElement element = completionParameters.getOriginalFile().findElementAt(completionParameters.getOffset() - 1);
if (element != null) {
LuaIndexExpr indexExpr = (LuaIndexExpr) element.getParent();
LuaTypeSet prefixTypeSet = indexExpr.guessPrefixType();
if (prefixTypeSet != null) {
prefixTypeSet.getTypes().forEach(luaType -> luaType.addFieldCompletions(completionParameters, completionResultSet));
}
}
//words in file
suggestWordsInFile(completionParameters, processingContext, completionResultSet);
}
});
//,local,local
extend(CompletionType.BASIC, psiElement().inside(LuaFile.class).andNot(SHOW_CLASS_METHOD).andNot(SHOW_FIELD).andNot(IN_COMMENT), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
//local
PsiElement cur = completionParameters.getOriginalFile().findElementAt(completionParameters.getOffset() - 1);
LuaPsiTreeUtil.walkUpLocalNameDef(cur, nameDef -> {
LookupElementBuilder elementBuilder = LookupElementBuilder.create(nameDef.getText())
.withIcon(LuaIcons.LOCAL_VAR);
completionResultSet.addElement(elementBuilder);
return true;
});
LuaPsiTreeUtil.walkUpLocalFuncDef(cur, nameDef -> {
LookupElementBuilder elementBuilder = LookupElementBuilder.create(nameDef.getText())
.withIcon(LuaIcons.LOCAL_FUNCTION);
completionResultSet.addElement(elementBuilder);
return true;
});
//global functions
Project project = completionParameters.getOriginalFile().getProject();
Collection<String> list = LuaGlobalFuncIndex.getInstance().getAllKeys(project);
for (String name : list) {
LookupElementBuilder elementBuilder = LookupElementBuilder.create(name)
.withTypeText("Global Func")
.withIcon(LuaIcons.GLOBAL_FUNCTION);
completionResultSet.addElement(elementBuilder);
}
//global fields
Collection<String> allGlobalFieldNames = LuaGlobalFieldIndex.getInstance().getAllKeys(project);
for (String name : allGlobalFieldNames) {
completionResultSet.addElement(LookupElementBuilder.create(name).withIcon(LuaIcons.GLOBAL_FIELD));
}
//key words
TokenSet keywords = TokenSet.orSet(LuaSyntaxHighlighter.KEYWORD_TOKENS, LuaSyntaxHighlighter.PRIMITIVE_TYPE_SET);
keywords = TokenSet.orSet(TokenSet.create(LuaTypes.SELF), keywords);
for (IElementType keyWordToken : keywords.getTypes()) {
completionResultSet.addElement(LookupElementBuilder.create(keyWordToken));
}
//words in file
suggestWordsInFile(completionParameters, processingContext, completionResultSet);
}
});
}
private static void suggestWordsInFile(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
HashSet<String> wordsInFileSet = new HashSet<>();
PsiFile file = completionParameters.getOriginalFile();
file.acceptChildren(new LuaVisitor() {
@Override
public void visitPsiElement(@NotNull LuaPsiElement o) {
o.acceptChildren(this);
}
@Override
public void visitElement(PsiElement element) {
if (element.getNode().getElementType() == LuaTypes.ID && element.getTextLength() > 2) {
wordsInFileSet.add(element.getText());
}
super.visitElement(element);
}
});
for (String s : wordsInFileSet) {
completionResultSet.addElement(PrioritizedLookupElement.withPriority(LookupElementBuilder
.create(s)
.withIcon(LuaIcons.WORD)
.withTypeText("Word In File")
, -1));
}
}
private static void suggestKeywords(PsiElement position) {
GeneratedParserUtilBase.CompletionState state = new GeneratedParserUtilBase.CompletionState(8) {
@Override
public String convertItem(Object o) {
if (o instanceof LuaTokenType) {
LuaTokenType tokenType = (LuaTokenType) o;
return tokenType.toString();
}
// we do not have other keywords
return o instanceof String? (String)o : null;
}
};
PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(position.getProject());
PsiFile file = psiFileFactory.createFileFromText("a.lua", LuaLanguage.INSTANCE, "local ", true, false);
file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state);
TreeUtil.ensureParsed(file.getNode());
System.out.println("
}
}
|
package com.thinkaurelius.titan.graphdb.loadingstatus;
import cern.colt.map.AbstractIntIntMap;
import cern.colt.map.OpenIntIntHashMap;
import com.thinkaurelius.titan.core.TitanType;
import com.thinkaurelius.titan.graphdb.query.QueryUtil;
import com.thinkaurelius.titan.graphdb.query.InternalTitanQuery;
import java.util.HashMap;
import java.util.Map;
public class BasicLoadingStatus implements LoadingStatus {
private Map<TitanType,Byte> loadedTypes;
private byte allLoadedDirsIndex;
private AbstractIntIntMap groups;
BasicLoadingStatus() {
allLoadedDirsIndex = 0;
loadedTypes = null;
groups = null;
}
@Override
public boolean hasLoadedEdges(InternalTitanQuery query) {
if (DirectionTypeEncoder.hasAllCovered(allLoadedDirsIndex, query)) return true;
if (groups!=null && (query.hasGroupCondition() || query.hasEdgeTypeCondition())) {
short groupid=-1;
if (query.hasGroupCondition()) groupid = query.getGroupCondition().getID();
else if (query.hasEdgeTypeCondition()) groupid = query.getTypeCondition().getGroup().getID();
assert groupid>=0;
if (DirectionTypeEncoder.hasAllCovered((byte)groups.get(groupid), query)) return true;
}
if (loadedTypes!=null && query.hasEdgeTypeCondition()) {
TitanType type = query.getTypeCondition();
Byte code = loadedTypes.get(type);
if (code!=null && DirectionTypeEncoder.hasAllCovered(code.byteValue(), query)) return true;
}
return false;
}
@Override
public LoadingStatus loadedEdges(InternalTitanQuery query) {
if (query.hasEdgeTypeCondition()) {
if (!QueryUtil.hasFirstKeyConstraint(query)) {
TitanType type = query.getTypeCondition();
if (loadedTypes==null) loadedTypes = new HashMap<TitanType,Byte>();
byte code = 0;
Byte tmp = loadedTypes.get(type);
if (tmp!=null) code = tmp.byteValue();
code = DirectionTypeEncoder.loaded(code, query);
loadedTypes.put(type, Byte.valueOf(code));
}
} else if (query.hasGroupCondition()) {
short groupid = query.getGroupCondition().getID();
if (groups==null) groups=new OpenIntIntHashMap(5);
byte code = (byte)groups.get(groupid);
code = DirectionTypeEncoder.loaded(code, query);
groups.put(groupid, code);
} else {
allLoadedDirsIndex=DirectionTypeEncoder.loaded(allLoadedDirsIndex,query);
}
return this;
}
}
|
package com.vaguehope.morrigan.model.media.internal.db.mmdb;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.vaguehope.morrigan.model.db.IDbColumn;
import com.vaguehope.morrigan.model.media.IMediaItemStorageLayer.SortDirection;
import com.vaguehope.morrigan.model.media.IMixedMediaItem;
import com.vaguehope.morrigan.model.media.IMixedMediaItem.MediaType;
import com.vaguehope.morrigan.model.media.internal.db.SqliteHelper;
import com.vaguehope.morrigan.util.QuerySplitter;
import com.vaguehope.morrigan.util.QuoteRemover;
class SearchParser {
private static final int MAX_SEARCH_TERMS = 20;
private static final String _SQL_MEDIAFILES_SELECT =
"SELECT id,file,type,md5,sha1,added,modified,enabled,enabledmodified,missing,remloc,startcnt,endcnt,lastplay,duration,width,height"
+ " FROM tbl_mediafiles";
private static final String _SQL_WHERE = " WHERE";
private static final String _SQL_AND = " AND";
private static final String _SQL_OR = " OR";
private static final String _SQL_MEDIAFILES_WHERTYPE =
" type=?";
private static final String _SQL_MEDIAFILES_WHERES_FILE =
" (file LIKE ? ESCAPE ?)";
private static final String _SQL_MEDIAFILES_WHERES_NOT_FILE =
" NOT " + _SQL_MEDIAFILES_WHERES_FILE;
private static final String _SQL_MEDIAFILES_WHERES_TAG =
" (id IN (SELECT mf_id FROM tbl_tags WHERE tag LIKE ? ESCAPE ? AND (deleted IS NULL OR deleted!=1)))";
private static final String _SQL_MEDIAFILES_WHERES_NOT_TAG =
" NOT " + _SQL_MEDIAFILES_WHERES_TAG;
private static final String _SQL_MEDIAFILES_WHERES_FILEORTAG =
" (file LIKE ? ESCAPE ? OR id IN (SELECT mf_id FROM tbl_tags WHERE tag LIKE ? ESCAPE ? AND (deleted IS NULL OR deleted!=1)))";
private static final String _SQL_MEDIAFILES_WHERENOTMISSING =
" (missing<>1 OR missing is NULL)";
private static final String _SQL_MEDIAFILES_WHEREENABLED =
" (enabled<>0 OR enabled is NULL)";
private static final String _SQL_MEDIAFILES_SEARCHORDERBY =
" ORDER BY lastplay DESC, endcnt DESC, startcnt DESC, file COLLATE NOCASE ASC";
private SearchParser () {
throw new AssertionError();
}
/**
* Excludes missing and disabled. Ordered by lastplay, endcnt, startcnt,
* file.
*/
public static Search parseSearch (final MediaType mediaType, final String allTerms) {
return parseSearch(mediaType, null, null, true, true, allTerms);
}
public static Search parseSearch (final MediaType mediaType, final String allTerms,
final IDbColumn[] sort, final SortDirection[] direction) {
return parseSearch(mediaType, sort, direction, true, true, allTerms);
}
public static Search parseSearch (final MediaType mediaType,
final IDbColumn[] sort, final SortDirection[] direction,
final boolean excludeMissing, final boolean excludeDisabled) {
return parseSearch(mediaType, sort, direction, excludeMissing, excludeDisabled, null);
}
public static Search parseSearch (final MediaType mediaType,
final IDbColumn[] sorts, final SortDirection[] directions,
final boolean excludeMissing, final boolean excludeDisabled,
final String allTerms) {
if (sorts == null ^ directions == null) throw new IllegalArgumentException("Must specify both or neith of sort and direction.");
if (sorts != null && directions != null && sorts.length != directions.length) throw new IllegalArgumentException("Sorts and directions must be same length.");
final StringBuilder sql = new StringBuilder(_SQL_MEDIAFILES_SELECT);
final List<String> terms = QuerySplitter.split(allTerms, MAX_SEARCH_TERMS);
appendWhere(sql, mediaType, excludeMissing, excludeDisabled, terms);
if (sorts != null && directions != null && sorts.length > 0 && directions.length > 0) {
sql.append(" ORDER BY ");
for (int i = 0; i < sorts.length; i++) {
if (i > 0) sql.append(",");
sql.append(sorts[i].getName()).append(directions[i].getSql());
}
}
else {
sql.append(_SQL_MEDIAFILES_SEARCHORDERBY);
}
sql.append(";");
return new Search(sql.toString(), mediaType, terms);
}
private static void appendWhere (final StringBuilder sql, final MediaType mediaType, final boolean excludeMissing,
final boolean excludeDisabled, final List<String> terms) {
if (mediaType == MediaType.UNKNOWN && terms.size() < 1 && !excludeMissing && !excludeDisabled) return;
sql.append(_SQL_WHERE);
boolean needAnd = false;
if (mediaType != MediaType.UNKNOWN) {
if (needAnd) sql.append(_SQL_AND);
needAnd = true;
sql.append(_SQL_MEDIAFILES_WHERTYPE);
}
if (terms.size() > 0) {
if (needAnd) sql.append(_SQL_AND);
needAnd = true;
sql.append(" ( ");
int openBrackets = 0;
for (int i = 0; i < terms.size(); i++) {
final String term = terms.get(i);
final String prevTerm = i > 0 ? terms.get(i - 1) : null;
final String nextTerm = i < terms.size() - 1 ? terms.get(i + 1) : null;
if ("OR".equals(term)) {
if (prevTerm == null || nextTerm == null) continue; // Ignore leading and trailing.
if ("OR".equals(prevTerm)) continue;
if ("AND".equals(prevTerm)) continue;
if ("(".equals(prevTerm)) continue;
if (")".equals(nextTerm)) continue;
sql.append(_SQL_OR);
continue;
}
if ("AND".equals(term)) {
if (prevTerm == null || nextTerm == null) continue; // Ignore leading and trailing.
if ("OR".equals(prevTerm)) continue;
if ("AND".equals(prevTerm)) continue;
if ("(".equals(prevTerm)) continue;
if (")".equals(nextTerm)) continue;
sql.append(_SQL_AND);
continue;
}
if (")".equals(term)) {
if (openBrackets > 0) {
sql.append(" ) ");
openBrackets -= 1;
}
continue;
}
if (i > 0) {
// Not the first term and not following OR or AND.
if (!"OR".equals(prevTerm) && !"AND".equals(prevTerm) && !"(".equals(prevTerm)) {
sql.append(_SQL_AND);
}
}
if ("(".equals(term)) {
sql.append(" ( ");
openBrackets += 1;
}
else if (isFileMatchPartial(term)) {
sql.append(_SQL_MEDIAFILES_WHERES_FILE);
}
else if (isFileNotMatchPartial(term)) {
sql.append(_SQL_MEDIAFILES_WHERES_NOT_FILE);
}
else if (isTagMatchPartial(term) || isTagMatchExact(term)) {
sql.append(_SQL_MEDIAFILES_WHERES_TAG);
}
else if (isTagNotMatchPartial(term) || isTagNotMatchExact(term)) {
sql.append(_SQL_MEDIAFILES_WHERES_NOT_TAG);
}
else {
sql.append(_SQL_MEDIAFILES_WHERES_FILEORTAG);
}
}
// Tidy any unclosed brackets.
for (int i = 0; i < openBrackets; i++) {
sql.append(" ) ");
}
sql.append(" ) ");
}
if (excludeMissing) {
if (needAnd) sql.append(_SQL_AND);
needAnd = true;
sql.append(_SQL_MEDIAFILES_WHERENOTMISSING);
}
if (excludeDisabled) {
if (needAnd) sql.append(_SQL_AND);
needAnd = true;
sql.append(_SQL_MEDIAFILES_WHEREENABLED);
}
}
protected static boolean isFileMatchPartial (final String term) {
return term.startsWith("f~") || term.startsWith("F~");
}
protected static boolean isFileNotMatchPartial (final String term) {
return term.startsWith("-f~") || term.startsWith("-F~");
}
protected static boolean isTagMatchPartial (final String term) {
return term.startsWith("t~") || term.startsWith("T~");
}
protected static boolean isTagNotMatchPartial (final String term) {
return term.startsWith("-t~") || term.startsWith("-T~");
}
protected static boolean isTagMatchExact (final String term) {
return term.startsWith("t=") || term.startsWith("T=");
}
protected static boolean isTagNotMatchExact (final String term) {
return term.startsWith("-t=") || term.startsWith("-T=");
}
protected static String removeMatchOperator (final String term) {
int x = term.indexOf('=');
if (x < 0) x = term.indexOf('~');
if (x < 0) throw new IllegalArgumentException("term does not contain '=' or '~': " + term);
return term.substring(x + 1);
}
protected static String anchoredOrWildcardEnds (final String term) {
String ret = term;
if (ret.startsWith("^")) {
ret = ret.substring(1);
}
else {
ret = "%" + ret;
}
if (ret.endsWith("$")) {
ret = ret.substring(0, ret.length() - 1);
}
else {
ret = ret + "%";
}
return ret;
}
public static class Search {
private final String sql;
private final MediaType mediaType;
private final List<String> terms;
public Search (final String sql, final MediaType mediaType, final List<String> terms) {
this.sql = sql;
this.mediaType = mediaType;
this.terms = terms;
}
private PreparedStatement prepare (final Connection con) throws SQLException {
try {
return con.prepareStatement(this.sql);
}
catch (final SQLException e) {
throw new SQLException("Failed to compile query (sql='" + this.sql + "').", e);
}
}
public List<IMixedMediaItem> execute (final Connection con, final MixedMediaItemFactory itemFactory) throws SQLException {
return execute(con, itemFactory, -1);
}
public List<IMixedMediaItem> execute (final Connection con, final MixedMediaItemFactory itemFactory, final int maxResults) throws SQLException {
final PreparedStatement ps = prepare(con);
try {
int parmIn = 1;
if (this.mediaType != MediaType.UNKNOWN) ps.setInt(parmIn++, this.mediaType.getN());
for (final String term : this.terms) {
if ("OR".equals(term)) continue;
if ("AND".equals(term)) continue;
if ("(".equals(term)) continue;
if (")".equals(term)) continue;
if (isFileMatchPartial(term) || isFileNotMatchPartial(term)
|| isTagMatchPartial(term) || isTagNotMatchPartial(term)) {
ps.setString(parmIn++, anchoredOrWildcardEnds(SqliteHelper.escapeSearch(QuoteRemover.unquote(removeMatchOperator(term)))));
ps.setString(parmIn++, SqliteHelper.SEARCH_ESC);
}
else if (isTagMatchExact(term) || isTagNotMatchExact(term)) {
ps.setString(parmIn++, SqliteHelper.escapeSearch(QuoteRemover.unquote(removeMatchOperator(term))));
ps.setString(parmIn++, SqliteHelper.SEARCH_ESC);
}
else {
final String escapedTerm = SqliteHelper.escapeSearch(QuoteRemover.unquote(term));
ps.setString(parmIn++, "%" + escapedTerm + "%");
ps.setString(parmIn++, SqliteHelper.SEARCH_ESC);
ps.setString(parmIn++, "%" + escapedTerm + "%");
ps.setString(parmIn++, SqliteHelper.SEARCH_ESC);
}
}
if (maxResults > 0) ps.setMaxRows(maxResults);
final ResultSet rs = ps.executeQuery();
try {
return MixedMediaSqliteLayerInner.local_parseRecordSet(rs, itemFactory);
}
finally {
rs.close();
}
}
finally {
ps.close();
}
}
@Override
public String toString () {
return new StringBuilder("Search{")
.append("sql=" + this.sql)
.append(", mediaType=" + this.mediaType)
.append(", terms=" + this.terms)
.append("}")
.toString();
}
}
}
|
package ecse321.fall2014.group3.bomberman.physics;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import com.flowpowered.math.vector.Vector2f;
public class SweepAndPruneAlgorithm {
private final Set<Collidable> collidables = new HashSet<>();
private final List<EndPoint> xPoints = new LinkedList<>();
private final List<EndPoint> yPoints = new LinkedList<>();
private final boolean doAsserts;
public SweepAndPruneAlgorithm() {
this(false);
}
public SweepAndPruneAlgorithm(boolean doAsserts) {
this.doAsserts = doAsserts;
}
public void add(Collidable collidable) {
collidables.add(collidable);
final EndPoint xMax = new EndPoint(collidable, true, true);
final EndPoint xMin = new EndPoint(collidable, true, false);
insertSorted(xPoints, xMax);
insertSorted(xPoints, xMin);
final EndPoint yMax = new EndPoint(collidable, false, true);
final EndPoint yMin = new EndPoint(collidable, false, false);
insertSorted(yPoints, yMax);
insertSorted(yPoints, yMin);
if (doAsserts) {
assertSorted(xPoints);
assertSorted(yPoints);
}
}
public void remove(Collidable collidable) {
collidables.remove(collidable);
removeEndPoints(xPoints, collidable);
removeEndPoints(yPoints, collidable);
if (doAsserts) {
assertSorted(xPoints);
assertSorted(yPoints);
}
}
public void update() {
updateEndPoints(xPoints);
updateEndPoints(yPoints);
sortEndPoints(xPoints);
sortEndPoints(yPoints);
if (doAsserts) {
assertSorted(xPoints);
assertSorted(yPoints);
}
final Set<CollidingPair> colliding = intersect(computeCollisions(xPoints), computeCollisions(yPoints));
for (Collidable collidable : collidables) {
collidable.clearCollisionList();
collidable.clearCollisionList();
}
for (CollidingPair pair : colliding) {
pair.updateCollisionLists();
}
}
public int getCount() {
return collidables.size();
}
public void clear() {
collidables.clear();
xPoints.clear();
yPoints.clear();
}
private static Set<CollidingPair> computeCollisions(List<EndPoint> points) {
final Set<CollidingPair> collidingPairs = new HashSet<>();
final Set<Collidable> openSet = new HashSet<>();
for (EndPoint point : points) {
final Collidable current = point.getOwner();
if (point.isMin()) {
// minimum points are first, so add box to open set
openSet.add(current);
} else {
// max points are last, so remove box from open set
openSet.remove(current);
// collide with all the remaining objects in open set
for (Collidable collidable : openSet) {
collidingPairs.add(new CollidingPair(current, collidable));
}
}
}
return collidingPairs;
}
private static void sortEndPoints(List<EndPoint> points) {
int size = points.size() - 1;
for (int i = 0; i < size; i++) {
final ListIterator<EndPoint> iterator = points.listIterator(i);
EndPoint previous = iterator.next();
while (iterator.hasNext()) {
final EndPoint current = iterator.next();
if (current.compareTo(previous) < 0) {
iterator.remove();
boolean wasSmaller = false;
while (iterator.hasPrevious() && (wasSmaller = current.compareTo(iterator.previous()) < 0)) {
}
if (!wasSmaller) {
iterator.next();
}
iterator.add(current);
break;
}
previous = current;
i++;
}
}
}
private static void updateEndPoints(List<EndPoint> points) {
for (EndPoint point : points) {
point.update();
}
}
private static void removeEndPoints(List<EndPoint> points, Collidable collidable) {
for (Iterator<EndPoint> iterator = points.iterator(); iterator.hasNext(); ) {
if (iterator.next().hasOwner(collidable)) {
iterator.remove();
}
}
}
private static <T extends Comparable<T>> void insertSorted(List<T> list, T element) {
int i = 0;
for (Comparable<T> existing : list) {
if (existing.compareTo(element) >= 0) {
break;
}
i++;
}
list.add(i, element);
}
private static Set<CollidingPair> intersect(Set<CollidingPair> xCollisions, Set<CollidingPair> yCollisions) {
for (Iterator<CollidingPair> iterator = xCollisions.iterator(); iterator.hasNext(); ) {
if (!yCollisions.contains(iterator.next())) {
iterator.remove();
}
}
return xCollisions;
}
private static void assertSorted(List<EndPoint> points) {
if (points.size() <= 1) {
return;
}
final Iterator<EndPoint> iterator = points.iterator();
EndPoint previous = iterator.next();
while (iterator.hasNext()) {
final EndPoint current = iterator.next();
if (current.compareTo(previous) < 0) {
throw new AssertionError("End points are not sorted");
}
previous = current;
}
}
private static class EndPoint implements Comparable<EndPoint> {
private final Collidable owner;
private final boolean isX;
private final boolean isMax;
private float point;
private EndPoint(Collidable owner, boolean isX, boolean isMax) {
this.owner = owner;
this.isX = isX;
this.isMax = isMax;
update();
}
private void update() {
final Vector2f vec;
if (isMax) {
vec = owner.getBoxMaxPoint();
} else {
vec = owner.getBoxMinPoint();
}
if (isX) {
point = vec.getX();
} else {
point = vec.getY();
}
}
private boolean hasOwner(Collidable collidable) {
// we need to check references here, not values
return owner.equals(collidable);
}
private Collidable getOwner() {
return owner;
}
private boolean isMin() {
return !isMax;
}
@Override
public int compareTo(EndPoint other) {
return (int) Math.signum(this.point - other.point);
}
@Override
public String toString() {
return owner + (isMax ? " max :" : " min :") + point;
}
}
private static class CollidingPair {
private final Collidable first, second;
private CollidingPair(Collidable first, Collidable second) {
if (first.getID() == second.getID()) {
throw new IllegalArgumentException("A box cannot collide with itself");
}
// Sort so pairs of the same objects are guaranteed to be equal
if (first.getID() > second.getID()) {
this.first = second;
this.second = first;
} else {
this.first = first;
this.second = second;
}
}
private Collidable getFirst() {
return first;
}
private Collidable getSecond() {
return second;
}
private void updateCollisionLists() {
getFirst().addColliding(getSecond());
getSecond().addColliding(getFirst());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CollidingPair)) {
return false;
}
final CollidingPair that = (CollidingPair) o;
return first.equals(that.first) && second.equals(that.second);
}
@Override
public int hashCode() {
return first.hashCode() ^ second.hashCode();
}
@Override
public String toString() {
return "(" + first.getID() + ", " + second.getID() + ")";
}
}
}
|
package edu.northwestern.bioinformatics.studycalendar.xml.utils;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarSystemException;
import edu.northwestern.bioinformatics.studycalendar.dao.DaoFinder;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Change;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.ChildrenChange;
import gov.nih.nci.cabig.ctms.dao.DomainObjectDao;
/**
* @author John Dzak
*/
// TODO: this is not XML-specific (other than the error message) -- it could go in DeltaService
public class XmlUtils {
private DaoFinder daoFinder;
/**
* When a Change object is persisted to the database, when retreived the child element is null.
* We must retrieve it using the child id.
*/
public PlanTreeNode<?> findChangeChild(Change change) {
Integer childId = ((ChildrenChange)change).getChildId();
Class<? extends PlanTreeNode<?>> childClass = ((PlanTreeInnerNode) change.getDelta().getNode()).childClass();
DomainObjectDao dao = daoFinder.findDao(childClass);
PlanTreeNode<?> child = (PlanTreeNode<?>) dao.getById(childId);
if (child == null) {
throw new StudyCalendarSystemException("Problem importing template. Child with class %s and id %s could not be found",
childClass.getName(), childId.toString());
}
return child;
}
////// Bean Setters
public void setDaoFinder(DaoFinder daoFinder) {
this.daoFinder = daoFinder;
}
}
|
package net.programmer.igoodie.twitchspawn.tslanguage.action;
import net.minecraft.command.CommandSource;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.ItemStack;
import net.programmer.igoodie.twitchspawn.tslanguage.EventArguments;
import net.programmer.igoodie.twitchspawn.tslanguage.parser.TSLParser;
import net.programmer.igoodie.twitchspawn.tslanguage.parser.TSLSyntaxError;
import java.util.List;
public class ClearAction extends ItemSelectiveAction {
public ClearAction(List<String> words) throws TSLSyntaxError {
this.message = TSLParser.parseMessage(words);
List<String> actionWords = actionPart(words);
long countFrom = actionWords.stream()
.filter(word -> word.equalsIgnoreCase("FROM")).count();
if (countFrom == 0) parseSingleWord(actionWords);
else if (countFrom == 1) parseFrom(actionWords);
else throw new TSLSyntaxError("At most 1 FROM statement expected, found %d instead.", countFrom);
}
@Override
protected void performAction(ServerPlayerEntity player, EventArguments args) {
if (selectionType == SelectionType.WITH_INDEX) {
getInventory(player, inventoryType).set(inventoryIndex, ItemStack.EMPTY);
} else if (selectionType == SelectionType.EVERYTHING) {
if (inventoryType == null) {
player.inventory.clear();
} else {
List<ItemStack> inventory = getInventory(player, inventoryType);
for (int i = 0; i < inventory.size(); i++) {
inventory.set(i, ItemStack.EMPTY);
}
}
} else if (selectionType == SelectionType.RANDOM) {
InventorySlot randomSlot = inventoryType == null
? randomInventorySlot(player, false)
: randomInventorySlot(getInventory(player, inventoryType), false);
if (randomSlot != null) {
randomSlot.pullOut();
}
} else if (selectionType == SelectionType.ONLY_HELD_ITEM) {
int selectedHotbarIndex = player.inventory.currentItem;
player.inventory.mainInventory.set(selectedHotbarIndex, ItemStack.EMPTY);
} else if (selectionType == SelectionType.HOTBAR) {
for (int i = 0; i <= 8; i++) {
player.inventory.mainInventory.set(i, ItemStack.EMPTY);
}
}
CommandSource commandSource = player.getCommandSource()
.withPermissionLevel(9999).withFeedbackDisabled();
player.getServer().getCommandManager().handleCommand(commandSource,
"/playsound minecraft:entity.item.break master @s");
player.getServer().getCommandManager().handleCommand(commandSource,
"/particle minecraft:smoke ~ ~ ~ 2 2 2 0.1 400");
}
}
|
package org.chocosolver.solver.constraints.binary.element;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ConstraintsName;
import org.chocosolver.solver.constraints.unary.PropEqualXC;
import org.chocosolver.solver.constraints.unary.PropMemberBound;
import org.chocosolver.solver.variables.IntVar;
public class ElementFactory {
private ElementFactory() {
}
/**
* Count the number of time the values in TABLE increase or decrease (ie, count picks and valleys).
*
* @param TABLE an array of values
* @return the number of picks and valleys
*/
private static int sawtooth(int[] TABLE) {
int i = 0;
while (i < TABLE.length - 1 && TABLE[i] == TABLE[i + 1]) {
i++;
}
if (i == TABLE.length - 1) {
return -1;
}
boolean up = TABLE[i] < TABLE[i + 1];
int c = 0;
i++;
while (i < TABLE.length - 1) {
if (up && TABLE[i] > TABLE[i + 1]) {
c++;
up = false;
} else if (!up && TABLE[i] < TABLE[i + 1]) {
c++;
up = true;
}
i++;
}
return c;
}
/**
* Detect and return the most adapted Element propagator wrt to the values in TABLE
*
* @param VALUE the result variable
* @param TABLE the array of values
* @param INDEX the index variable
* @param OFFSET the offset
* @return an Element constraint
*/
public static Constraint detect(IntVar VALUE, int[] TABLE, IntVar INDEX, int OFFSET) {
// first chech the variables match
int st = sawtooth(TABLE);
if (st == -1) { // all values from TABLE are the same OR TABLE only contains one value
assert TABLE[0] == TABLE[TABLE.length - 1];
return new Constraint("FAKE_ELMT",
new PropMemberBound(INDEX, 0, TABLE.length - OFFSET),
new PropEqualXC(VALUE, TABLE[0])
);
}
return new Constraint(ConstraintsName.ELEMENT, new PropElement(VALUE, TABLE, INDEX, OFFSET));
}
}
|
package org.jboss.forge.plugin.idea.ui.component;
import org.jboss.forge.addon.ui.hints.InputType;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TextBoxComponentBuilder extends AbstractTextComponentBuilder
{
@Override
protected String getSupportedInputType()
{
return InputType.TEXTBOX;
}
@Override
protected JTextComponent createTextComponent()
{
return new JTextField();
}
}
|
package org.jenkinsci.plugins.docker.workflow.client;
import com.google.common.base.Optional;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Node;
import hudson.util.ArgumentListBuilder;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WindowsDockerClient extends DockerClient {
private static final Logger LOGGER = Logger.getLogger(WindowsDockerClient.class.getName());
private final Launcher launcher;
private final Node node;
public WindowsDockerClient(@Nonnull Launcher launcher, @CheckForNull Node node, @CheckForNull String toolName) {
super(launcher, node, toolName);
this.launcher = launcher;
this.node = node;
}
@Override
public String run(@Nonnull EnvVars launchEnv, @Nonnull String image, @CheckForNull String args, @CheckForNull String workdir, @Nonnull Map<String, String> volumes, @Nonnull Collection<String> volumesFromContainers, @Nonnull EnvVars containerEnv, @Nonnull String user, @Nonnull String... command) throws IOException, InterruptedException {
ArgumentListBuilder argb = new ArgumentListBuilder("docker", "run", "-d", "-t");
if (args != null) {
argb.addTokenized(args);
}
if (workdir != null) {
argb.add("-w", workdir);
}
for (Map.Entry<String, String> volume : volumes.entrySet()) {
argb.add("-v", volume.getKey() + ":" + volume.getValue());
}
for (String containerId : volumesFromContainers) {
argb.add("--volumes-from", containerId);
}
for (Map.Entry<String, String> variable : containerEnv.entrySet()) {
argb.add("-e");
argb.addMasked(variable.getKey()+"="+variable.getValue());
}
argb.add(image).add(command);
LaunchResult result = launch(launchEnv, false, null, argb);
if (result.getStatus() == 0) {
return result.getOut();
} else {
throw new IOException(String.format("Failed to run image '%s'. Error: %s", image, result.getErr()));
}
}
@Override
public List<String> listProcess(@Nonnull EnvVars launchEnv, @Nonnull String containerId) throws IOException, InterruptedException {
LaunchResult result = launch(launchEnv, false, null, "docker", "top", containerId);
if (result.getStatus() != 0) {
throw new IOException(String.format("Failed to run top '%s'. Error: %s", containerId, result.getErr()));
}
List<String> processes = new ArrayList<>();
try (Reader r = new StringReader(result.getOut());
BufferedReader in = new BufferedReader(r)) {
String line;
in.readLine(); // ps header
while ((line = in.readLine()) != null) {
final StringTokenizer stringTokenizer = new StringTokenizer(line, " ");
if (stringTokenizer.countTokens() < 1) {
throw new IOException("Unexpected `docker top` output : "+line);
}
processes.add(stringTokenizer.nextToken()); // COMMAND
}
}
return processes;
}
@Override
public Optional<String> getContainerIdIfContainerized() throws IOException, InterruptedException {
if (node == null ||
launch(new EnvVars(), true, null, "sc.exe", "query", "cexecsvc").getStatus() != 0) {
return Optional.absent();
}
LaunchResult getComputerName = launch(new EnvVars(), true, null, "hostname");
if(getComputerName.getStatus() != 0) {
throw new IOException("Failed to get hostname.");
}
String shortID = getComputerName.getOut().toLowerCase();
LaunchResult getLongIdResult = launch(new EnvVars(), true, null, "docker", "inspect", shortID, "--format={{.Id}}");
if(getLongIdResult.getStatus() != 0) {
LOGGER.log(Level.INFO, "Running inside of a container but cannot determine container ID from current environment.");
return Optional.absent();
}
return Optional.of(getLongIdResult.getOut());
}
@Override
public String whoAmI() throws IOException, InterruptedException {
try (ByteArrayOutputStream userId = new ByteArrayOutputStream()) {
launcher.launch().cmds("whoami").quiet(true).stdout(userId).start().joinWithTimeout(CLIENT_TIMEOUT, TimeUnit.SECONDS, launcher.getListener());
return userId.toString();
}
}
private LaunchResult launch(EnvVars env, boolean quiet, FilePath workDir, String... args) throws IOException, InterruptedException {
return launch(env, quiet, workDir, new ArgumentListBuilder(args));
}
private LaunchResult launch(EnvVars env, boolean quiet, FilePath workDir, ArgumentListBuilder argb) throws IOException, InterruptedException {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Executing command \"{0}\"", argb);
}
Launcher.ProcStarter procStarter = launcher.launch();
if (workDir != null) {
procStarter.pwd(workDir);
}
LaunchResult result = new LaunchResult();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
result.setStatus(procStarter.quiet(quiet).cmds(argb).envs(env).stdout(out).stderr(err).start().joinWithTimeout(CLIENT_TIMEOUT, TimeUnit.SECONDS, launcher.getListener()));
final String charsetName = Charset.defaultCharset().name();
result.setOut(out.toString(charsetName));
result.setErr(err.toString(charsetName));
return result;
}
}
|
package org.sagebionetworks.web.client.widget.entity;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.evaluation.model.Submission;
import org.sagebionetworks.repo.model.Entity;
import org.sagebionetworks.repo.model.Reference;
import org.sagebionetworks.repo.model.TeamHeader;
import org.sagebionetworks.repo.model.Versionable;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.SynapseClientAsync;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.transform.NodeModelCreator;
import org.sagebionetworks.web.client.widget.entity.EvaluationSubmitterView.Presenter;
import org.sagebionetworks.web.shared.EntityWrapper;
import org.sagebionetworks.web.shared.PaginatedResults;
import org.sagebionetworks.web.shared.exceptions.RestServiceException;
import org.sagebionetworks.web.shared.exceptions.UnknownErrorException;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class EvaluationSubmitter implements Presenter {
private EvaluationSubmitterView view;
private SynapseClientAsync synapseClient;
private NodeModelCreator nodeModelCreator;
private GlobalApplicationState globalApplicationState;
private AuthenticationController authenticationController;
private Entity submissionEntity;
private String submissionEntityId, submissionName;
private Long submissionEntityVersion;
private List<Evaluation> evaluations;
@Inject
public EvaluationSubmitter(EvaluationSubmitterView view,
SynapseClientAsync synapseClient,
NodeModelCreator nodeModelCreator,
GlobalApplicationState globalApplicationState,
AuthenticationController authenticationController) {
this.view = view;
this.view.setPresenter(this);
this.synapseClient = synapseClient;
this.nodeModelCreator = nodeModelCreator;
this.globalApplicationState = globalApplicationState;
this.authenticationController = authenticationController;
}
/**
*
* @param submissionEntity set to null if an entity finder should be shown
* @param evaluationIds set to null if we should query for all available evaluations
*/
public void configure(Entity submissionEntity, Set<String> evaluationIds) {
view.showLoading();
this.submissionEntity = submissionEntity;
try {
if (evaluationIds == null)
synapseClient.getAvailableEvaluations(getEvalCallback());
else
synapseClient.getAvailableEvaluations(evaluationIds, getEvalCallback());
} catch (RestServiceException e) {
view.showErrorMessage(e.getMessage());
}
}
private AsyncCallback<String> getEvalCallback() {
return new AsyncCallback<String>() {
@Override
public void onSuccess(String jsonString) {
try {
PaginatedResults<Evaluation> results = nodeModelCreator.createPaginatedResults(jsonString, Evaluation.class);
List<Evaluation> evaluations = results.getResults();
if (evaluations == null || evaluations.size() == 0) {
//no available evaluations, pop up an info dialog
view.showErrorMessage(DisplayConstants.NOT_PARTICIPATING_IN_ANY_EVALUATIONS);
}
else {
view.showModal1(submissionEntity == null, evaluations);
}
} catch (JSONObjectAdapterException e) {
onFailure(new UnknownErrorException(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION));
}
}
@Override
public void onFailure(Throwable caught) {
if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view))
view.showErrorMessage(caught.getMessage());
}
};
}
@Override
public void nextClicked(Reference selectedReference, String submissionName, List<Evaluation> evaluations) {
//in any case look up the entity (to make sure we have the most recent version, for the current etag
submissionEntityVersion = null;
if (submissionEntity != null) {
submissionEntityId = submissionEntity.getId();
if (submissionEntity instanceof Versionable)
submissionEntityVersion = ((Versionable)submissionEntity).getVersionNumber();
}
else {
submissionEntityId = selectedReference.getTargetId();
submissionEntityVersion = selectedReference.getTargetVersionNumber();
}
this.submissionName = submissionName;
this.evaluations = evaluations;
//The standard is to attach access requirements to the associated team, and show them when joining the team.
//So access requirements are not checked here.
view.hideModal1();
getAvailableTeams();
}
public void getAvailableTeams() {
synapseClient.getAvailableSubmissionTeams(getTeamsCallback());
}
private AsyncCallback<String> getTeamsCallback() {
return new AsyncCallback<String>() {
@Override
public void onSuccess(String jsonString) {
try {
PaginatedResults<TeamHeader> results = nodeModelCreator.createPaginatedResults(jsonString, TeamHeader.class);
List<TeamHeader> teams = results.getResults();
view.showModal2(teams);
} catch (JSONObjectAdapterException e) {
onFailure(new UnknownErrorException(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION));
}
}
@Override
public void onFailure(Throwable caught) {
if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view))
view.showErrorMessage(caught.getMessage());
}
};
}
@Override
public void doneClicked(String selectedTeamId) {
lookupEtagAndCreateSubmission(submissionEntityId, submissionEntityVersion, evaluations, selectedTeamId);
}
public void lookupEtagAndCreateSubmission(final String id, final Long ver, final List<Evaluation> evaluations, final String selectedTeamId) {
//look up entity for the current etag
synapseClient.getEntity(id, new AsyncCallback<EntityWrapper>() {
public void onSuccess(EntityWrapper result) {
Entity entity;
try {
entity = nodeModelCreator.createEntity(result);
Long v = null;
if (ver != null)
v = ver;
else if (entity instanceof Versionable)
v = ((Versionable)entity).getVersionNumber();
else {
//entity is not versionable, the service will not accept null, but will accept a version of 1
v = 1L;
}
submitToEvaluations(id, v, entity.getEtag(), selectedTeamId, evaluations);
} catch (JSONObjectAdapterException e) {
onFailure(new UnknownErrorException(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION));
}
}
@Override
public void onFailure(Throwable caught) {
if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view))
view.showErrorMessage(caught.getMessage());
}
});
}
public void submitToEvaluations(String entityId, Long versionNumber, String etag, String selectedTeamId, List<Evaluation> evaluations) {
//set up shared values across all submissions
Submission newSubmission = new Submission();
newSubmission.setEntityId(entityId);
newSubmission.setUserId(authenticationController.getCurrentUserPrincipalId());
newSubmission.setTeamId(selectedTeamId);
newSubmission.setVersionNumber(versionNumber);
if (submissionName != null && submissionName.trim().length() > 0)
newSubmission.setName(submissionName);
if (evaluations.size() > 0)
submitToEvaluations(newSubmission, etag, evaluations, 0);
}
public void submitToEvaluations(final Submission newSubmission, final String etag, final List<Evaluation> evaluations, final int index) {
//and create a new submission for each evaluation
Evaluation evaluation = evaluations.get(index);
newSubmission.setEvaluationId(evaluation.getId());
try {
synapseClient.createSubmission(newSubmission, etag, new AsyncCallback<Submission>() {
@Override
public void onSuccess(Submission result) {
//result is the updated submission
if (index == evaluations.size()-1) {
HashSet<String> replyMessages = new HashSet<String>();
for (Evaluation eval : evaluations) {
String message = eval.getSubmissionReceiptMessage();
if (message == null || message.length()==0)
message = DisplayConstants.SUBMISSION_RECEIVED_TEXT;
replyMessages.add(message);
}
view.hideModal2();
view.showSubmissionAcceptedDialogs(replyMessages);
} else {
submitToEvaluations(newSubmission, etag, evaluations, index+1);
}
}
@Override
public void onFailure(Throwable caught) {
if(!DisplayUtils.handleServiceException(caught, globalApplicationState, authenticationController.isLoggedIn(), view))
view.showErrorMessage(caught.getMessage());
}
});
} catch (RestServiceException e) {
view.showErrorMessage(e.getMessage());
}
}
public Widget asWidget() {
return view.asWidget();
}
}
|
package org.sagebionetworks.web.client.widget.entity.renderer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.sagebionetworks.evaluation.model.UserEvaluationState;
import org.sagebionetworks.repo.model.AccessRequirement;
import org.sagebionetworks.repo.model.TermsOfUseAccessRequirement;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.repo.model.UserSessionData;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.SynapseClientAsync;
import org.sagebionetworks.web.client.exceptions.IllegalArgumentException;
import org.sagebionetworks.web.client.place.LoginPlace;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.transform.NodeModelCreator;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.utils.CallbackP;
import org.sagebionetworks.web.client.utils.GovernanceServiceHelper;
import org.sagebionetworks.web.client.widget.WidgetRendererPresenter;
import org.sagebionetworks.web.client.widget.entity.EvaluationSubmitter;
import org.sagebionetworks.web.client.widget.entity.TutorialWizard;
import org.sagebionetworks.web.client.widget.entity.registration.WidgetConstants;
import org.sagebionetworks.web.shared.PaginatedResults;
import org.sagebionetworks.web.shared.WebConstants;
import org.sagebionetworks.web.shared.WikiPageKey;
import org.sagebionetworks.web.shared.exceptions.ForbiddenException;
import org.sagebionetworks.web.shared.exceptions.RestServiceException;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class JoinWidget implements JoinWidgetView.Presenter, WidgetRendererPresenter {
private JoinWidgetView view;
private Map<String,String> descriptor;
private WikiPageKey wikiKey;
private AuthenticationController authenticationController;
private SynapseClientAsync synapseClient;
private GlobalApplicationState globalApplicationState;
private NodeModelCreator nodeModelCreator;
private JSONObjectAdapter jsonObjectAdapter;
private EvaluationSubmitter evaluationSubmitter;
private String[] evaluationIds;
@Inject
public JoinWidget(JoinWidgetView view, SynapseClientAsync synapseClient,
AuthenticationController authenticationController,
GlobalApplicationState globalApplicationState,
NodeModelCreator nodeModelCreator,
JSONObjectAdapter jsonObjectAdapter, EvaluationSubmitter evaluationSubmitter) {
this.view = view;
view.setPresenter(this);
this.synapseClient = synapseClient;
this.authenticationController = authenticationController;
this.globalApplicationState = globalApplicationState;
this.nodeModelCreator = nodeModelCreator;
this.jsonObjectAdapter = jsonObjectAdapter;
this.evaluationSubmitter = evaluationSubmitter;
}
@Override
public void configure(final WikiPageKey wikiKey, final Map<String, String> widgetDescriptor) {
this.wikiKey = wikiKey;
this.descriptor = widgetDescriptor;
String evaluationId = descriptor.get(WidgetConstants.JOIN_WIDGET_EVALUATION_ID_KEY);
if (evaluationId != null) {
evaluationIds = new String[1];
evaluationIds[0] = evaluationId;
}
String subchallengeIdList = null;
if(descriptor.containsKey(WidgetConstants.JOIN_WIDGET_SUBCHALLENGE_ID_LIST_KEY)) subchallengeIdList = descriptor.get(WidgetConstants.JOIN_WIDGET_SUBCHALLENGE_ID_LIST_KEY);
if(subchallengeIdList != null) {
evaluationIds = subchallengeIdList.split(WidgetConstants.JOIN_WIDGET_SUBCHALLENGE_ID_LIST_DELIMETER);
}
//figure out if we should show anything
try {
synapseClient.getUserEvaluationState(evaluationIds[0], new AsyncCallback<UserEvaluationState>() {
@Override
public void onSuccess(UserEvaluationState state) {
view.configure(wikiKey, state);
}
@Override
public void onFailure(Throwable caught) {
//if the user can't read the evaluation, then don't show the join button. if there was some other error, then report it...
if (!(caught instanceof ForbiddenException)) {
view.showError(DisplayConstants.EVALUATION_USER_STATE_ERROR + caught.getMessage());
}
}
});
} catch (RestServiceException e) {
view.showError(DisplayConstants.EVALUATION_USER_STATE_ERROR + e.getMessage());
}
//set up view based on descriptor parameters
descriptor = widgetDescriptor;
}
@SuppressWarnings("unchecked")
public void clearState() {
}
@Override
public Widget asWidget() {
return view.asWidget();
}
@Override
public void register() {
registerStep1();
}
/**
* Check that the user is logged in
*/
public void registerStep1() {
if (!authenticationController.isLoggedIn()) {
//go to login page
view.showAnonymousRegistrationMessage();
//directs to the login page
}
else {
registerStep2();
}
}
/**
* Gather additional info about the logged in user
*/
public void registerStep2() {
//pop up profile form. user does not have to fill in info
UserSessionData sessionData = authenticationController.getCurrentUserSessionData();
UserProfile profile = sessionData.getProfile();
view.showProfileForm(profile, new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
continueToStep3();
}
@Override
public void onFailure(Throwable caught) {
continueToStep3();
}
public void continueToStep3(){
try{
registerStep3(0);
} catch (RestServiceException e) {
view.showError(DisplayConstants.EVALUATION_REGISTRATION_ERROR + e.getMessage());
}
}
});
}
/**
* Check for unmet access restrictions. As long as more exist, it will keep calling itself until all restrictions are approved.
* Will not proceed to step3 (joining the challenge) until all have been approved.
* @throws RestServiceException
*/
public void registerStep3(final int evalIndex) throws RestServiceException {
synapseClient.getUnmetEvaluationAccessRequirements(evaluationIds[evalIndex], new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
//are there unmet access restrictions?
try{
PaginatedResults<TermsOfUseAccessRequirement> ar = nodeModelCreator.createPaginatedResults(result, TermsOfUseAccessRequirement.class);
if (ar.getTotalNumberOfResults() > 0) {
//there are unmet access requirements. user must accept all before joining the challenge
List<TermsOfUseAccessRequirement> unmetRequirements = ar.getResults();
final AccessRequirement firstUnmetAccessRequirement = unmetRequirements.get(0);
String text = GovernanceServiceHelper.getAccessRequirementText(firstUnmetAccessRequirement);
Callback termsOfUseCallback = new Callback() {
@Override
public void invoke() {
//agreed to terms of use.
setLicenseAccepted(firstUnmetAccessRequirement.getId(), evalIndex);
}
};
//pop up the requirement
view.showAccessRequirement(text, termsOfUseCallback);
} else {
if (evalIndex == evaluationIds.length - 1)
registerStep4();
else
registerStep3(evalIndex+1);
}
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable caught) {
view.showError(DisplayConstants.EVALUATION_REGISTRATION_ERROR + caught.getMessage());
}
});
}
public void setLicenseAccepted(Long arId, final int evalIndex) {
final CallbackP<Throwable> onFailure = new CallbackP<Throwable>() {
@Override
public void invoke(Throwable t) {
view.showError(DisplayConstants.EVALUATION_REGISTRATION_ERROR + t.getMessage());
}
};
Callback onSuccess = new Callback() {
@Override
public void invoke() {
//ToU signed, now try to register for the challenge (will check for other unmet access restrictions before join)
try {
registerStep3(evalIndex);
} catch (RestServiceException e) {
onFailure.invoke(e);
}
}
};
GovernanceServiceHelper.signTermsOfUse(
authenticationController.getCurrentUserPrincipalId(),
arId,
onSuccess,
onFailure,
synapseClient,
jsonObjectAdapter);
}
/**
* Join the evaluation
* @throws RestServiceException
*/
public void registerStep4() throws RestServiceException {
//create participants
synapseClient.createParticipants(evaluationIds, new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
view.showInfo("Successfully Joined!", "");
configure(wikiKey, descriptor);
}
@Override
public void onFailure(Throwable caught) {
view.showError(DisplayConstants.EVALUATION_REGISTRATION_ERROR + caught.getMessage());
}
});
}
@Override
public void gotoLoginPage() {
goTo(new LoginPlace(LoginPlace.LOGIN_TOKEN));
}
public void goTo(Place place) {
globalApplicationState.getPlaceChanger().goTo(place);
}
@Override
public void submitToChallengeClicked() {
//has this user ever submitted to a challenge before?
try {
synapseClient.hasSubmitted(new AsyncCallback<Boolean>() {
@Override
public void onSuccess(Boolean hasSubmitted) {
if(hasSubmitted) {
//pop up the submission dialog that has an Entity Finder
showSubmissionDialog();
} else {
showSubmissionGuide(new TutorialWizard.Callback() {
@Override
public void tutorialSkipped() {
submissionUserGuideSkipped();
}
@Override
public void tutorialFinished() {
//do nothing
}
});
}
}
@Override
public void onFailure(Throwable caught) {
view.showError(DisplayConstants.EVALUATION_SUBMISSION_ERROR + caught.getMessage());
}
});
} catch (RestServiceException e) {
view.showError(DisplayConstants.EVALUATION_SUBMISSION_ERROR + e.getMessage());
}
}
public void getTutorialSynapseId(AsyncCallback<String> callback) {
synapseClient.getSynapseProperty(WebConstants.CHALLENGE_TUTORIAL_PROPERTY, callback);
}
@Override
public void submissionUserGuideSkipped() {
showSubmissionDialog();
}
@Override
public void showSubmissionGuide(final TutorialWizard.Callback callback) {
//no submissions found. walk through the steps of uploading to Synapse
getTutorialSynapseId(new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
onFailure(new IllegalArgumentException(DisplayConstants.PROPERTY_ERROR + WebConstants.CHALLENGE_TUTORIAL_PROPERTY));
};
public void onSuccess(String tutorialEntityId) {
view.showSubmissionUserGuide(tutorialEntityId, callback);
};
});
}
public void showSubmissionDialog() {
List<String> evaluationIdsList = new ArrayList<String>();
for (int i = 0; i < evaluationIds.length; i++) {
evaluationIdsList.add(evaluationIds[i]);
}
evaluationSubmitter.configure(null, evaluationIdsList);
}
}
|
package settings;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import controller.Controller;
import network.Peer;
import ntp.NTP;
public class Settings {
//NETWORK
private static final int DEFAULT_MIN_CONNECTIONS = 10;
private static final int DEFAULT_MAX_CONNECTIONS = 50;
private static final int DEFAULT_MAX_RECEIVE_PEERS = 20;
private static final int DEFAULT_MAX_SENT_PEERS = 20;
private static final int DEFAULT_CONNECTION_TIMEOUT = 10000;
private static final int DEFAULT_PING_INTERVAL = 30000;
private static final boolean DEFAULT_TRYING_CONNECT_TO_BAD_PEERS = true;
private static final String[] DEFAULT_PEERS = { };
//TESTNET
public static final long DEFAULT_MAINNET_STAMP = 1400247274336L; // QORA RELEASE
private long genesisStamp = -1;
//RPC
private static final int DEFAULT_RPC_PORT = 9085;
private static final String DEFAULT_RPC_ALLOWED = "127.0.0.1";
private static final boolean DEFAULT_RPC_ENABLED = true;
//GUI CONSOLE
private static final boolean DEFAULT_GUI_CONSOLE_ENABLED = true;
//WEB
private static final int DEFAULT_WEB_PORT = 9090;
private static final String DEFAULT_WEB_ALLOWED = "127.0.0.1";
private static final boolean DEFAULT_WEB_ENABLED = true;
//GUI
private static final boolean DEFAULT_GUI_ENABLED = true;
//SETTINGS.JSON FILE
private static final String DEFAULT_SETTINGS_PATH = "settings.json";
//DATA
private static final String DEFAULT_DATA_DIR = "data";
private static final String DEFAULT_WALLET_DIR = "wallet";
private static final boolean DEFAULT_GENERATOR_KEY_CACHING = false;
private static final boolean DEFAULT_CHECKPOINTING = true;
private static final boolean DEFAULT_SOUND_RECEIVE_COIN = true;
private static final boolean DEFAULT_SOUND_MESSAGE = true;
private static final boolean DEFAULT_SOUND_NEW_TRANSACTION = true;
private static final int DEFAULT_MAX_BYTE_PER_FEE = 512;
private static final boolean ALLOW_FEE_LESS_REQUIRED = false;
private static final BigDecimal DEFAULT_BIG_FEE = new BigDecimal(1000);
private static final String DEFAULT_BIG_FEE_MESSAGE = "Do you really want to set such a large fee?\nThese coins will go to the forgers.";
//DATE FORMAT
private static final String DEFAULT_TIME_ZONE = "";
private static final String DEFAULT_TIME_FORMAT = "";
private static final boolean DEFAULT_NS_UPDATE = false;
private static Settings instance;
private JSONObject settingsJSON;
private JSONObject peersJSON;
private String currentSettingsPath;
List<Peer> cacheInternetPeers;
long timeLoadInternetPeers;
public static Settings getInstance()
{
if(instance == null)
{
instance = new Settings();
}
return instance;
}
public static void FreeInstance()
{
if(instance != null)
{
instance = null;
}
}
private Settings()
{
int alreadyPassed = 0;
String settingsFilePath = "settings.json";
try
{
while(alreadyPassed<2)
{
//OPEN FILE
File file = new File(settingsFilePath);
currentSettingsPath = settingsFilePath;
//CREATE FILE IF IT DOESNT EXIST
if(!file.exists())
{
file.createNewFile();
}
//READ SETTINS JSON FILE
List<String> lines = Files.readLines(file, Charsets.UTF_8);
String jsonString = "";
for(String line : lines){
jsonString += line;
}
//CREATE JSON OBJECT
this.settingsJSON = (JSONObject) JSONValue.parse(jsonString);
alreadyPassed++;
if(this.settingsJSON.containsKey("settingspath"))
{
settingsFilePath = (String) this.settingsJSON.get("settingspath");
}
else
{
alreadyPassed ++;
}
}
}
catch(Exception e)
{
//STOP
System.out.println("ERROR reading settings.json. closing");
System.exit(0);
}
//TRY READ PEERS.JSON
try
{
//OPEN FILE
File file = new File(this.getCurrentPeersPath());
//CREATE FILE IF IT DOESNT EXIST
if(file.exists())
{
//READ PEERS FILE
List<String> lines = Files.readLines(file, Charsets.UTF_8);
String jsonString = "";
for(String line : lines){
jsonString += line;
}
//CREATE JSON OBJECT
this.peersJSON = (JSONObject) JSONValue.parse(jsonString);
} else {
this.peersJSON = new JSONObject();
}
}
catch(Exception e)
{
//STOP
System.out.println("ERROR reading peers.json.");
System.exit(0);
}
}
public JSONObject Dump()
{
return settingsJSON;
}
public String getCurrentSettingsPath()
{
return currentSettingsPath;
}
public String getCurrentPeersPath()
{
if(this.currentSettingsPath == "settings.json" || this.currentSettingsPath == "") {
return "peers.json";
} else {
File file = new File(this.currentSettingsPath);
if(file.exists()){
return file.getAbsoluteFile().getParent() + "/peers.json";
}
}
return currentSettingsPath;
}
public JSONArray getPeersJson()
{
return (JSONArray) this.peersJSON.get("knownpeers");
}
@SuppressWarnings("unchecked")
public List<Peer> getKnownPeers()
{
boolean loadPeersFromInternet = (
Controller.getInstance().getToOfflineTime() != 0L
&&
NTP.getTime() - Controller.getInstance().getToOfflineTime() > 5*60*1000
);
List<Peer> knownPeers = new ArrayList<Peer>();
JSONArray peersArray = new JSONArray();
try {
JSONArray peersArraySettings = (JSONArray) this.settingsJSON.get("knownpeers");
if(peersArraySettings != null)
{
for (Object peer : peersArraySettings) {
if(!peersArray.contains(peer)) {
peersArray.add(peer);
}
}
}
} catch (Exception e) {
Logger.getGlobal().info("Error with loading knownpeers from settings.json.");
}
try {
JSONArray peersArrayPeers = (JSONArray) this.peersJSON.get("knownpeers");
if(peersArrayPeers != null)
{
for (Object peer : peersArrayPeers) {
if(!peersArray.contains(peer)) {
peersArray.add(peer);
}
}
}
} catch (Exception e) {
Logger.getGlobal().info("Error with loading knownpeers from peers.json.");
}
knownPeers = getKnownPeersFromJSONArray(peersArray);
if(knownPeers.size() == 0 || loadPeersFromInternet)
{
knownPeers = getKnownPeersFromInternet();
}
return knownPeers;
}
public List<Peer> getKnownPeersFromInternet()
{
try {
if(this.cacheInternetPeers == null) {
this.cacheInternetPeers = new ArrayList<Peer>();
}
if(this.cacheInternetPeers.size() == 0 || NTP.getTime() - this.timeLoadInternetPeers > 24*60*60*1000 )
{
this.timeLoadInternetPeers = NTP.getTime();
URL u = new URL("https://raw.githubusercontent.com/Qoracoin/Qora/master/Qora/peers.json");
InputStream in = u.openStream();
String stringInternetSettings = IOUtils.toString( in );
JSONObject internetSettingsJSON = (JSONObject) JSONValue.parse(stringInternetSettings);
JSONArray peersArray = (JSONArray) internetSettingsJSON.get("knownpeers");
if(peersArray != null) {
this.cacheInternetPeers = getKnownPeersFromJSONArray(peersArray);
}
}
return this.cacheInternetPeers;
} catch (Exception e) {
//RETURN EMPTY LIST
return this.cacheInternetPeers;
}
}
@SuppressWarnings("unchecked")
public List<Peer> getKnownPeersFromJSONArray(JSONArray peersArray)
{
try
{
//GET PEERS FROM JSON
if(peersArray.isEmpty())
peersArray.addAll(Arrays.asList(DEFAULT_PEERS));
//CREATE LIST WITH PEERS
List<Peer> peers = new ArrayList<Peer>();
for(int i=0; i<peersArray.size(); i++)
{
try
{
InetAddress address = InetAddress.getByName((String) peersArray.get(i));
//CHECK IF SOCKET IS NOT LOCALHOST
if(!address.equals(InetAddress.getLocalHost()))
{
//CREATE PEER
Peer peer = new Peer(address);
//ADD TO LIST
peers.add(peer);
}
}catch(Exception e)
{
Logger.getGlobal().info((String) peersArray.get(i) + " - invalid peer address!");
}
}
//RETURN
return peers;
}
catch(Exception e)
{
//RETURN EMPTY LIST
return new ArrayList<Peer>();
}
}
public void setGenesisStamp(long testNetStamp) {
this.genesisStamp = testNetStamp;
}
public boolean isTestnet () {
return this.getGenesisStamp() != DEFAULT_MAINNET_STAMP;
}
public long getGenesisStamp() {
if(this.genesisStamp == -1) {
if(this.settingsJSON.containsKey("testnetstamp"))
{
if(this.settingsJSON.get("testnetstamp").toString().equals("now") ||
((Long) this.settingsJSON.get("testnetstamp")).longValue() == 0) {
this.genesisStamp = System.currentTimeMillis();
} else {
this.genesisStamp = ((Long) this.settingsJSON.get("testnetstamp")).longValue();
}
} else {
this.genesisStamp = DEFAULT_MAINNET_STAMP;
}
}
return this.genesisStamp;
}
public int getMaxConnections()
{
if(this.settingsJSON.containsKey("maxconnections"))
{
return ((Long) this.settingsJSON.get("maxconnections")).intValue();
}
return DEFAULT_MAX_CONNECTIONS;
}
public int getMaxReceivePeers()
{
if(this.settingsJSON.containsKey("maxreceivepeers"))
{
return ((Long) this.settingsJSON.get("maxreceivepeers")).intValue();
}
return DEFAULT_MAX_RECEIVE_PEERS;
}
public int getMaxSentPeers()
{
if(this.settingsJSON.containsKey("maxsentpeers"))
{
return ((Long) this.settingsJSON.get("maxsentpeers")).intValue();
}
return DEFAULT_MAX_SENT_PEERS;
}
public int getMinConnections()
{
if(this.settingsJSON.containsKey("minconnections"))
{
return ((Long) this.settingsJSON.get("minconnections")).intValue();
}
return DEFAULT_MIN_CONNECTIONS;
}
public int getConnectionTimeout()
{
if(this.settingsJSON.containsKey("connectiontimeout"))
{
return ((Long) this.settingsJSON.get("connectiontimeout")).intValue();
}
return DEFAULT_CONNECTION_TIMEOUT;
}
public boolean isTryingConnectToBadPeers()
{
if(this.settingsJSON.containsKey("tryingconnecttobadpeers"))
{
return ((Boolean) this.settingsJSON.get("tryingconnecttobadpeers")).booleanValue();
}
return DEFAULT_TRYING_CONNECT_TO_BAD_PEERS;
}
public int getRpcPort()
{
if(this.settingsJSON.containsKey("rpcport"))
{
return ((Long) this.settingsJSON.get("rpcport")).intValue();
}
return DEFAULT_RPC_PORT;
}
public String[] getRpcAllowed()
{
try
{
if(this.settingsJSON.containsKey("rpcallowed"))
{
//GET PEERS FROM JSON
JSONArray allowedArray = (JSONArray) this.settingsJSON.get("rpcallowed");
//CREATE LIST WITH PEERS
String[] allowed = new String[allowedArray.size()];
for(int i=0; i<allowedArray.size(); i++)
{
allowed[i] = (String) allowedArray.get(i);
}
//RETURN
return allowed;
}
//RETURN
return DEFAULT_RPC_ALLOWED.split(";");
}
catch(Exception e)
{
//RETURN EMPTY LIST
return new String[0];
}
}
public boolean isRpcEnabled()
{
if(this.settingsJSON.containsKey("rpcenabled"))
{
return ((Boolean) this.settingsJSON.get("rpcenabled")).booleanValue();
}
return DEFAULT_RPC_ENABLED;
}
public int getWebPort()
{
if(this.settingsJSON.containsKey("webport"))
{
return ((Long) this.settingsJSON.get("webport")).intValue();
}
return DEFAULT_WEB_PORT;
}
public boolean isGuiConsoleEnabled()
{
if(this.settingsJSON.containsKey("guiconsoleenabled"))
{
return ((Boolean) this.settingsJSON.get("guiconsoleenabled")).booleanValue();
}
return DEFAULT_GUI_CONSOLE_ENABLED;
}
public String[] getWebAllowed()
{
try
{
if(this.settingsJSON.containsKey("weballowed"))
{
//GET PEERS FROM JSON
JSONArray allowedArray = (JSONArray) this.settingsJSON.get("weballowed");
//CREATE LIST WITH PEERS
String[] allowed = new String[allowedArray.size()];
for(int i=0; i<allowedArray.size(); i++)
{
allowed[i] = (String) allowedArray.get(i);
}
//RETURN
return allowed;
}
//RETURN
return DEFAULT_WEB_ALLOWED.split(";");
}
catch(Exception e)
{
//RETURN EMPTY LIST
return new String[0];
}
}
public boolean isWebEnabled()
{
if(this.settingsJSON.containsKey("webenabled"))
{
return ((Boolean) this.settingsJSON.get("webenabled")).booleanValue();
}
return DEFAULT_WEB_ENABLED;
}
public boolean updateNameStorage()
{
if(this.settingsJSON.containsKey("nsupdate"))
{
return ((Boolean) this.settingsJSON.get("nsupdate")).booleanValue();
}
return DEFAULT_NS_UPDATE;
}
public String getWalletDir()
{
if(this.settingsJSON.containsKey("walletdir"))
{
return (String) this.settingsJSON.get("walletdir");
}
return DEFAULT_WALLET_DIR;
}
public String getDataDir()
{
if(this.settingsJSON.containsKey("datadir"))
{
return (String) this.settingsJSON.get("datadir");
}
return DEFAULT_DATA_DIR;
}
public String getSettingsPath()
{
if(this.settingsJSON.containsKey("settingspath"))
{
return (String) this.settingsJSON.get("settingspath");
}
return DEFAULT_SETTINGS_PATH;
}
public int getPingInterval()
{
if(this.settingsJSON.containsKey("pinginterval"))
{
return ((Long) this.settingsJSON.get("pinginterval")).intValue();
}
return DEFAULT_PING_INTERVAL;
}
public boolean isGeneratorKeyCachingEnabled()
{
if(this.settingsJSON.containsKey("generatorkeycaching"))
{
return ((Boolean) this.settingsJSON.get("generatorkeycaching")).booleanValue();
}
return DEFAULT_GENERATOR_KEY_CACHING;
}
public boolean isCheckpointingEnabled()
{
if(this.settingsJSON.containsKey("checkpoint"))
{
return ((Boolean) this.settingsJSON.get("checkpoint")).booleanValue();
}
return DEFAULT_CHECKPOINTING;
}
public boolean isSoundReceivePaymentEnabled()
{
if(this.settingsJSON.containsKey("soundreceivepayment"))
{
return ((Boolean) this.settingsJSON.get("soundreceivepayment")).booleanValue();
}
return DEFAULT_SOUND_RECEIVE_COIN;
}
public boolean isSoundReceiveMessageEnabled()
{
if(this.settingsJSON.containsKey("soundreceivemessage"))
{
return ((Boolean) this.settingsJSON.get("soundreceivemessage")).booleanValue();
}
return DEFAULT_SOUND_MESSAGE;
}
public boolean isSoundNewTransactionEnabled()
{
if(this.settingsJSON.containsKey("soundnewtransaction"))
{
return ((Boolean) this.settingsJSON.get("soundnewtransaction")).booleanValue();
}
return DEFAULT_SOUND_NEW_TRANSACTION;
}
public int getMaxBytePerFee()
{
if(this.settingsJSON.containsKey("maxbyteperfee"))
{
return ((Long) this.settingsJSON.get("maxbyteperfee")).intValue();
}
return DEFAULT_MAX_BYTE_PER_FEE;
}
public boolean isAllowFeeLessRequired()
{
if(this.settingsJSON.containsKey("allowfeelessrequired"))
{
return ((Boolean) this.settingsJSON.get("allowfeelessrequired")).booleanValue();
}
return ALLOW_FEE_LESS_REQUIRED;
}
public BigDecimal getBigFee()
{
return DEFAULT_BIG_FEE;
}
public String getBigFeeMessage()
{
return DEFAULT_BIG_FEE_MESSAGE;
}
public boolean isGuiEnabled()
{
if(!Controller.getInstance().doesWalletDatabaseExists())
{
return true;
}
if(System.getProperty("nogui") != null)
{
return false;
}
if(this.settingsJSON.containsKey("guienabled"))
{
return ((Boolean) this.settingsJSON.get("guienabled")).booleanValue();
}
return DEFAULT_GUI_ENABLED;
}
public String getTimeZone()
{
if(this.settingsJSON.containsKey("timezone")) {
return (String) this.settingsJSON.get("timezone");
}
return DEFAULT_TIME_ZONE;
}
public String getTimeFormat()
{
if(this.settingsJSON.containsKey("timeformat")) {
return (String) this.settingsJSON.get("timeformat");
}
return DEFAULT_TIME_FORMAT;
}
public boolean isSysTrayEnabled() {
if(this.settingsJSON.containsKey("systray"))
{
return ((Boolean) this.settingsJSON.get("systray")).booleanValue();
}
return true;
}
}
|
package org.mtransit.parser.ca_ste_julie_omitsju_bus;
import java.util.HashSet;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.mt.data.MTrip;
public class SteJulieOMITSJUBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-ste-julie-omitsju-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new SteJulieOMITSJUBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating OMITSJU bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("\nGenerating OMITSJU bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public boolean excludeRoute(GRoute gRoute) {
return super.excludeRoute(gRoute);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
private static final long RID_STARTS_WITH_T = 20000l;
@Override
public long getRouteId(GRoute gRoute) {
if (Utils.isDigitsOnly(gRoute.getRouteShortName())) {
return Long.parseLong(gRoute.getRouteShortName());
}
Matcher matcher = DIGITS.matcher(gRoute.getRouteId());
if (matcher.find()) {
long id = Long.parseLong(matcher.group());
if (gRoute.getRouteShortName().toLowerCase(Locale.ENGLISH).startsWith("t")) {
return id + RID_STARTS_WITH_T;
}
}
System.out.printf("\nUnexpected route ID for %s!\n", gRoute);
System.exit(-1);
return -1;
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
routeLongName = CleanUtils.SAINT.matcher(routeLongName).replaceAll(CleanUtils.SAINT_REPLACEMENT);
routeLongName = SECTEUR.matcher(routeLongName).replaceAll(SECTEUR_REPLACEMENT);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR = "649039";
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public String getRouteColor(GRoute gRoute) {
if ("1".equals(gRoute.getRouteShortName())) return "7E4A94";
if ("3".equals(gRoute.getRouteShortName())) return "41A62B";
if ("4".equals(gRoute.getRouteShortName())) return "EAC800";
if ("5".equals(gRoute.getRouteShortName())) return "E2007A";
if ("6".equals(gRoute.getRouteShortName())) return "B49C4C";
if ("7".equals(gRoute.getRouteShortName())) return "60BDDC";
if ("8".equals(gRoute.getRouteShortName())) return "F39400";
if ("T1".equals(gRoute.getRouteShortName())) return "E53834";
if ("T2".equals(gRoute.getRouteShortName())) return "007C79";
if ("T3".equals(gRoute.getRouteShortName())) return "79421E";
if ("325".equals(gRoute.getRouteShortName())) return "57585A";
if ("330".equals(gRoute.getRouteShortName())) return "57585A";
if ("340".equals(gRoute.getRouteShortName())) return "57585A";
if ("350".equals(gRoute.getRouteShortName())) return "57585A";
if ("600".equals(gRoute.getRouteShortName())) return "9C9E9F";
System.out.printf("\nUnexpected route color for %s!\n", gRoute);
System.exit(-1);
return null;
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId());
}
private static final Pattern DIRECTION = Pattern.compile("(direction )", Pattern.CASE_INSENSITIVE);
private static final String DIRECTION_REPLACEMENT = "";
private static final Pattern SECTEUR = Pattern.compile("(secteur[s]? )", Pattern.CASE_INSENSITIVE);
private static final String SECTEUR_REPLACEMENT = "";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = DIRECTION.matcher(tripHeadsign).replaceAll(DIRECTION_REPLACEMENT);
tripHeadsign = SECTEUR.matcher(tripHeadsign).replaceAll(SECTEUR_REPLACEMENT);
tripHeadsign = CleanUtils.removePoints(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypesFRCA(tripHeadsign);
return CleanUtils.cleanLabelFR(tripHeadsign);
}
private static final Pattern START_WITH_FACE_A = Pattern.compile("^(face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern START_WITH_FACE_AU = Pattern.compile("^(face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern START_WITH_FACE = Pattern.compile("^(face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_FACE_A = Pattern.compile("( face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_WITH_FACE_AU = Pattern.compile("( face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_WITH_FACE = Pattern.compile("( face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern[] START_WITH_FACES = new Pattern[] { START_WITH_FACE_A, START_WITH_FACE_AU, START_WITH_FACE };
private static final Pattern[] SPACE_FACES = new Pattern[] { SPACE_FACE_A, SPACE_WITH_FACE_AU, SPACE_WITH_FACE };
private static final Pattern AVENUE = Pattern.compile("( avenue)", Pattern.CASE_INSENSITIVE);
private static final String AVENUE_REPLACEMENT = " av.";
@Override
public String cleanStopName(String gStopName) {
gStopName = AVENUE.matcher(gStopName).replaceAll(AVENUE_REPLACEMENT);
gStopName = Utils.replaceAll(gStopName, START_WITH_FACES, CleanUtils.SPACE);
gStopName = Utils.replaceAll(gStopName, SPACE_FACES, CleanUtils.SPACE);
gStopName = CleanUtils.cleanStreetTypesFRCA(gStopName);
return CleanUtils.cleanLabelFR(gStopName);
}
private static final String ZERO = "0";
@Override
public String getStopCode(GStop gStop) {
if (ZERO.equals(gStop.getStopCode())) {
return null;
}
return super.getStopCode(gStop);
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
@Override
public int getStopId(GStop gStop) {
String stopCode = getStopCode(gStop);
if (stopCode != null && stopCode.length() > 0) {
return Integer.valueOf(stopCode); // using stop code as stop ID
}
Matcher matcher = DIGITS.matcher(gStop.getStopId());
if (matcher.find()) {
int digits = Integer.parseInt(matcher.group());
int stopId;
if (gStop.getStopId().startsWith("SJU")) {
stopId = 0;
} else if (gStop.getStopId().startsWith("LON")) {
stopId = 1_000_000;
} else {
System.out.printf("\nStop doesn't have an ID (start with)! %s\n", gStop);
System.exit(-1);
return -1;
}
if (gStop.getStopId().endsWith("A")) {
stopId += 100_000;
} else if (gStop.getStopId().endsWith("B")) {
stopId += 200_000;
} else {
System.out.printf("\nStop doesn't have an ID (end with)! %s!\n", gStop);
System.exit(-1);
return -1;
}
return stopId + digits;
}
System.out.printf("\nUnexpected stop ID for %s!\n", gStop);
System.exit(-1);
return -1;
}
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc330.Beachbot2014Java.commands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc330.Beachbot2014Java.Robot;
public class SendDefaultSmartDashboardData extends Command {
public SendDefaultSmartDashboardData() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
requires(Robot.smartDashboardSender);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
setRunWhenDisabled(true);
}
int count = 0;
// Called just before this Command runs the first time
protected void initialize() {
SmartDashboard.putNumber("ChassisX", chassisX);
SmartDashboard.putNumber("ChassisY", chassisY);
SmartDashboard.putNumber("EncoderLeft", encoderLeft);
SmartDashboard.putNumber("EncoderRight", encoderRight);
count = 0;
}
double pickupCurrent = 0;
double armPosition = 0;
double chassisX = 0;
double chassisY = 0;
double gyroAngle = 0;
double encoderLeft = 0;
double encoderRight = 0;
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (count % 10 == 0)
{
if (pickupCurrent != Robot.pickup.getCurrent()) {
pickupCurrent = Robot.pickup.getCurrent();
SmartDashboard.putNumber("PickupCurrent", pickupCurrent);
}
if (armPosition != Robot.arm.getArmPosition()) {
armPosition = Robot.arm.getArmPosition();
SmartDashboard.putNumber("ArmPosition", armPosition);
}
if (chassisX != Robot.chassis.getX()) {
chassisX = Robot.chassis.getX();
SmartDashboard.putNumber("ChassisX", chassisX);
}
if (chassisY != Robot.chassis.getY()) {
chassisY = Robot.chassis.getY();
SmartDashboard.putNumber("ChassisY", chassisY);
}
if (gyroAngle != Robot.chassis.getAngle()) {
gyroAngle = Robot.chassis.getAngle();
SmartDashboard.putNumber("GyroAngle", gyroAngle);
}
if (encoderLeft != Robot.chassis.getLeftDistance()) {
encoderLeft = Robot.chassis.getLeftDistance();
SmartDashboard.putNumber("EncoderLeft", encoderLeft);
}
if (encoderRight != Robot.chassis.getRightDistance()) {
encoderRight = Robot.chassis.getRightDistance();
SmartDashboard.putNumber("EncoderRight", encoderRight);
}
}
count++;
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
package at.grahsl.kafka.connect.mongodb.converter;
import at.grahsl.kafka.connect.mongodb.converter.types.sink.bson.*;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.apache.kafka.connect.errors.DataException;
import org.bson.*;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
@RunWith(JUnitPlatform.class)
public class SinkFieldConverterTest {
@TestFactory
@DisplayName("tests for boolean field conversions")
public List<DynamicTest> testBooleanFieldConverter() {
SinkFieldConverter converter = new BooleanFieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList(true,false)).forEach(el -> {
tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+el,
() -> assertEquals(el, ((BsonBoolean)converter.toBson(el)).getValue())
));
});
tests.add(dynamicTest("optional type conversion checks", () -> {
Schema valueOptionalDefault = SchemaBuilder.bool().optional().defaultValue(true);
assertAll("",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.BOOLEAN_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_BOOLEAN_SCHEMA)),
() -> assertEquals(valueOptionalDefault.defaultValue(),
converter.toBson(null, valueOptionalDefault).asBoolean().getValue())
);
}));
return tests;
}
@TestFactory
@DisplayName("tests for int8 field conversions")
public List<DynamicTest> testInt8FieldConverter() {
SinkFieldConverter converter = new Int8FieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList(Byte.MIN_VALUE,(byte)0,Byte.MAX_VALUE)).forEach(
el -> tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+el,
() -> assertEquals((int)el, ((BsonInt32)converter.toBson(el)).getValue())
))
);
tests.add(dynamicTest("optional type conversions", () -> {
Schema valueOptionalDefault = SchemaBuilder.int8().optional().defaultValue((byte)0);
assertAll("checks",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.INT8_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT8_SCHEMA)),
() -> assertEquals(((Byte)valueOptionalDefault.defaultValue()).intValue(),
((BsonInt32)converter.toBson(null, valueOptionalDefault)).getValue())
);
}));
return tests;
}
@TestFactory
@DisplayName("tests for int16 field conversions")
public List<DynamicTest> testInt16FieldConverter() {
SinkFieldConverter converter = new Int16FieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList(Short.MIN_VALUE,(short)0,Short.MAX_VALUE)).forEach(
el -> tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+el,
() -> assertEquals((short)el, ((BsonInt32)converter.toBson(el)).getValue())
))
);
tests.add(dynamicTest("optional type conversions", () -> {
Schema valueOptionalDefault = SchemaBuilder.int16().optional().defaultValue((short)0);
assertAll("checks",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.INT16_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT16_SCHEMA)),
() -> assertEquals(((short)valueOptionalDefault.defaultValue()),
((BsonInt32)converter.toBson(null, valueOptionalDefault)).getValue())
);
}));
return tests;
}
@TestFactory
@DisplayName("tests for int32 field conversions")
public List<DynamicTest> testInt32FieldConverter() {
SinkFieldConverter converter = new Int32FieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList(Integer.MIN_VALUE,0,Integer.MAX_VALUE)).forEach(
el -> tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+el,
() -> assertEquals((int)el, ((BsonInt32)converter.toBson(el)).getValue())
))
);
tests.add(dynamicTest("optional type conversions", () -> {
Schema valueOptionalDefault = SchemaBuilder.int32().optional().defaultValue(0);
assertAll("checks",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.INT32_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT32_SCHEMA)),
() -> assertEquals(valueOptionalDefault.defaultValue(),
((BsonInt32)converter.toBson(null, valueOptionalDefault)).getValue())
);
}));
return tests;
}
@TestFactory
@DisplayName("tests for int64 field conversions")
public List<DynamicTest> testInt64FieldConverter() {
SinkFieldConverter converter = new Int64FieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList(Long.MIN_VALUE,0L,Long.MAX_VALUE)).forEach(
el -> tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+el,
() -> assertEquals((long)el, ((BsonInt64)converter.toBson(el)).getValue())
))
);
tests.add(dynamicTest("optional type conversions", () -> {
Schema valueOptionalDefault = SchemaBuilder.int64().optional().defaultValue(0L);
assertAll("checks",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.INT64_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_INT64_SCHEMA)),
() -> assertEquals((long)valueOptionalDefault.defaultValue(),
((BsonInt64)converter.toBson(null, valueOptionalDefault)).getValue())
);
}));
return tests;
}
@TestFactory
@DisplayName("tests for float32 field conversions")
public List<DynamicTest> testFloat32FieldConverter() {
SinkFieldConverter converter = new Float32FieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList(Float.MIN_VALUE,0f,Float.MAX_VALUE)).forEach(
el -> tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+el,
() -> assertEquals((float)el, ((BsonDouble)converter.toBson(el)).getValue())
))
);
tests.add(dynamicTest("optional type conversions", () -> {
Schema valueOptionalDefault = SchemaBuilder.float32().optional().defaultValue(0.0f);
assertAll("checks",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.FLOAT32_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_FLOAT32_SCHEMA)),
() -> assertEquals(((Float)valueOptionalDefault.defaultValue()).doubleValue(),
((BsonDouble)converter.toBson(null, valueOptionalDefault)).getValue())
);
}));
return tests;
}
@TestFactory
@DisplayName("tests for float64 field conversions")
public List<DynamicTest> testFloat64FieldConverter() {
SinkFieldConverter converter = new Float64FieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList(Double.MIN_VALUE,0d,Double.MAX_VALUE)).forEach(
el -> tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+el,
() -> assertEquals((double)el, ((BsonDouble)converter.toBson(el)).getValue())
))
);
tests.add(dynamicTest("optional type conversions", () -> {
Schema valueOptionalDefault = SchemaBuilder.float64().optional().defaultValue(0.0d);
assertAll("checks",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.FLOAT64_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_FLOAT64_SCHEMA)),
() -> assertEquals(valueOptionalDefault.defaultValue(),
((BsonDouble)converter.toBson(null, valueOptionalDefault)).getValue())
);
}));
return tests;
}
@TestFactory
@DisplayName("tests for string field conversions")
public List<DynamicTest> testStringFieldConverter() {
SinkFieldConverter converter = new StringFieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList("fooFOO","","blahBLAH")).forEach(
el -> tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+el,
() -> assertEquals(el, ((BsonString)converter.toBson(el)).getValue())
))
);
tests.add(dynamicTest("optional type conversions", () -> {
Schema valueOptionalDefault = SchemaBuilder.string().optional().defaultValue("");
assertAll("checks",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.STRING_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_STRING_SCHEMA)),
() -> assertEquals(valueOptionalDefault.defaultValue(),
((BsonString)converter.toBson(null, valueOptionalDefault)).getValue())
);
}));
return tests;
}
@TestFactory
@DisplayName("tests for bytes field conversions")
public List<DynamicTest> testBytesFieldConverter() {
SinkFieldConverter converter = new BytesFieldConverter();
List<DynamicTest> tests = new ArrayList<>();
new ArrayList<>(Arrays.asList(new byte[]{-128,-127,0},new byte[]{},new byte[]{0,126,127})).forEach(
el -> tests.add(dynamicTest("conversion with "
+ converter.getClass().getSimpleName() + " for "+Arrays.toString(el),
() -> assertEquals(el, ((BsonBinary)converter.toBson(el)).getData())
))
);
tests.add(dynamicTest("optional type conversions", () -> {
Schema valueOptionalDefault = SchemaBuilder.bytes().optional().defaultValue(new byte[]{});
assertAll("checks",
() -> assertThrows(DataException.class, () -> converter.toBson(null, Schema.BYTES_SCHEMA)),
() -> assertEquals(new BsonNull(), converter.toBson(null, Schema.OPTIONAL_BYTES_SCHEMA)),
() -> assertEquals(valueOptionalDefault.defaultValue(),
((BsonBinary)converter.toBson(null, valueOptionalDefault)).getData())
);
}));
return tests;
}
}
|
package ca.corefacility.bioinformatics.irida.ria.web;
import org.junit.Test;
import org.springframework.mobile.device.site.SitePreference;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import static org.junit.Assert.assertEquals;
/**
* Unit Tests for {@link LoginController}
*
* @author Josh Adam <josh.adam@phac-aspc.gc.ca>
*/
public class LoginControllerTest {
private LoginController controller = new LoginController();
@Test
public void testShowLoginPage() {
Model model = new ExtendedModelMap();
assertEquals("login", controller.showLogin(model, false));
}
@Test
public void testShowSplashPage() {
SitePreference preference = SitePreference.NORMAL;
assertEquals("splash", controller.showSplash(preference));
}
}
|
package com.fundynamic.d2tm.game.event;
import com.fundynamic.d2tm.Game;
import com.fundynamic.d2tm.game.Viewport;
import com.fundynamic.d2tm.game.drawing.DrawableViewPort;
import com.fundynamic.d2tm.game.map.Map;
import com.fundynamic.d2tm.game.math.Vector2D;
import com.fundynamic.d2tm.graphics.Tile;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import static com.fundynamic.d2tm.Game.SCREEN_HEIGHT;
import static com.fundynamic.d2tm.Game.SCREEN_WIDTH;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@RunWith(MockitoJUnitRunner.class)
public class DrawableViewPortMoverListenerTest {
public static final float MOVE_SPEED = 1.0F;
public static final float SCROLL_SPEED = 2.0F;
public static final int ANY_COORDINATE_NOT_NEAR_BORDER = 100;
public static final float INITIAL_VIEWPORT_X = 4F;
public static final float INITIAL_VIEWPORT_Y = 4F;
public static int HEIGHT_OF_MAP = 20;
public static int WIDTH_OF_MAP = 25;
@Mock
private Viewport viewport;
private DrawableViewPort drawableViewPort;
private DrawableViewPortMoverListener listener;
private int renderAndUpdatedCalled;
@Before
public void setUp() throws SlickException {
drawableViewPort = new DrawableViewPort(viewport, Vector2D.zero(), new Vector2D<>(INITIAL_VIEWPORT_X, INITIAL_VIEWPORT_Y), mock(Graphics.class), MOVE_SPEED);
listener = new DrawableViewPortMoverListener(drawableViewPort, SCROLL_SPEED);
Mockito.when(viewport.getMap()).thenReturn(new Map(null, WIDTH_OF_MAP, HEIGHT_OF_MAP));
renderAndUpdatedCalled = 0;
}
@Test
public void mouseHittingLeftBorderOfScreenMovesViewportToLeft() throws SlickException {
// moved to 2 pixels close to the left of the screen
listener.mouseMoved(3, ANY_COORDINATE_NOT_NEAR_BORDER, 2, ANY_COORDINATE_NOT_NEAR_BORDER);
Vector2D<Float> viewportVector = updateAndRenderAndReturnNewViewportVector();
Assert.assertEquals((INITIAL_VIEWPORT_X - (MOVE_SPEED * SCROLL_SPEED)), viewportVector.getX(), 0.0001F);
Assert.assertEquals(INITIAL_VIEWPORT_Y, viewportVector.getY(), 0.0001F);
}
@Test
public void mouseHittingRightBorderOfScreenMovesViewportToRight() throws SlickException {
// moved to 2 pixels close to the right of the screen
listener.mouseMoved(SCREEN_WIDTH - 3, ANY_COORDINATE_NOT_NEAR_BORDER, SCREEN_WIDTH - 2, ANY_COORDINATE_NOT_NEAR_BORDER);
Vector2D<Float> viewportVector = updateAndRenderAndReturnNewViewportVector();
Assert.assertEquals((INITIAL_VIEWPORT_X + (MOVE_SPEED * SCROLL_SPEED)), viewportVector.getX(), 0.0001F);
Assert.assertEquals(INITIAL_VIEWPORT_Y, viewportVector.getY(), 0.0001F);
}
@Test
public void mouseHittingTopOfScreenMovesViewportUp() throws SlickException {
// moved to 2 pixels close to the top of the screen
listener.mouseMoved(ANY_COORDINATE_NOT_NEAR_BORDER, 3, ANY_COORDINATE_NOT_NEAR_BORDER, 2);
Vector2D<Float> viewportVector = updateAndRenderAndReturnNewViewportVector();
Assert.assertEquals(INITIAL_VIEWPORT_X, viewportVector.getX(), 0.0001F);
Assert.assertEquals((INITIAL_VIEWPORT_Y - (MOVE_SPEED * SCROLL_SPEED)), viewportVector.getY(), 0.0001F);
}
@Test
public void mouseHittingBottomOfScreenMovesViewportDown() throws SlickException {
// moved to 2 pixels close to the bottom of the screen
listener.mouseMoved(ANY_COORDINATE_NOT_NEAR_BORDER, SCREEN_HEIGHT - 3, ANY_COORDINATE_NOT_NEAR_BORDER, SCREEN_HEIGHT - 2);
Vector2D<Float> viewportVector = updateAndRenderAndReturnNewViewportVector();
Assert.assertEquals(INITIAL_VIEWPORT_X, viewportVector.getX(), 0.0001F);
Assert.assertEquals((INITIAL_VIEWPORT_Y + (MOVE_SPEED * SCROLL_SPEED)), viewportVector.getY(), 0.0001F);
}
@Test
public void mouseFromTopLeftToNoBorderStopsMoving() throws SlickException {
// this updates viewport coordinates one move up and to the left
listener.mouseMoved(ANY_COORDINATE_NOT_NEAR_BORDER, ANY_COORDINATE_NOT_NEAR_BORDER, 0, 0);
updateAndRender(); // and move the viewport
Vector2D<Float> tickOneViewportVector = drawableViewPort.getViewingVector();
// move back to the middle
listener.mouseMoved(0, 0, ANY_COORDINATE_NOT_NEAR_BORDER, ANY_COORDINATE_NOT_NEAR_BORDER);
updateAndRender(); // and stop moving
// Check that the viewport stopped moving
Vector2D<Float> viewportVector = getLastCalledViewport();
Assert.assertEquals("Y position moved while expected to have stopped", tickOneViewportVector.getY(), viewportVector.getY(), 0.0001F);
Assert.assertEquals("X position moved while expected to have stopped", tickOneViewportVector.getX(), viewportVector.getX(), 0.0001F);
}
@Test
public void mouseFromBottomRightToNoBorderStopsMoving() throws SlickException {
// this updates viewport coordinates one move up and to the left
listener.mouseMoved(ANY_COORDINATE_NOT_NEAR_BORDER, ANY_COORDINATE_NOT_NEAR_BORDER, SCREEN_WIDTH, SCREEN_HEIGHT);
updateAndRender(); // and move the viewport
Vector2D<Float> tickOneViewportVector = drawableViewPort.getViewingVector();
// move back to the middle
listener.mouseMoved(SCREEN_WIDTH, SCREEN_HEIGHT, ANY_COORDINATE_NOT_NEAR_BORDER, ANY_COORDINATE_NOT_NEAR_BORDER);
updateAndRender(); // and stop moving
// Check that the viewport stopped moving
Vector2D<Float> viewportVector = getLastCalledViewport();
Assert.assertEquals("Y position moved while expected to have stopped", tickOneViewportVector.getY(), viewportVector.getY(), 0.0001F);
Assert.assertEquals("X position moved while expected to have stopped", tickOneViewportVector.getX(), viewportVector.getX(), 0.0001F);
}
@Test
public void stopsMovingLeftWhenAtTheLeftEdge() throws SlickException {
listener.mouseMoved(0, ANY_COORDINATE_NOT_NEAR_BORDER, 0, ANY_COORDINATE_NOT_NEAR_BORDER); // move left
updateAndRender();
updateAndRender();
updateAndRender();
Vector2D<Float> viewportVector = getLastCalledViewport();
Assert.assertEquals("X position moved over the edge", 0F, viewportVector.getX(), 0.0001F);
}
@Test
public void stopsMovingUpWhenAtTheUpperEdge() throws SlickException {
listener.mouseMoved(ANY_COORDINATE_NOT_NEAR_BORDER, 0, ANY_COORDINATE_NOT_NEAR_BORDER, 0); // move up
updateAndRender();
updateAndRender();
updateAndRender();
Vector2D<Float> viewportVector = getLastCalledViewport();
Assert.assertEquals("Y position moved over the edge", 0F, viewportVector.getY(), 0.0001F);
}
@Test
public void stopsMovingDownWhenAtTheBottomEdge() throws SlickException {
int viewportX = 0;
int viewportY = 0;
float scrollSpeed = 16F;
float maxYViewportPosition = (HEIGHT_OF_MAP * Tile.HEIGHT) - Game.SCREEN_HEIGHT; // 40F
drawableViewPort = new DrawableViewPort(viewport, Vector2D.zero(), new Vector2D<>(viewportX, viewportY), mock(Graphics.class), MOVE_SPEED);
listener = new DrawableViewPortMoverListener(drawableViewPort, scrollSpeed);
listener.mouseMoved(ANY_COORDINATE_NOT_NEAR_BORDER, SCREEN_HEIGHT, ANY_COORDINATE_NOT_NEAR_BORDER, SCREEN_HEIGHT); // move down
updateAndRender();
updateAndRender();
updateAndRender();
Vector2D<Float> viewportVector = getLastCalledViewport();
Assert.assertEquals("Y position moved over the bottom", maxYViewportPosition, viewportVector.getY(), 0.0001F);
}
@Test
public void stopsMovingDownWhenAtTheRightEdge() throws SlickException {
int viewportX = 0;
int viewportY = 0;
float scrollSpeed = 16F;
float maxXViewportPosition = (WIDTH_OF_MAP * Tile.WIDTH) - Game.SCREEN_WIDTH;
drawableViewPort = new DrawableViewPort(viewport, Vector2D.zero(), new Vector2D<>(viewportX, viewportY), mock(Graphics.class), MOVE_SPEED);
listener = new DrawableViewPortMoverListener(drawableViewPort, scrollSpeed);
listener.mouseMoved(SCREEN_WIDTH, ANY_COORDINATE_NOT_NEAR_BORDER, SCREEN_WIDTH, ANY_COORDINATE_NOT_NEAR_BORDER); // move right
updateAndRender();
updateAndRender();
Vector2D<Float> viewportVector = getLastCalledViewport();
Assert.assertEquals("X position moved over the right", maxXViewportPosition, viewportVector.getX(), 0.0001F);
}
private Vector2D<Float> updateAndRenderAndReturnNewViewportVector() throws SlickException {
updateAndRender();
return getLastCalledViewport();
}
private void updateAndRender() throws SlickException {
drawableViewPort.update();
drawableViewPort.render();
renderAndUpdatedCalled++;
}
private Vector2D<Float> getLastCalledViewport() throws SlickException {
Mockito.verify(viewport, times(renderAndUpdatedCalled)).draw(Mockito.<Graphics>anyObject(), Mockito.<Vector2D<Integer>>anyObject(), Mockito.<Vector2D<Float>>any());
return drawableViewPort.getViewingVector();
}
}
|
package helper;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.Normalizer;
import java.util.Collection;
import java.util.Collections;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.rio.LanguageHandler;
import org.eclipse.rdf4j.rio.ParserConfig;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.BasicParserSettings;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
/**
* @author Jan Schnasse schnasse@hbz-nrw.de
*
*/
public class RdfUtils {
/**
* @param inputStream
* an Input stream containing rdf data
* @param inf
* the rdf format
* @param baseUrl
* see sesame docu
* @return a Graph representing the rdf in the input stream
*/
public static Collection<Statement> readRdfToGraph(InputStream inputStream, RDFFormat inf, String baseUrl) {
try {
RDFParser rdfParser = Rio.createParser(inf);
StatementCollector collector = new StatementCollector();
rdfParser.setRDFHandler(collector);
ParserConfig parserConfig = rdfParser.getParserConfig();
System.out.println(parserConfig.toString());
parserConfig.set(BasicParserSettings.LANGUAGE_HANDLERS, Collections.<LanguageHandler> emptyList());
rdfParser.setParserConfig(parserConfig);
rdfParser.parse(inputStream, baseUrl);
return collector.getStatements();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param url
* url to get Rdf data from
* @param inf
* expected rdf serilization
* @param accept
* accept header
* @return a Rdf-Graph
* @throws IOException
*/
public static Collection<Statement> readRdfToGraph(URL url, RDFFormat inf, String accept) throws Exception {
try (InputStream in = URLUtil.urlToInputStream(url, URLUtil.mapOf("Accept", accept))) {
return readRdfToGraph(in, inf, url.toString());
}
}
public static RepositoryConnection readRdfInputStreamToRepository(InputStream is, RDFFormat inf) {
RepositoryConnection con = null;
try {
Repository myRepository = new SailRepository(new MemoryStore());
myRepository.initialize();
con = myRepository.getConnection();
String baseURI = "";
con.add(is, baseURI, inf);
return con;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Literal normalizeLiteral(Literal l) {
ValueFactory v = SimpleValueFactory.getInstance();
Literal newLiteral = null;
if (l.getLanguage().isPresent()) {
String l_lang = l.getLanguage().get();
newLiteral = v.createLiteral(Normalizer.normalize(l.stringValue().trim(), Normalizer.Form.NFKC), l_lang);
} else {
newLiteral = v.createLiteral(Normalizer.normalize(l.stringValue().trim(), Normalizer.Form.NFKC));
}
return newLiteral;
}
}
|
package matou.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class ServerNew {
private final static int BUFF_SIZE = 1024;
private final Charset UTF8_charset = Charset.forName("UTF8");
/* Code pour l'envoie de paquets */
private final ServerSocketChannel serverSocketChannel;
private final Selector selector;
private final Set<SelectionKey> selectedKeys;
private final HashMap<SocketChannel, ClientInfo> clientMap = new HashMap<>();
public ServerNew(int port) throws IOException {
serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
serverSocketChannel.bind(inetSocketAddress);
selector = Selector.open();
selectedKeys = selector.selectedKeys();
// requestProcessor = new RequestProcessor();
}
private static void usage() {
System.out.println("java matou.server.Server 7777");
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
usage();
return;
}
new ServerNew(Integer.parseInt(args[0])).launch();
}
public void launch() throws IOException {
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
Set<SelectionKey> selectedKeys = selector.selectedKeys();
System.out.println("Server started on " + serverSocketChannel.getLocalAddress());
while (!Thread.interrupted()) {
// printKeys();
// System.out.println("Starting select");
selector.select();
// System.out.println("Select finished");
// printSelectedKey();
processSelectedKeys();
selectedKeys.clear();
}
}
private void processSelectedKeys() throws IOException {
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isValid() && key.isAcceptable()) {
doAccept(key);
}
try {
ClientInfo clientInfo = (ClientInfo) key.attachment();
if (key.isValid() && key.isWritable()) {
clientInfo.doWrite(key);
}
if (key.isValid() && key.isReadable()) {
clientInfo.doRead(key);
}
} catch (IOException e) {
}
keyIterator.remove();
}
}
private void doAccept(SelectionKey key) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel clientSocketChannel = serverSocketChannel.accept();
if (clientSocketChannel == null) {
return;
}
System.out.println("Client connected " + clientSocketChannel);
clientSocketChannel.configureBlocking(false);
clientSocketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, new ClientInfo(clientSocketChannel));
}
private void cleanMapFromInvalidElements() {
clientMap.keySet().removeIf(e -> remoteAddressToString(e).equals("???"));
}
private String remoteAddressToString(SocketChannel sc) {
try {
return sc.getRemoteAddress().toString();
} catch (IOException e) {
return "???";
}
}
private enum PacketType {
E_PSEUDO(1),
E_CO_CLIENT_TO_CLIENT(2),
/* deconnection du client */
DC_PSEUDO(6),
/* envoie et reception de la liste des clients */
D_LIST_CLIENT_CO(7),
R_LIST_CLIENT_CO(8),
/* Concerne l'envoie et la reception */
E_M_ALL(9),
/* reception pseudo */
R_PSEUDO(10),
/* envoie adresse du serveur du client au serveur principal */
E_ADDR_SERV_CLIENT(11),
R_CO_CLIENT_TO_CLIENT(12);
private final byte value;
PacketType(int value) {
this.value = (byte) value;
}
public static PacketType encode(byte b) {
for (PacketType p : PacketType.values()) {
if (p.getValue() == b) {
return p;
}
}
throw new IllegalArgumentException("Wrong byte b : " + b);
}
public byte getValue() {
return value;
}
}
private enum CurrentStatus {
BEGIN(0),
MIDDLE(1),
END(2);
private final byte value;
CurrentStatus(int value) {
this.value = (byte) value;
}
public byte getValue() {
return value;
}
}
private enum answerPseudo {
TAKEN(0),
FREE(1),
ALREADY_CHOSEN(2);
private final byte value;
answerPseudo(int value) {
this.value = (byte) value;
}
public byte getValue() {
return value;
}
}
private class ClientInfo {
boolean isClosed = false;
CurrentStatus status = CurrentStatus.BEGIN;
private String name = null;
private ByteBuffer in;
private ByteBuffer out;
private SocketChannel socketChannel;
private byte currentOp = -1;
private InetSocketAddress adressServer;
private SelectionKey selectionKey;
public ClientInfo(SocketChannel socketChannel) {
in = ByteBuffer.allocate(BUFF_SIZE);
out = ByteBuffer.allocate(BUFF_SIZE);
this.socketChannel = socketChannel;
}
public void buildOutBuffer(SelectionKey key) {
this.selectionKey = key;
cleanMapFromInvalidElements();
// System.err.println("Status = " + status);
// System.err.println("in = " + in);
// System.err.println("pseudo = " + name);
// System.err.println("CurrentOp = " + currentOp);
// System.err.println("Selection Key = " +selectionKey.interestOps());
// Lis le 1er byte et le stocke
if (in.position() > 0 && status == CurrentStatus.BEGIN) {
in.flip();
currentOp = in.get();
System.out.println("CurrentOp = " + currentOp);
status = CurrentStatus.MIDDLE;
in.compact();
in.flip();
//return;
}
// System.err.println("////////////////////////////////////////////////////////////////");
// System.err.println("status after begin = " + status);
// System.err.println("In = " + in);
// System.err.println("pseudo = " + name);
// System.err.println("CurrentOp = " + currentOp);
// System.err.println("Out = " + out);
if (status == CurrentStatus.MIDDLE) {
// reset position au 1er bit lu si jamais on reboucle , pour pouvoir tout relire sauf le 1er bit deja lu
in.position(0);
PacketType bb2 = PacketType.encode(currentOp);
switch (bb2) {
case E_PSEUDO:
System.out.println("Entering decode pseudo");
decodeE_PSEUDO();
System.out.println("Exiting decode pseudo");
break;
case E_CO_CLIENT_TO_CLIENT:
System.out.println("Entering co client");
decodeCO_CLIENT_TO_CLIENT();
System.out.println("Exiting co client");
break;
case DC_PSEUDO:
System.out.println("Entering disconnection");
decodeDC_PSEUDO();
System.out.println("Exiting disconnection");
break;
case D_LIST_CLIENT_CO:
System.out.println("Entering demand list client");
decodeD_LIST_CLIENT_CO();
System.out.println("Exiting demand list client");
break;
case E_M_ALL:
System.out.println("Entering envoie message all");
decodeM_ALL();
System.out.println("Exiting envoie message all");
break;
case E_ADDR_SERV_CLIENT:
System.out.println("Entering envoie adresse serveur client");
decodeE_ADDR_SERV_CLIENT();
System.out.println("Exiting envoie adresse serveur client");
break;
default:
System.err.println("Error : Unkown code " + currentOp);
break;
}
}
}
// Fonctionne
private void decodeE_PSEUDO() {
int size;
if (in.remaining() < Integer.BYTES) {
// in.compact();
return;
}
size = in.getInt();
if (in.remaining() < size) {
// in.position(in.position() - Integer.BYTES);
// in.compact();
return;
}
ByteBuffer tempo = ByteBuffer.allocate(size);
for (int i = 0; i < size; i++) {
tempo.put(in.get());
}
tempo.flip();
String pseudo = UTF8_charset.decode(tempo).toString();
// System.out.println("Pseudo = " + pseudo);
in.compact();
//// Ecriture de la reponse dans le buffer de sortie ////
if (writeOutAnswerPseudo(pseudo)) {
return;
}
status = CurrentStatus.END;
// System.out.println("status end = " + status);
}
private boolean writeOutAnswerPseudo(String pseudo) {
out = ByteBuffer.allocate(Byte.BYTES + Integer.BYTES);
out.put(PacketType.R_PSEUDO.getValue());
if (pseudoAlreadyExists(pseudo)) {
out.putInt(answerPseudo.TAKEN.getValue());
} else {
// Si le client a deja un nom , il ne peut pas en changer
if (name != null) {
out.putInt(answerPseudo.ALREADY_CHOSEN.getValue());
status = CurrentStatus.END;
return true;
}
// Valeur de FREE = 1
out.putInt(answerPseudo.FREE.getValue());
// On n'attribut le nom que s'il est libre
name = pseudo;
clientMap.put(socketChannel, this);
}
return false;
}
private boolean pseudoAlreadyExists(String pseudo) {
final boolean[] exists = {false};
clientMap.forEach((sc, clientInfo) -> {
if (clientInfo.getName().compareToIgnoreCase(pseudo) == 0) {
exists[0] = true;
}
});
return exists[0];
}
private void decodeCO_CLIENT_TO_CLIENT() {
if (in.remaining() < Integer.BYTES) {
System.err.println(" E_CO_CLIENT_TO_CLIENT in < Int");
return;
}
int sizeDestinataire = in.getInt();
if (in.remaining() < sizeDestinataire) {
System.err.println(" E_CO_CLIENT_TO_CLIENT in < Dest");
return;
}
ByteBuffer destBuff = ByteBuffer.allocate(sizeDestinataire);
for (int i = 0; i < sizeDestinataire; i++) {
destBuff.put(in.get());
}
if (in.remaining() < Integer.BYTES) {
System.err.println(" E_CO_CLIENT_TO_CLIENT dest lu mais -> in < Int");
return;
}
int sizeSrc = in.getInt();
if (in.remaining() < sizeSrc) {
System.err.println(" E_CO_CLIENT_TO_CLIENT dest lu mais -> in < SRC");
return;
}
ByteBuffer srcBuff = ByteBuffer.allocate(sizeSrc);
for (int i = 0; i < sizeSrc; i++) {
srcBuff.put(in.get());
}
srcBuff.flip();
destBuff.flip();
String dest = UTF8_charset.decode(destBuff).toString();
if (!findClientInMap(dest)) {
in.compact();
out = ByteBuffer.allocate(Byte.BYTES + Integer.BYTES);
out.put(PacketType.R_CO_CLIENT_TO_CLIENT.getValue())// -1 -> placeholder
.putInt(0);
status = CurrentStatus.END;
} else {
// Ne touche que au buffer Out du destinataire
clientMap.forEach((sc, clientInfo) -> {
if (!sc.equals(socketChannel)) {
if (dest.equals(clientInfo.getName())) {
clientInfo.out = ByteBuffer.allocate(Byte.BYTES + Integer.BYTES + sizeSrc);
clientInfo.out.put(PacketType.E_CO_CLIENT_TO_CLIENT.getValue())
.putInt(sizeSrc)
.put(srcBuff);
clientInfo.status = CurrentStatus.END;
clientInfo.selectionKey.interestOps(SelectionKey.OP_WRITE);
}
}
});
out = ByteBuffer.allocate(Byte.BYTES + Integer.BYTES);
out.put(PacketType.R_CO_CLIENT_TO_CLIENT.getValue())// -1 -> placeholder
.putInt(1);
status = CurrentStatus.END;
in.compact();
}
}
private boolean findClientInMap(String dest) {
final boolean[] toReturn = {false};
clientMap.values().forEach((clientInfo) -> {
if (dest.equals(clientInfo.getName())) {
toReturn[0] = true;
}
});
return toReturn[0];
}
private void decodeDC_PSEUDO() {
SocketChannel tmp = socketChannel;
System.out.println("Disconnecting client : " + clientMap.get(tmp));
status = CurrentStatus.BEGIN;
clientMap.remove(tmp);
}
// Fonctionne
private void decodeD_LIST_CLIENT_CO() {
encodeR_LIST_CLIENT_CO();
in.compact();
status = CurrentStatus.END;
}
private void encodeR_LIST_CLIENT_CO() {
Long size = calculSizeBufferList();
if (size <= 0) {
System.err.println("This should never happen !!!!! Error : nobody is connected ");
return;
}
out = ByteBuffer.allocate(size.intValue());
out.put(PacketType.R_LIST_CLIENT_CO.getValue())
.putInt(clientMap.size());
StringBuilder sb = new StringBuilder();
clientMap.forEach((socketChannel, clientInfo) -> {
sb.delete(0, sb.length());
sb.append(clientInfo.getAdressServer().getHostString())
.append(":")
.append(clientInfo.getAdressServer().getPort());
String to_encode = sb.toString();
out.putInt(clientInfo.getName().length())
.put(UTF8_charset.encode(clientInfo.getName()))
.putInt(sb.length())
.put(UTF8_charset.encode(to_encode));
}
);
}
private long calculSizeBufferList() {
final Long[] total = {0L};
total[0] += Byte.BYTES;
total[0] += Integer.BYTES;
clientMap.values().forEach((clientInfo) -> {
// Peut se simplifier mais cette forme est plus clair
long clientSize = Integer.BYTES + clientInfo.getName().length() + Integer.BYTES + clientInfo.getAdressServer().toString().replace("/", "").length();
total[0] += clientSize;
});
return total[0];
}
// Fonctionne
private void decodeE_ADDR_SERV_CLIENT() {
if (in.remaining() < Integer.BYTES) {
// in.compact();
return;
}
int size = in.getInt();
if (in.remaining() < size) {
// in.position(in.position() - Integer.BYTES);
// in.compact();
return;
}
ByteBuffer tempo = ByteBuffer.allocate(size);
for (int i = 0; i < size; i++) {
tempo.put(in.get());
}
tempo.flip();
in.compact();
if (adressServer == null) {
status = CurrentStatus.BEGIN;
String fullChain = UTF8_charset.decode(tempo).toString();
int splitIndex = fullChain.lastIndexOf(':');
String host = fullChain.substring(0, splitIndex);
int port = Integer.parseInt(fullChain.substring(splitIndex + 1));
adressServer = new InetSocketAddress(host, port);
// clientMap.values().forEach(System.out::println);
}
}
// Fonctionne
private void decodeM_ALL() {
if (in.remaining() < Integer.BYTES) {
return;
}
int sizeName = in.getInt();
if (in.remaining() < sizeName) {
return;
}
ByteBuffer buffName = ByteBuffer.allocate(sizeName);
for (int i = 0; i < sizeName; i++) {
buffName.put(in.get());
}
buffName.flip();
///// Decode message //////
int sizeMessage;
if (in.remaining() < Integer.BYTES) {
return;
}
sizeMessage = in.getInt();
if (in.remaining() < sizeMessage) {
return;
}
ByteBuffer buffMessage = ByteBuffer.allocate(sizeMessage);
for (int i = 0; i < sizeMessage; i++) {
buffMessage.put(in.get());
}
buffMessage.flip();
ByteBuffer toSend = ByteBuffer.allocate(Byte.BYTES + Integer.BYTES + sizeName + Integer.BYTES + sizeMessage);
toSend.put(PacketType.E_M_ALL.getValue())
.putInt(sizeName)
.put(buffName)
.putInt(sizeMessage)
.put(buffMessage);
clientMap.forEach((sc, clientInfo) -> {
if (!sc.equals(socketChannel)) {
clientInfo.out = toSend.duplicate();
clientInfo.status = CurrentStatus.END;
clientInfo.selectionKey.interestOps(SelectionKey.OP_WRITE);
}
});
in.compact();
status = CurrentStatus.END;
}
// Pas de readAll en non bloquant
private void doRead(SelectionKey key) throws IOException {
System.out.println("In READ");
if (-1 == socketChannel.read(in)) {
System.out.println("///////////////////////Closed///////////////////////");
System.out.println("Client : " + name + " disconnected");
isClosed = true;
if (in.position() == 0) {
clientMap.remove(socketChannel);
socketChannel.close();
return;
}
}
buildOutBuffer(key);
int interest;
if ((interest = getInterestKey()) != 0) {
key.interestOps(interest);
}
}
private void doWrite(SelectionKey key) throws IOException {
System.out.println("In WRITE");
if (status == CurrentStatus.END) {
out.flip();
socketChannel.write(out);
out.compact();
if (isClosed) {
clientMap.remove(socketChannel);
socketChannel.close();
return;
}
status = CurrentStatus.BEGIN;
}
key.interestOps(getInterestKey());
}
public int getInterestKey() {
int interestKey = 0;// initialize
if (out.position() > 0) {
interestKey = interestKey | SelectionKey.OP_WRITE;
}
if (!isClosed) {
interestKey = interestKey | SelectionKey.OP_READ;
}
return interestKey;
}
public String getName() {
return name;
}
public InetSocketAddress getAdressServer() {
return adressServer;
}
@Override
public String toString() {
return "ClientInfo{ " +
" \nisClosed=" + isClosed +
" \nstatus=" + status +
" \nname='" + name + '\'' +
" \nin=" + in +
" \nout=" + out +
" \nsocketChannel=" + socketChannel +
" \ncurrentOp=" + currentOp +
" \nadressServer=" + adressServer +
"\n}\n";
}
}
}
|
package net.wasdev.gameon.room;
import java.util.Properties;
import javax.enterprise.context.ApplicationScoped;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.kafka.clients.producer.*;
@ApplicationScoped
public class Kafka {
protected String kafkaUrl;
private Producer<String,String> producer=null;
public Kafka(){
getConfig();
initProducer();
}
private void getConfig() {
try {
kafkaUrl = (String) new InitialContext().lookup("kafkaUrl");
} catch (NamingException e) {
}
if (kafkaUrl == null ) {
throw new IllegalStateException("kafkaUrl("+String.valueOf(kafkaUrl)+") was not found, check server.xml/server.env");
}
}
private void initProducer(){
System.out.println("Initializing kafka producer for url "+kafkaUrl);
Properties producerProps = new Properties();
producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);
producerProps.put("acks","-1");
producerProps.put("client.id","gameon-room");
producerProps.put("retries",0);
producerProps.put("batch.size",16384);
producerProps.put("zookeeper.session.timeout.ms",1000);
producerProps.put("linger.ms",1);
producerProps.put("buffer.memory",33554432);
producerProps.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
producerProps.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
//this is a cheat, we need to enable ssl when talking to message hub, and not to kafka locally
//the easiest way to know which we are running on, is to check how many hosts are in kafkaUrl
//locally for kafka there'll only ever be one, and messagehub gives us a whole bunch..
boolean multipleHosts = kafkaUrl.indexOf(",") != -1;
if(multipleHosts){
producerProps.put("security.protocol","SASL_SSL");
producerProps.put("ssl.protocol","TLSv1.2");
producerProps.put("ssl.enabled.protocols","TLSv1.2");
producerProps.put("ssl.truststore.location","/opt/ibm/java/jre/security/cacerts");
producerProps.put("ssl.truststore.password","changeit");
producerProps.put("ssl.truststore.type","JKS");
producerProps.put("ssl.endpoint.identification.algorithm","HTTPS");
}
producer = new KafkaProducer<String, String>(producerProps);
}
public void publishMessage(String topic, String key, String message){
System.out.println("Publishing to kafka, creating record");
ProducerRecord<String,String> pr = new ProducerRecord<String,String>(topic, key, message);
System.out.println("Publishing to kafka, sending record");
producer.send(pr);
System.out.println("Publishing to kafka, sent record");
}
}
|
package org.subethamail.smtp.server;
import java.io.IOException;
import java.net.ServerSocket;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.subethamail.smtp.command.CommandDispatcher;
import org.subethamail.smtp.command.DataCommand;
import org.subethamail.smtp.command.EhloCommand;
import org.subethamail.smtp.command.ExpnCommand;
import org.subethamail.smtp.command.HelloCommand;
import org.subethamail.smtp.command.HelpCommand;
import org.subethamail.smtp.command.MailCommand;
import org.subethamail.smtp.command.NoopCommand;
import org.subethamail.smtp.command.QuitCommand;
import org.subethamail.smtp.command.ReceiptCommand;
import org.subethamail.smtp.command.ResetCommand;
import org.subethamail.smtp.command.VerboseCommand;
import org.subethamail.smtp.command.VerifyCommand;
/**
* @author Ian McFarland <ian@neo.com>
*/
public class SMTPServiceCore implements Runnable
{
private SMTPServerContext serverContext;
private boolean go = false;
ServerSocket serverSocket;
private CommandDispatcher commandDispatcher;
private static Log log = LogFactory.getLog(SMTPServiceCore.class);
public SMTPServiceCore(SMTPServerContext context)
{
this.serverContext = context;
initializeCommandDispatcher();
serverContext.setCommandDispatcher(commandDispatcher);
}
private void initializeCommandDispatcher()
{
commandDispatcher = new CommandDispatcher(serverContext);
// new CommandLogger(new HelloCommand(commandDispatcher));
// new CommandLogger(new EhloCommand(commandDispatcher));
// new CommandLogger(new MailCommand(commandDispatcher));
// new CommandLogger(new ReceiptCommand(commandDispatcher));
new HelloCommand(commandDispatcher);
new EhloCommand(commandDispatcher);
new MailCommand(commandDispatcher);
new ReceiptCommand(commandDispatcher);
new DataCommand(commandDispatcher);
new ResetCommand(commandDispatcher);
new NoopCommand(commandDispatcher);
// new CommandLogger(new QuitCommand(commandDispatcher));
new QuitCommand(commandDispatcher);
new HelpCommand(commandDispatcher);
new VerifyCommand(commandDispatcher);
new ExpnCommand(commandDispatcher);
new VerboseCommand(commandDispatcher);
// new EtrnCommand(commandDispatcher);
// new DsnCommand(commandDispatcher);
}
public void start() throws IOException
{
go = true;
serverSocket = new ServerSocket(serverContext.getPort());
new Thread(this).start();
}
public void stop()
{
go = false;
try
{
serverSocket.close();
}
catch (IOException e)
{
log.error("Failed to close server socket.", e);
}
}
public void run()
{
log.info("SMTP Server socket started on port "
+ serverContext.getPort());
while (go)
{
try
{
new SocketHandler(serverContext, serverSocket.accept());
}
catch (IOException ioe)
{
if (go)
{
log
.error(
"IOException accepting connection in SMTPServiceCore",
ioe);
} // Otherwise this is just the socket complaining that it was
// closed while in accept.
}
}
try
{
serverSocket.close();
log.info("SMTP Server socket shut down.");
}
catch (IOException e)
{
log.error("Failed to close server socket.", e);
}
}
}
|
package sopc2dts.parsers.sopcinfo;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import sopc2dts.Logger;
import sopc2dts.Logger.LogLevel;
import sopc2dts.lib.AvalonSystem.SystemDataType;
import sopc2dts.lib.components.Interface;
import sopc2dts.lib.components.BasicComponent;
import sopc2dts.lib.devicetree.DTHelper;
public class SopcInfoInterface extends SopcInfoElementWithParams {
protected SystemDataType type = SystemDataType.CONDUIT;
protected boolean isMaster;
Interface bi;
public SopcInfoInterface(ContentHandler p, XMLReader xr, String iName,
BasicComponent owner, Attributes atts) {
super(p, xr, null);
setKind(atts.getValue("kind"));
bi = new Interface(iName, type, isMaster, owner);
basicElement = bi;
owner.getInterfaces().add(bi);
}
boolean setKind(String k)
{
boolean valid = true;
if(k.equalsIgnoreCase("avalon_master") ||
k.equalsIgnoreCase("avalon_tristate_master") ||
k.equalsIgnoreCase("tristate_conduit_master") ||
k.equalsIgnoreCase("altera_axi_master")||
k.equalsIgnoreCase("altera_axi4_master"))
{
type = SystemDataType.MEMORY_MAPPED;
isMaster = true;
} else if(k.equalsIgnoreCase("avalon_slave") ||
k.equalsIgnoreCase("avalon_tristate_slave") ||
k.equalsIgnoreCase("tristate_conduit_slave") ||
k.equalsIgnoreCase("altera_axi_slave") ||
k.equalsIgnoreCase("altera_axi4_slave"))
{
type = SystemDataType.MEMORY_MAPPED;
isMaster = false;
} else if(k.equalsIgnoreCase("clock_sink"))
{
type = SystemDataType.CLOCK;
isMaster = false;
} else if(k.equalsIgnoreCase("clock_source"))
{
type = SystemDataType.CLOCK;
isMaster = true;
} else if(k.equalsIgnoreCase("interrupt_receiver"))
{
type = SystemDataType.INTERRUPT;
isMaster = true;
} else if(k.equalsIgnoreCase("interrupt_sender"))
{
type = SystemDataType.INTERRUPT;
isMaster = false;
} else if(k.equalsIgnoreCase("nios_custom_instruction_master"))
{
type = SystemDataType.CUSTOM_INSTRUCTION;
isMaster = true;
} else if(k.equalsIgnoreCase("nios_custom_instruction_slave"))
{
type = SystemDataType.CUSTOM_INSTRUCTION;
isMaster = false;
} else if(k.equalsIgnoreCase("avalon_streaming_sink"))
{
type = SystemDataType.STREAMING;
isMaster = false;
} else if(k.equalsIgnoreCase("avalon_streaming_source"))
{
type = SystemDataType.STREAMING;
isMaster = true;
} else if(k.equalsIgnoreCase("reset_sink"))
{
type = SystemDataType.RESET;
isMaster = false;
} else if(k.equalsIgnoreCase("reset_source"))
{
type = SystemDataType.RESET;
isMaster = true;
} else if(k.equalsIgnoreCase("conduit") ||
k.equalsIgnoreCase("conduit_start") ||
k.equalsIgnoreCase("conduit_end"))
{
type = SystemDataType.CONDUIT;
isMaster = false;
} else {
valid = false;
Logger.logln("Unsupported interface kind: " + k, LogLevel.WARNING);
}
return valid;
}
public long[] getAddressableSize()
{
long[] res;
long span = 1;
int stepSize = 1;
String assVal = getParamValue("addressSpan");
if(assVal!=null)
{
span = Long.decode(assVal);
}
assVal = getParamValue("addressAlignment");
if((assVal!=null)&&(assVal.equals("NATIVE")))
{
assVal = getParamValue("addressUnits");
if(assVal!=null)
{
if(assVal.equalsIgnoreCase("WORDS"))
{
stepSize = 4;
} else {
System.out.println("Unsupported AddressUnits: " + assVal + " reverting to bytes");
}
}
}
switch(bi.getSecondaryWidth()) {
case 1: {
res = new long[1];
res[0] = span*stepSize;
} break;
case 2: {
res = new long[2];
DTHelper.long2longArr(span * stepSize, res);
} break;
default: {
Logger.logln("Unsupported cell-count: " + bi.getSecondaryWidth(), LogLevel.ERROR);
res = new long[0];
}
}
return res;
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equalsIgnoreCase(getElementName()))
{
if(bi.isMemorySlave())
{
bi.setInterfaceValue(getAddressableSize());
} else if(bi.isClockMaster())
{
bi.setInterfaceValue(DTHelper.parseSize4Intf(getParamValue("clockRate"), bi));
}
}
super.endElement(uri, localName, qName);
}
@Override
public String getElementName() {
return "interface";
}
}
|
// E4X.java
package ed.js;
import java.util.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import ed.js.func.*;
import ed.js.engine.*;
import ed.util.*;
public class E4X {
public static JSFunction _cons = new Cons();
public static class Cons extends JSFunctionCalls1 {
public JSObject newOne(){
return new ENode();
}
public Object call( Scope scope , Object str , Object [] args){
Object blah = scope.getThis();
ENode e;
if ( blah instanceof ENode)
e = (ENode)blah;
else
e = new ENode();
e.init( str.toString() );
return e;
}
protected void init() {
final JSFunctionCalls1 bar = this;
set( "settings" , new JSFunctionCalls0(){
public Object call( Scope s, Object foo[] ){
JSObjectBase sets = new JSObjectBase();
sets.set("ignoreComments", bar.get("ignoreComments"));
sets.set("ignoreProcessingInstructions", bar.get("ignoreProcessingInstructions"));
sets.set("ignoreWhitespace", bar.get("ignoreWhitespace"));
sets.set("prettyPrinting", bar.get("prettyPrinting"));
sets.set("prettyIndent", bar.get("prettyIndent"));
return sets;
}
} );
set( "setSettings", new JSFunctionCalls0() {
public Object call( Scope s, Object foo[] ){
JSObject settings = new JSObjectBase();
if(foo.length > 0 && foo[0] instanceof JSObjectBase) {
settings = (JSObject)foo[0];
Object setting = settings.get("ignoreComments");
if(setting != null && setting instanceof Boolean) {
bar.set( "ignoreComments" , ((Boolean)setting).booleanValue());
}
setting = settings.get("ignoreProcessingInstructions");
if(setting != null && setting instanceof Boolean)
bar.set( "ignoreProcessingInstructions" , ((Boolean)setting).booleanValue());
setting = settings.get("ignoreWhitespace");
if(setting != null && setting instanceof Boolean)
bar.set( "ignoreWhitespace" , ((Boolean)setting).booleanValue());
setting = settings.get("prettyPrinting");
if(setting != null && setting instanceof Boolean)
bar.set( "prettyPrinting" , ((Boolean)setting).booleanValue());
setting = settings.get("prettyIndent");
if(setting != null && setting instanceof Integer)
bar.set( "prettyIndent" , ((Integer)setting).intValue());
}
else {
bar.set( "ignoreComments" , true);
bar.set( "ignoreProcessingInstructions" , true);
bar.set( "ignoreWhitespace" , true);
bar.set( "prettyPrinting" , true);
bar.set( "prettyIndent" , 2);
}
return null;
}
} );
set( "defaultSettings" , new JSFunctionCalls0(){
public Object call( Scope s, Object foo[] ){
JSObjectBase sets = new JSObjectBase();
sets.set("ignoreComments", true);
sets.set("ignoreProcessingInstructions", true);
sets.set("ignoreWhitespace", true);
sets.set("prettyPrinting", true);
sets.set("prettyIndent", 2);
return sets;
}
} );
set( "ignoreComments" , true);
set( "ignoreProcessingInstructions" , true);
set( "ignoreWhitespace" , true);
set( "prettyPrinting" , true);
set( "prettyIndent" , 2);
_prototype.dontEnumExisting();
}
};
static class ENode extends JSObjectBase {
private ENode(){}
private ENode( Node n ){
_node = n;
}
void init( String s ){
_raw = s;
try {
_document = XMLUtil.parse( s );
_node = _document.getDocumentElement();
}
catch ( Exception e ){
throw new RuntimeException( "can't parse : " + e );
}
}
public Object get( Object n ){
if ( n == null )
return null;
if ( n instanceof String || n instanceof JSString ){
return _nodeGet( _node , n.toString() );
}
throw new RuntimeException( "can't handle : " + n.getClass() );
}
public Object child( Object propertyName ) {
try {
int x = Integer.parseInt(propertyName.toString());
return ((EList)get( "*" )).get(new Integer(propertyName.toString()));
}
catch( NumberFormatException nfe ) {
return get(propertyName.toString());
}
}
public int childIndex() {
Node parent = _node.getParentNode();
if( parent == null || parent.getNodeType() == Node.ATTRIBUTE_NODE ) return -1;
NodeList children = parent.getChildNodes();
for( int i=0; i<children.getLength(); i++ ) {
if(children.item(i).isEqualNode(_node)) return i;
}
return -1;
}
/** public DocumentFragment getNode() {
return _fragment;
}
public void appendChild(ENode child) {
_node.appendChild(child.getNode());
}*/
public String toString(){
if ( _raw != null )
return _raw;
if ( _node == null )
return null;
if ( _node.getChildNodes() != null &&
_node.getChildNodes().getLength() == 1 &&
_node.getChildNodes().item(0) instanceof CharacterData )
return XMLUtil.toString( _node.getChildNodes().item(0) );
return XMLUtil.toString( _node );
}
private String _raw;
private Document _document;
private Node _node;
}
static class EList extends JSObjectBase {
private EList( List<Node> lst ){
_lst = lst;
}
public Object get( Object n ){
if ( n == null )
return null;
if ( n instanceof Number )
return child( ((Number)n).intValue() );
if ( n instanceof JSString || n instanceof String ){
String s = n.toString();
if ( s.equals( "length" ) ||
s.equals( "toString" ) ||
s.equals( "tojson" ) ||
s.equals( "child" ) )
return null;
}
if ( n instanceof Query ){
Query q = (Query)n;
List<Node> matching = new ArrayList<Node>();
for ( Node theNode : _lst ){
if ( q.match( theNode ) )
matching.add( theNode );
}
return _handleListReturn( matching );
}
throw new RuntimeException( "can't handle [" + n + "] from a list" );
}
public ENode child( int num ){
return new ENode( _lst.get( num ) );
}
public int length(){
if ( _lst == null )
return -1;
return _lst.size();
}
public String toString(){
StringBuilder buf = new StringBuilder();
for ( Node n : _lst )
XMLUtil.append( n , buf , 0 );
return buf.toString();
}
final private List<Node> _lst;
}
static Object _nodeGet( Node start , String s ){
final boolean search = s.startsWith( ".." );
if ( search )
s = s.substring(2);
final boolean attr = s.startsWith( "@" );
if ( attr )
s = s.substring(1);
final boolean all = s.endsWith("*");
if( all )
s = s.substring(0, s.length()-1);
List<Node> traverse = new LinkedList<Node>();
traverse.add( start );
List<Node> res = new ArrayList<Node>();
while ( ! traverse.isEmpty() ){
Node n = traverse.remove(0);
if ( attr ){
NamedNodeMap nnm = n.getAttributes();
if ( all ) {
for(int i=0; i<nnm.getLength(); i++) {
res.add(nnm.item(i));
}
}
if ( nnm != null ){
Node a = nnm.getNamedItem( s );
if ( a != null )
res.add( a );
}
}
NodeList children = n.getChildNodes();
if ( children == null )
continue;
for ( int i=0; i<children.getLength(); i++ ){
Node c = children.item(i);
if ( all || ( ! attr && c.getNodeName().equals( s ) ) )
res.add( c );
if ( search )
traverse.add( c );
}
}
return _handleListReturn( res );
}
static Object _handleListReturn( List<Node> lst ){
if ( lst.size() == 0 )
return null;
if ( lst.size() == 1 ){
Node n = lst.get(0);
if ( n instanceof Attr )
return n.getNodeValue();
return new ENode( n );
}
return new EList( lst );
}
public static abstract class Query {
public Query( String what , JSString match ){
_what = what;
_match = match;
}
abstract boolean match( Node n );
final String _what;
final JSString _match;
}
public static class Query_EQ extends Query {
public Query_EQ( String what , JSString match ){
super( what , match );
}
boolean match( Node n ){
return JSInternalFunctions.JS_eq( _nodeGet( n , _what ) , _match );
}
public String toString(){
return " [[ " + _what + " == " + _match + " ]] ";
}
}
}
|
import ratpack.server.RatpackServer;
import ratpack.groovy.template.TextTemplateModule;
import ratpack.guice.Guice;
import ratpack.server.RatpackServer;
import ratpack.server.ServerConfig;
import static ratpack.groovy.Groovy.groovyTemplate;
import static ratpack.groovy.Groovy.ratpack;
import java.util.*;
import java.sql.*;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main {
public static void main(String... args) throws Exception {
RatpackServer.start(b -> {
ServerConfig serverConfig = ServerConfig.findBaseDir()
.env()
.build();
b
.serverConfig(serverConfig)
.registry(
Guice.registry(s -> s
.module(TextTemplateModule.class, conf ->
conf.setStaticallyCompile(true)
)
)
)
.handlers(c -> {
c
.get("index.html", ctx -> {
ctx.redirect(301, "/");
})
.get(ctx -> ctx.render(groovyTemplate("index.html")))
.get("hello", ctx -> {
ctx.render("Hello!");
})
.get("db", ctx -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
boolean local = !"cedar-14".equals(System.getenv("STACK"));
connection = DatabaseUrl.extract(local).getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
ctx.render(groovyTemplate(attributes, "db.html"));
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
ctx.render(groovyTemplate(attributes, "error.html"));
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
})
.assets("public");
});
}
);
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/hello", (req, res) -> "Good by World!");
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Good bye World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (name text, tick timestamp)");
stmt.executeUpdate("INSERT INTO name, ticks VALUES ('HOLAAAAAA', now())");
ResultSet rs = stmt.executeQuery("SELECT name, tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("name") + " " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import static javax.measure.unit.SI.KILOGRAM;
import javax.measure.quantity.Mass;
import org.jscience.physics.model.RelativisticModel;
import org.jscience.physics.amount.Amount;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/hello", (req, res) -> {
RelativisticModel.select();
String energy = System.getenv().get("ENERGY");
Amount<Mass> m = Amount.valueOf(energy).to(KILOGRAM);
return "E=mc^2: " + energy + " = " + m.toString();
});
/*get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());*/
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
import static spark.Spark.get;
import static spark.Spark.post;
import static spark.SparkBase.port;
import static spark.SparkBase.staticFileLocation;
import java.util.HashMap;
import java.util.Map;
import spark.ModelAndView;
import spark.template.freemarker.FreeMarkerEngine;
import controller.ClienteController;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
//TODO mudar para pagina do app :)
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
// get("/receber", (req, res) -> {
// String json = req;
// return new ClienteController().receberMsg(json);
// post("/enviar", (req, res) -> {
// String json = req;
// new ClienteController().enviarMsg(json);
// return "ok";
// post("/recomendacao", (req, res) -> {
// new ClienteController().addAmigos();
// String json = req;
// return new ClienteController().recomendar(json);
// post("/newuser", (req, res) -> {
// String json = req;
// new ClienteController().criarCliente(json);
// return "ok";
// post("/newfriend", (req, res) -> {
// String json = req;
// new ClienteController().novaAmizade(json);
// return "ok";
// post("/localizacao", (req, res) -> {
// String json = req;
// new ClienteController().editarLocation(json);
// return "ok";
post("/teste", (req, res) -> {
return req.body();
});
}
}
|
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/hello", (req, res) -> "Hello World");
/*get("/hello", (req, res) -> {
RelativisticModel.select();
Amount<Mass> m = Amount.valueOf("12 GeV").to(KILOGRAM);
return "E=mc^2: 12 GeV = " + m.toString();
});*/
/*get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
*/
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
package com.mercadopago;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.mercadopago.callbacks.FailureRecovery;
import com.mercadopago.core.MercadoPago;
import com.mercadopago.model.Installment;
import com.mercadopago.model.Issuer;
import com.mercadopago.model.PayerCost;
import com.mercadopago.model.PaymentMethod;
import com.mercadopago.model.PaymentPreference;
import com.mercadopago.model.PaymentType;
import com.mercadopago.model.Setting;
import com.mercadopago.model.Site;
import com.mercadopago.model.Token;
import com.mercadopago.util.ApiUtil;
import com.mercadopago.util.ErrorUtil;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class CardVaultActivity extends ShowCardActivity {
private Activity mActivity;
protected boolean mActiveActivity;
private View mCardBackground;
private PayerCost mPayerCost;
private PaymentPreference mPaymentPreference;
private FailureRecovery mFailureRecovery;
private List<PaymentMethod> mPaymentMethodList;
private Site mSite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivityParameters();
if(mDecorationPreference != null && mDecorationPreference.hasColors()) {
setTheme(R.style.Theme_MercadoPagoTheme_NoActionBar);
}
mActivity = this;
mActiveActivity = true;
setContentView();
initializeToolbar();
initializeActivityControls();
mMercadoPago = new MercadoPago.Builder()
.setContext(this)
.setPublicKey(mPublicKey)
.build();
if (mCurrentPaymentMethod != null) {
initializeCard();
}
initializeFrontFragment();
startGuessingCardActivity();
}
private void initializeActivityControls() {
mCardBackground = findViewById(R.id.card_background);
if(mDecorationPreference != null && mDecorationPreference.hasColors())
{
mCardBackground.setBackgroundColor(mDecorationPreference.getLighterColor());
}
}
@Override
protected void onResume() {
mActiveActivity = true;
super.onResume();
}
@Override
protected void onDestroy() {
mActiveActivity = false;
super.onDestroy();
}
@Override
protected void onPause() {
mActiveActivity = false;
super.onPause();
}
@Override
protected void onStop() {
mActiveActivity = false;
super.onStop();
}
@Override
protected void getActivityParameters() {
super.getActivityParameters();
mPublicKey = getIntent().getStringExtra("publicKey");
mSite = (Site) getIntent().getSerializableExtra("site");
mSecurityCodeLocation = CardInterface.CARD_SIDE_BACK;
mAmount = new BigDecimal(getIntent().getStringExtra("amount"));
mPaymentMethodList = (ArrayList<PaymentMethod>) this.getIntent().getSerializableExtra("paymentMethodList");
mPaymentPreference = (PaymentPreference) this.getIntent().getSerializableExtra("paymentPreference");
if (mPaymentPreference == null) {
mPaymentPreference = new PaymentPreference();
}
}
protected void initializeToolbar() {
super.initializeToolbarWithTitle("");
}
protected void setContentView() {
setContentView(R.layout.activity_new_card_vault);
}
private void startGuessingCardActivity() {
runOnUiThread(new Runnable() {
public void run() {
new MercadoPago.StartActivityBuilder()
.setActivity(mActivity)
.setPublicKey(mPublicKey)
.setAmount(new BigDecimal(100))
.setPaymentPreference(mPaymentPreference)
.setSupportedPaymentMethods(mPaymentMethodList)
.setDecorationPreference(mDecorationPreference)
.startGuessingCardActivity();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == MercadoPago.GUESSING_CARD_REQUEST_CODE) {
resolveGuessingCardRequest(resultCode, data);
} else if (requestCode == MercadoPago.INSTALLMENTS_REQUEST_CODE) {
resolveInstallmentsRequest(resultCode, data);
}
else if(requestCode == ErrorUtil.ERROR_REQUEST_CODE) {
resolveErrorRequest(resultCode, data);
}
}
private void resolveErrorRequest(int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
recoverFromFailure();
}
else {
setResult(resultCode, data);
finish();
}
}
protected void resolveInstallmentsRequest(int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
mPayerCost = (PayerCost) bundle.getSerializable("payerCost");
finishWithResult();
} else if (resultCode == RESULT_CANCELED) {
setResult(RESULT_CANCELED, data);
finish();
}
}
protected void resolveGuessingCardRequest(int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
mCurrentPaymentMethod = (PaymentMethod) data.getSerializableExtra("paymentMethod");
mToken = (Token) data.getSerializableExtra("token");
mSelectedIssuer = (Issuer) data.getSerializableExtra("issuer");
if (mToken != null && mCurrentPaymentMethod != null) {
mBin = mToken.getFirstSixDigits();
mCardholder = mToken.getCardholder();
List<Setting> settings = mCurrentPaymentMethod.getSettings();
Setting setting = Setting.getSettingByBin(settings, mBin);
mSecurityCodeLocation = setting.getSecurityCode().getCardLocation();
mCardNumberLength = setting.getCardNumber().getLength();
}
initializeCard();
if (mCurrentPaymentMethod != null) {
int color = getCardColor(mCurrentPaymentMethod);
mFrontFragment.quickTransition(color);
}
checkStartInstallmentsActivity();
} else if (resultCode == RESULT_CANCELED){
setResult(RESULT_CANCELED, data);
finish();
}
}
public void checkStartInstallmentsActivity() {
if (!mCurrentPaymentMethod.getPaymentTypeId().equals(PaymentType.CREDIT_CARD)) {
finishWithResult();
}
else {
mMercadoPago.getInstallments(mBin, mAmount, mSelectedIssuer.getId(), mCurrentPaymentMethod.getId(),
new Callback<List<Installment>>() {
@Override
public void success(List<Installment> installments, Response response) {
if (mActiveActivity) {
if (installments.size() == 1) {
if (installments.get(0).getPayerCosts().size() == 1) {
mPayerCost = installments.get(0).getPayerCosts().get(0);
finishWithResult();
}
if (installments.get(0).getPayerCosts().size() > 1) {
startInstallmentsActivity(installments.get(0).getPayerCosts());
} else {
ErrorUtil.startErrorActivity(mActivity, getString(R.string.mpsdk_standard_error_message), false);
}
} else {
ErrorUtil.startErrorActivity(mActivity, getString(R.string.mpsdk_standard_error_message), false);
}
}
}
@Override
public void failure(RetrofitError error) {
if (mActiveActivity) {
mFailureRecovery = new FailureRecovery() {
@Override
public void recover() {
checkStartInstallmentsActivity();
}
};
ApiUtil.showApiExceptionError(mActivity, error);
}
}
});
}
}
public void startInstallmentsActivity(final List<PayerCost> payerCosts) {
runOnUiThread(new Runnable() {
public void run() {
new MercadoPago.StartActivityBuilder()
.setActivity(mActivity)
.setPublicKey(mPublicKey)
.setPaymentMethod(mCurrentPaymentMethod)
.setAmount(mAmount)
.setToken(mToken)
.setPayerCosts(payerCosts)
.setIssuer(mSelectedIssuer)
.setPaymentPreference(mPaymentPreference)
.setSite(mSite)
.setDecorationPreference(mDecorationPreference)
.startCardInstallmentsActivity();
overridePendingTransition(R.anim.fade_in_seamless, R.anim.fade_out_seamless);
}
});
}
@Override
protected void finishWithResult() {
Intent returnIntent = new Intent();
returnIntent.putExtra("payerCost", mPayerCost);
returnIntent.putExtra("paymentMethod", mCurrentPaymentMethod);
returnIntent.putExtra("token", mToken);
returnIntent.putExtra("issuer", mSelectedIssuer);
setResult(RESULT_OK, returnIntent);
finish();
}
private void recoverFromFailure() {
if(mFailureRecovery != null) {
mFailureRecovery.recover();
}
}
}
|
package gcba.ratings.sdk;
import android.util.Log;
import com.google.gson.Gson;
import java.util.HashMap;
public final class Rating {
Rating(String api, String app, String platform, String range, String token) {
validateUrl(api);
validateKey(app, "app");
validateKey(platform, "platform");
validateKey(range, "range");
validateToken(token);
this.url = getUrl(api.trim());
this.app = app.trim();
this.platform = platform.trim();
this.range = range.trim();
this.token = token.trim();
this.user = new HashMap<String, String>();
}
private String url;
private String app;
private String platform;
private String range;
private String token;
private HashMap<String, String> user;
private void validateUrl(String url) {
if (url == null) throw new IllegalArgumentException("api can't be null");
if (!url.trim().matches("^(ftp|http|https):\\/\\/[^ \"]+$")) throw new IllegalArgumentException("invalid api");
}
private void validateKey(String key, String description) {
if (key == null) throw new IllegalArgumentException(description + " can't be null");
if (key.trim().length() != 32) throw new IllegalArgumentException(description + " is not a valid key");
}
private void validateToken(String token) {
if (token == null) throw new IllegalArgumentException("token can't be null");
if (token.trim().length() < 1) throw new IllegalArgumentException("invalid token");
}
private void validateName(String name) {
if (name.trim().length() < 3) throw new IllegalArgumentException("name too short");
if (name.trim().length() > 70) throw new IllegalArgumentException("name too long");
}
private void validateEmail(String email) {
if (!email.trim().matches("^[a-zA-Z0-9.!
if (email.trim().length() < 3) throw new IllegalArgumentException("email too short");
if (email.trim().length() > 100) throw new IllegalArgumentException("email too long");
}
private void validateMibaId(String mibaId) {
if (mibaId.trim().length() < 1) throw new IllegalArgumentException("mibaId too short");
}
private void validateRating(byte rating) {
if (rating < -127) throw new IllegalArgumentException("invalid rating");
}
private void validateDescription(String description) {
if (description.trim().length() < 3) throw new IllegalArgumentException("description too short");
if (description.trim().length() > 30) throw new IllegalArgumentException("description too long");
}
private void validateComment(String comment) {
if (comment.trim().length() < 3) throw new IllegalArgumentException("comment too short");
if (comment.trim().length() > 1000) throw new IllegalArgumentException("comment too long");
}
private String getUrl(String url) {
return url.charAt(url.length() - 1) == '/' ? url + "ratings" : url + "/ratings";
}
public void setUser(String name, String email, String mibaId) {
if (!(name != null || email != null || mibaId != null)) throw new IllegalArgumentException("user parameters can't all be null");
if (email == null && mibaId == null) throw new IllegalArgumentException("user has no valid email or mibaId");
if (name != null) {
validateName(name);
user.put("name", name.trim());
}
if (email != null) {
validateEmail(email);
user.put("email", email.trim());
}
if (mibaId != null) {
validateMibaId(mibaId);
user.put("mibaId", mibaId.trim());
}
}
public void create(byte rating, String description, String comment) {
Request request;
validateRating(rating);
request = new Request();
request.rating = rating;
request.range = range;
request.app.put("key", app);
request.platform.put("key", platform);
if (description != null) {
validateDescription(description);
request.description = description.trim();
}
if (comment != null) {
validateComment(comment);
request.comment = comment.trim();
}
send(request);
}
private void send(Request request) {
Gson gson;
String json;
gson = new Gson();
json = gson.toJson(request);
Log.d("JSON", json);
}
}
|
package org.jfree.chart.encoders;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.jfree.chart.util.ParamChecks;
/**
* Adapter class for the Sun PNG Encoder. The ImageEncoderFactory will only
* return a reference to this class by default if the library has been compiled
* under a JDK 1.4+ and is being run using a JDK 1.4+.
*/
public class SunPNGEncoderAdapter implements ImageEncoder {
/**
* Get the quality of the image encoding (always 0.0).
*
* @return A float representing the quality.
*/
@Override
public float getQuality() {
return 0.0f;
}
/**
* Set the quality of the image encoding (not supported in this
* ImageEncoder).
*
* @param quality A float representing the quality.
*/
@Override
public void setQuality(float quality) {
// No op
}
/**
* Get whether the encoder should encode alpha transparency (always false).
*
* @return Whether the encoder is encoding alpha transparency.
*/
@Override
public boolean isEncodingAlpha() {
return false;
}
/**
* Set whether the encoder should encode alpha transparency (not
* supported in this ImageEncoder).
*
* @param encodingAlpha Whether the encoder should encode alpha
* transparency.
*/
@Override
public void setEncodingAlpha(boolean encodingAlpha) {
// No op
}
/**
* Encodes an image in PNG format.
*
* @param bufferedImage The image to be encoded.
*
* @return The byte[] that is the encoded image.
*
* @throws IOException if there is an IO problem.
*/
@Override
public byte[] encode(BufferedImage bufferedImage) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
encode(bufferedImage, outputStream);
return outputStream.toByteArray();
}
/**
* Encodes an image in PNG format and writes it to an OutputStream.
*
* @param bufferedImage The image to be encoded.
* @param outputStream The OutputStream to write the encoded image to.
* @throws IOException if there is an IO problem.
*/
@Override
public void encode(BufferedImage bufferedImage, OutputStream outputStream)
throws IOException {
ParamChecks.nullNotPermitted(bufferedImage, "bufferedImage");
ParamChecks.nullNotPermitted(outputStream, "outputStream");
ImageIO.write(bufferedImage, ImageFormat.PNG, outputStream);
}
}
|
package com.cloud.agent.manager;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
import com.cloud.agent.StartupCommandProcessor;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.PingAnswer;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.ShutdownCommand;
import com.cloud.agent.api.StartupAnswer;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupProxyCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupSecondaryStorageCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.UnsupportedAnswer;
import com.cloud.agent.transport.Request;
import com.cloud.agent.transport.Response;
import com.cloud.alert.AlertManager;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.ManagementServerNode;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterIpAddressDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.UnsupportedVersionException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.Status.Event;
import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostTagsDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.hypervisor.kvm.resource.KvmDummyResourceBase;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.resource.Discoverer;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceState;
import com.cloud.resource.ServerResource;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StorageService;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.resource.DummySecondaryStorageResource;
import com.cloud.storage.secondary.SecondaryStorageVmManager;
import com.cloud.user.AccountManager;
import com.cloud.utils.ActionDelegate;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.HypervisorVersionChangedException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.utils.nio.HandlerFactory;
import com.cloud.utils.nio.Link;
import com.cloud.utils.nio.NioServer;
import com.cloud.utils.nio.Task;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.dao.VMInstanceDao;
import edu.emory.mathcs.backport.java.util.Collections;
/**
* Implementation of the Agent Manager. This class controls the connection to the agents.
*
* @config {@table || Param Name | Description | Values | Default || || port | port to listen on for agent connection. | Integer
* | 8250 || || workers | # of worker threads | Integer | 5 || || router.template.id | default id for template | Integer
* | 1 || || router.ram.size | default ram for router vm in mb | Integer | 128 || || router.ip.address | ip address for
* the router | ip | 10.1.1.1 || || wait | Time to wait for control commands to return | seconds | 1800 || || domain |
* domain for domain routers| String | foo.com || || alert.wait | time to wait before alerting on a disconnected agent |
* seconds | 1800 || || update.wait | time to wait before alerting on a updating agent | seconds | 600 || ||
* ping.interval | ping interval in seconds | seconds | 60 || || instance.name | Name of the deployment String |
* required || || start.retry | Number of times to retry start | Number | 2 || || ping.timeout | multiplier to
* ping.interval before announcing an agent has timed out | float | 2.0x || || router.stats.interval | interval to
* report router statistics | seconds | 300s || * }
**/
@Local(value = { AgentManager.class })
public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager {
private static final Logger s_logger = Logger.getLogger(AgentManagerImpl.class);
private static final Logger status_logger = Logger.getLogger(Status.class);
protected ConcurrentHashMap<Long, AgentAttache> _agents = new ConcurrentHashMap<Long, AgentAttache>(10007);
protected List<Pair<Integer, Listener>> _hostMonitors = new ArrayList<Pair<Integer, Listener>>(17);
protected List<Pair<Integer, Listener>> _cmdMonitors = new ArrayList<Pair<Integer, Listener>>(17);
protected List<Pair<Integer, StartupCommandProcessor>> _creationMonitors = new ArrayList<Pair<Integer, StartupCommandProcessor>>(17);
protected List<Long> _loadingAgents = new ArrayList<Long>();
protected int _monitorId = 0;
private Lock _agentStatusLock = new ReentrantLock();
protected NioServer _connection;
@Inject
protected HostDao _hostDao = null;
@Inject
protected DataCenterDao _dcDao = null;
@Inject
protected DataCenterIpAddressDao _privateIPAddressDao = null;
@Inject
protected IPAddressDao _publicIPAddressDao = null;
@Inject
protected HostPodDao _podDao = null;
@Inject
protected VMInstanceDao _vmDao = null;
@Inject
protected CapacityDao _capacityDao = null;
@Inject
protected ConfigurationDao _configDao = null;
@Inject
protected StoragePoolDao _storagePoolDao = null;
@Inject
protected StoragePoolHostDao _storagePoolHostDao = null;
@Inject
protected ClusterDao _clusterDao = null;
@Inject
protected ClusterDetailsDao _clusterDetailsDao = null;
@Inject
protected HostTagsDao _hostTagsDao = null;
@Inject
protected VolumeDao _volumeDao = null;
protected int _port;
@Inject
protected HighAvailabilityManager _haMgr = null;
@Inject
protected AlertManager _alertMgr = null;
@Inject
protected AccountManager _accountMgr = null;
@Inject
protected VirtualMachineManager _vmMgr = null;
@Inject StorageService _storageSvr = null;
@Inject StorageManager _storageMgr = null;
@Inject
protected HypervisorGuruManager _hvGuruMgr;
@Inject SecondaryStorageVmManager _ssvmMgr;
protected int _retry = 2;
protected String _name;
protected String _instance;
protected int _wait;
protected int _updateWait;
protected int _alertWait;
protected long _nodeId = -1;
protected Random _rand = new Random(System.currentTimeMillis());
protected int _pingInterval;
protected long _pingTimeout;
protected AgentMonitor _monitor = null;
protected ExecutorService _executor;
protected StateMachine2<Status, Status.Event, Host> _statusStateMachine = Status.getStateMachine();
@Inject ResourceManager _resourceMgr;
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name;
final ComponentLocator locator = ComponentLocator.getCurrentLocator();
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
if (configDao == null) {
throw new ConfigurationException("Unable to get the configuration dao.");
}
final Map<String, String> configs = configDao.getConfiguration("AgentManager", params);
_port = NumbersUtil.parseInt(configs.get("port"), 8250);
final int workers = NumbersUtil.parseInt(configs.get("workers"), 5);
String value = configs.get(Config.PingInterval.toString());
_pingInterval = NumbersUtil.parseInt(value, 60);
value = configs.get(Config.Wait.toString());
_wait = NumbersUtil.parseInt(value, 1800);
value = configs.get(Config.AlertWait.toString());
_alertWait = NumbersUtil.parseInt(value, 1800);
value = configs.get(Config.UpdateWait.toString());
_updateWait = NumbersUtil.parseInt(value, 600);
value = configs.get(Config.PingTimeout.toString());
final float multiplier = value != null ? Float.parseFloat(value) : 2.5f;
_pingTimeout = (long) (multiplier * _pingInterval);
s_logger.info("Ping Timeout is " + _pingTimeout);
value = configs.get(Config.DirectAgentLoadSize.key());
int threads = NumbersUtil.parseInt(value, 16);
_instance = configs.get("instance.name");
if (_instance == null) {
_instance = "DEFAULT";
}
_nodeId = ManagementServerNode.getManagementServerId();
s_logger.info("Configuring AgentManagerImpl. management server node id(msid): " + _nodeId);
long lastPing = (System.currentTimeMillis() >> 10) - _pingTimeout;
_hostDao.markHostsAsDisconnected(_nodeId, lastPing);
_monitor = ComponentLocator.inject(AgentMonitor.class, _nodeId, _hostDao, _vmDao, _dcDao, _podDao, this, _alertMgr, _pingTimeout);
registerForHostEvents(_monitor, true, true, false);
_executor = new ThreadPoolExecutor(threads, threads, 60l, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("AgentTaskPool"));
_connection = new NioServer("AgentManager", _port, workers + 10, this);
s_logger.info("Listening on " + _port + " with " + workers + " workers");
return true;
}
@Override
public Task create(Task.Type type, Link link, byte[] data) {
return new AgentHandler(type, link, data);
}
@Override
public int registerForHostEvents(final Listener listener, boolean connections, boolean commands, boolean priority) {
synchronized (_hostMonitors) {
_monitorId++;
if (connections) {
if (priority) {
_hostMonitors.add(0, new Pair<Integer, Listener>(_monitorId, listener));
} else {
_hostMonitors.add(new Pair<Integer, Listener>(_monitorId, listener));
}
}
if (commands) {
if (priority) {
_cmdMonitors.add(0, new Pair<Integer, Listener>(_monitorId, listener));
} else {
_cmdMonitors.add(new Pair<Integer, Listener>(_monitorId, listener));
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Registering listener " + listener.getClass().getSimpleName() + " with id " + _monitorId);
}
return _monitorId;
}
}
@Override
public int registerForInitialConnects(final StartupCommandProcessor creator,boolean priority) {
synchronized (_hostMonitors) {
_monitorId++;
if (priority) {
_creationMonitors.add(0, new Pair<Integer, StartupCommandProcessor>(
_monitorId, creator));
} else {
_creationMonitors.add(0, new Pair<Integer, StartupCommandProcessor>(
_monitorId, creator));
}
}
return _monitorId;
}
@Override
public void unregisterForHostEvents(final int id) {
s_logger.debug("Deregistering " + id);
_hostMonitors.remove(id);
}
private AgentControlAnswer handleControlCommand(AgentAttache attache, final AgentControlCommand cmd) {
AgentControlAnswer answer = null;
for (Pair<Integer, Listener> listener : _cmdMonitors) {
answer = listener.second().processControlCommand(attache.getId(), cmd);
if (answer != null) {
return answer;
}
}
s_logger.warn("No handling of agent control command: " + cmd + " sent from " + attache.getId());
return new AgentControlAnswer(cmd);
}
public void handleCommands(AgentAttache attache, final long sequence, final Command[] cmds) {
for (Pair<Integer, Listener> listener : _cmdMonitors) {
boolean processed = listener.second().processCommands(attache.getId(), sequence, cmds);
if (s_logger.isTraceEnabled()) {
s_logger.trace("SeqA " + attache.getId() + "-" + sequence + ": " + (processed ? "processed" : "not processed") + " by " + listener.getClass());
}
}
}
public void notifyAnswersToMonitors(long agentId, long seq, Answer[] answers) {
for (Pair<Integer, Listener> listener : _cmdMonitors) {
listener.second().processAnswers(agentId, seq, answers);
}
}
@Override
public AgentAttache findAttache(long hostId) {
AgentAttache attache = null;
synchronized (_agents) {
attache = _agents.get(hostId);
}
return attache;
}
@Override
public Answer sendToSecStorage(HostVO ssHost, Command cmd) {
if( ssHost.getType() == Host.Type.LocalSecondaryStorage ) {
return easySend(ssHost.getId(), cmd);
} else if ( ssHost.getType() == Host.Type.SecondaryStorage) {
return sendToSSVM(ssHost.getDataCenterId(), cmd);
} else {
String msg = "do not support Secondary Storage type " + ssHost.getType();
s_logger.warn(msg);
return new Answer(cmd, false, msg);
}
}
@Override
public void sendToSecStorage(HostVO ssHost, Command cmd, Listener listener) throws AgentUnavailableException {
if( ssHost.getType() == Host.Type.LocalSecondaryStorage ) {
send(ssHost.getId(), new Commands(cmd), listener);
} else if ( ssHost.getType() == Host.Type.SecondaryStorage) {
sendToSSVM(ssHost.getDataCenterId(), cmd, listener);
} else {
String err = "do not support Secondary Storage type " + ssHost.getType();
s_logger.warn(err);
throw new CloudRuntimeException(err);
}
}
private void sendToSSVM(final long dcId, final Command cmd, final Listener listener) throws AgentUnavailableException {
List<HostVO> ssAHosts = _ssvmMgr.listUpAndConnectingSecondaryStorageVmHost(dcId);
if (ssAHosts == null || ssAHosts.isEmpty() ) {
throw new AgentUnavailableException("No ssvm host found", -1);
}
Collections.shuffle(ssAHosts);
HostVO ssAhost = ssAHosts.get(0);
send(ssAhost.getId(), new Commands(cmd), listener);
}
@Override
public Answer sendToSSVM(final Long dcId, final Command cmd) {
List<HostVO> ssAHosts = _ssvmMgr.listUpAndConnectingSecondaryStorageVmHost(dcId);
if (ssAHosts == null || ssAHosts.isEmpty() ) {
return new Answer(cmd, false, "can not find secondary storage VM agent for data center " + dcId);
}
Collections.shuffle(ssAHosts);
HostVO ssAhost = ssAHosts.get(0);
return easySend(ssAhost.getId(), cmd);
}
@Override
public Answer sendTo(Long dcId, HypervisorType type, Command cmd) {
List<ClusterVO> clusters = _clusterDao.listByDcHyType(dcId, type.toString());
int retry = 0;
for (ClusterVO cluster : clusters) {
List<HostVO> hosts = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), null, dcId);
for (HostVO host : hosts) {
retry++;
if (retry > _retry) {
return null;
}
Answer answer = null;
try {
long targetHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(host.getId(), cmd);
answer = easySend(targetHostId, cmd);
} catch (Exception e) {
}
if (answer != null) {
return answer;
}
}
}
return null;
}
protected int getPingInterval() {
return _pingInterval;
}
@Override
public Answer send(Long hostId, Command cmd) throws AgentUnavailableException, OperationTimedoutException {
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand(cmd);
send(hostId, cmds, cmd.getWait());
Answer[] answers = cmds.getAnswers();
if (answers != null && !(answers[0] instanceof UnsupportedAnswer)) {
return answers[0];
}
if (answers != null && (answers[0] instanceof UnsupportedAnswer)) {
s_logger.warn("Unsupported Command: " + answers[0].getDetails());
return answers[0];
}
return null;
}
@DB
protected boolean noDbTxn() {
Transaction txn = Transaction.currentTxn();
return !txn.dbTxnStarted();
}
@Override
public Answer[] send(Long hostId, Commands commands, int timeout) throws AgentUnavailableException, OperationTimedoutException {
assert hostId != null : "Who's not checking the agent id before sending? ... (finger wagging)";
if (hostId == null) {
throw new AgentUnavailableException(-1);
}
if (timeout <= 0) {
timeout = _wait;
}
assert noDbTxn() : "I know, I know. Why are we so strict as to not allow txn across an agent call? ... Why are we so cruel ... Why are we such a dictator .... Too bad... Sorry...but NO AGENT COMMANDS WRAPPED WITHIN DB TRANSACTIONS!";
Command[] cmds = commands.toCommands();
assert cmds.length > 0 : "Ask yourself this about a hundred times. Why am I sending zero length commands?";
if (cmds.length == 0) {
commands.setAnswers(new Answer[0]);
}
final AgentAttache agent = getAttache(hostId);
if (agent == null || agent.isClosed()) {
throw new AgentUnavailableException("agent not logged into this management server", hostId);
}
Request req = new Request(hostId, _nodeId, cmds, commands.stopOnError(), true);
req.setSequence(agent.getNextSequence());
Answer[] answers = agent.send(req, timeout);
notifyAnswersToMonitors(hostId, req.getSequence(), answers);
commands.setAnswers(answers);
return answers;
}
protected Status investigate(AgentAttache agent) {
Long hostId = agent.getId();
if (s_logger.isDebugEnabled()) {
s_logger.debug("checking if agent (" + hostId + ") is alive");
}
Answer answer = easySend(hostId, new CheckHealthCommand());
if (answer != null && answer.getResult()) {
Status status = Status.Up;
if (s_logger.isDebugEnabled()) {
s_logger.debug("agent (" + hostId + ") responded to checkHeathCommand, reporting that agent is " + status);
}
return status;
}
return _haMgr.investigate(hostId);
}
protected AgentAttache getAttache(final Long hostId) throws AgentUnavailableException {
assert (hostId != null) : "Who didn't check their id value?";
if (hostId == null) {
return null;
}
AgentAttache agent = findAttache(hostId);
if (agent == null) {
s_logger.debug("Unable to find agent for " + hostId);
throw new AgentUnavailableException("Unable to find agent ", hostId);
}
return agent;
}
@Override
public long send(Long hostId, Commands commands, Listener listener) throws AgentUnavailableException {
final AgentAttache agent = getAttache(hostId);
if (agent.isClosed()) {
throw new AgentUnavailableException("Agent " + agent.getId() + " is closed", agent.getId());
}
Command[] cmds = commands.toCommands();
assert cmds.length > 0 : "Why are you sending zero length commands?";
if (cmds.length == 0) {
throw new AgentUnavailableException("Empty command set for agent " + agent.getId(), agent.getId());
}
Request req = new Request(hostId, _nodeId, cmds, commands.stopOnError(), true);
req.setSequence(agent.getNextSequence());
agent.send(req, listener);
return req.getSequence();
}
public void removeAgent(AgentAttache attache, Status nextState) {
if (attache == null) {
return;
}
long hostId = attache.getId();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Remove Agent : " + hostId);
}
AgentAttache removed = null;
boolean conflict = false;
synchronized (_agents) {
removed = _agents.remove(hostId);
if (removed != null && removed != attache) {
conflict = true;
_agents.put(hostId, removed);
removed = attache;
}
}
if (conflict) {
s_logger.debug("Agent for host " + hostId + " is created when it is being disconnected");
}
if (removed != null) {
removed.disconnect(nextState);
}
for (Pair<Integer, Listener> monitor : _hostMonitors) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending Disconnect to listener: " + monitor.second().getClass().getName());
}
monitor.second().processDisconnect(hostId, nextState);
}
}
protected AgentAttache notifyMonitorsOfConnection(AgentAttache attache, final StartupCommand[] cmd, boolean forRebalance) throws ConnectionException {
long hostId = attache.getId();
HostVO host = _hostDao.findById(hostId);
for (Pair<Integer, Listener> monitor : _hostMonitors) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending Connect to listener: " + monitor.second().getClass().getSimpleName());
}
for (int i = 0; i < cmd.length; i++) {
try {
monitor.second().processConnect(host, cmd[i], forRebalance);
} catch (Exception e) {
if (e instanceof ConnectionException) {
ConnectionException ce = (ConnectionException)e;
if (ce.isSetupError()) {
s_logger.warn("Monitor " + monitor.second().getClass().getSimpleName() + " says there is an error in the connect process for " + hostId + " due to " + e.getMessage());
handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected);
throw ce;
} else {
s_logger.info("Monitor " + monitor.second().getClass().getSimpleName() + " says not to continue the connect process for " + hostId + " due to " + e.getMessage());
handleDisconnectWithoutInvestigation(attache, Event.ShutdownRequested);
return attache;
}
} else if (e instanceof HypervisorVersionChangedException) {
handleDisconnectWithoutInvestigation(attache, Event.ShutdownRequested);
throw new CloudRuntimeException("Unable to connect " + attache.getId(), e);
} else {
s_logger.error("Monitor " + monitor.second().getClass().getSimpleName() + " says there is an error in the connect process for " + hostId + " due to " + e.getMessage(), e);
handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected);
throw new CloudRuntimeException("Unable to connect " + attache.getId(), e);
}
}
}
}
Long dcId = host.getDataCenterId();
ReadyCommand ready = new ReadyCommand(dcId);
Answer answer = easySend(hostId, ready);
if (answer == null || !answer.getResult()) {
// this is tricky part for secondary storage
// make it as disconnected, wait for secondary storage VM to be up
// return the attache instead of null, even it is disconnectede
handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected);
}
agentStatusTransitTo(host, Event.Ready, _nodeId);
attache.ready();
return attache;
}
protected boolean notifyCreatorsOfConnection(StartupCommand[] cmd) throws ConnectionException {
boolean handled = false;
for (Pair<Integer, StartupCommandProcessor> monitor : _creationMonitors) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending Connect to creator: "
+ monitor.second().getClass().getSimpleName());
}
handled = monitor.second().processInitialConnect(cmd);
if (handled) {
break;
}
}
return handled;
}
@Override
public boolean start() {
startDirectlyConnectedHosts();
if (_monitor != null) {
_monitor.start();
}
if (_connection != null) {
_connection.start();
}
return true;
}
public void startDirectlyConnectedHosts() {
List<HostVO> hosts = _resourceMgr.findDirectlyConnectedHosts();
for (HostVO host : hosts) {
loadDirectlyConnectedHost(host, false);
}
}
private ServerResource loadResourcesWithoutHypervisor(HostVO host){
String resourceName = host.getResource();
ServerResource resource = null;
try {
Class<?> clazz = Class.forName(resourceName);
Constructor constructor = clazz.getConstructor();
resource = (ServerResource) constructor.newInstance();
} catch (ClassNotFoundException e) {
s_logger.warn("Unable to find class " + host.getResource(), e);
} catch (InstantiationException e) {
s_logger.warn("Unablet to instantiate class " + host.getResource(), e);
} catch (IllegalAccessException e) {
s_logger.warn("Illegal access " + host.getResource(), e);
} catch (SecurityException e) {
s_logger.warn("Security error on " + host.getResource(), e);
} catch (NoSuchMethodException e) {
s_logger.warn("NoSuchMethodException error on " + host.getResource(), e);
} catch (IllegalArgumentException e) {
s_logger.warn("IllegalArgumentException error on " + host.getResource(), e);
} catch (InvocationTargetException e) {
s_logger.warn("InvocationTargetException error on " + host.getResource(), e);
}
if(resource != null){
_hostDao.loadDetails(host);
HashMap<String, Object> params = new HashMap<String, Object>(host.getDetails().size() + 5);
params.putAll(host.getDetails());
params.put("guid", host.getGuid());
params.put("zone", Long.toString(host.getDataCenterId()));
if (host.getPodId() != null) {
params.put("pod", Long.toString(host.getPodId()));
}
if (host.getClusterId() != null) {
params.put("cluster", Long.toString(host.getClusterId()));
String guid = null;
ClusterVO cluster = _clusterDao.findById(host.getClusterId());
if (cluster.getGuid() == null) {
guid = host.getDetail("pool");
} else {
guid = cluster.getGuid();
}
if (guid != null && !guid.isEmpty()) {
params.put("pool", guid);
}
}
params.put("ipaddress", host.getPrivateIpAddress());
params.put("secondary.storage.vm", "false");
params.put("max.template.iso.size", _configDao.getValue(Config.MaxTemplateAndIsoSize.toString()));
params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
try {
resource.configure(host.getName(), params);
} catch (ConfigurationException e) {
s_logger.warn("Unable to configure resource due to " + e.getMessage());
return null;
}
if (!resource.start()) {
s_logger.warn("Unable to start the resource");
return null;
}
}
return resource;
}
@SuppressWarnings("rawtypes")
protected boolean loadDirectlyConnectedHost(HostVO host, boolean forRebalance) {
boolean initialized = false;
ServerResource resource = null;
try {
//load the respective discoverer
Discoverer discoverer = _resourceMgr.getMatchingDiscover(host.getHypervisorType());
if(discoverer == null){
s_logger.info("Could not to find a Discoverer to load the resource: "+ host.getId() +" for hypervisor type: "+host.getHypervisorType());
resource = loadResourcesWithoutHypervisor(host);
}else{
resource = discoverer.reloadResource(host);
}
if(resource == null){
s_logger.warn("Unable to load the resource: "+ host.getId());
return false;
}
initialized = true;
} finally {
if(!initialized) {
if (host != null) {
agentStatusTransitTo(host, Event.AgentDisconnected, _nodeId);
}
}
}
if (forRebalance) {
Host h = _resourceMgr.createHostAndAgent(host.getId(), resource, host.getDetails(), false, null, true);
return (h == null ? false : true);
} else {
_executor.execute(new SimulateStartTask(host.getId(), resource, host.getDetails(), null));
return true;
}
}
protected AgentAttache createAttacheForDirectConnect(HostVO host, ServerResource resource)
throws ConnectionException {
if (resource instanceof DummySecondaryStorageResource || resource instanceof KvmDummyResourceBase) {
return new DummyAttache(this, host.getId(), false);
}
s_logger.debug("create DirectAgentAttache for " + host.getId());
DirectAgentAttache attache = new DirectAgentAttache(this, host.getId(), resource, host.isInMaintenanceStates(), this);
AgentAttache old = null;
synchronized (_agents) {
old = _agents.put(host.getId(), attache);
}
if (old != null) {
old.disconnect(Status.Removed);
}
return attache;
}
@Override
public boolean stop() {
if (_monitor != null) {
_monitor.signalStop();
}
if (_connection != null) {
_connection.stop();
}
s_logger.info("Disconnecting agents: " + _agents.size());
synchronized (_agents) {
for (final AgentAttache agent : _agents.values()) {
final HostVO host = _hostDao.findById(agent.getId());
if (host == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cant not find host " + agent.getId());
}
} else {
if (!agent.forForward()) {
agentStatusTransitTo(host, Event.ManagementServerDown, _nodeId);
}
}
}
}
return true;
}
@Override
public String getName() {
return _name;
}
protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event) {
long hostId = attache.getId();
s_logger.info("Host " + hostId + " is disconnecting with event " + event);
Status nextStatus = null;
HostVO host = _hostDao.findById(hostId);
if (host == null) {
s_logger.warn("Can't find host with " + hostId);
nextStatus = Status.Removed;
} else {
final Status currentStatus = host.getStatus();
if (currentStatus == Status.Down || currentStatus == Status.Alert || currentStatus == Status.Removed) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Host " + hostId + " is already " + currentStatus);
}
nextStatus = currentStatus;
} else {
try {
nextStatus = currentStatus.getNextStatus(event);
} catch (NoTransitionException e) {
String err = "Cannot find next status for " + event + " as current status is " + currentStatus + " for agent " + hostId;
s_logger.debug(err);
throw new CloudRuntimeException(err);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("The next status of agent " + hostId + "is " + nextStatus + ", current status is " + currentStatus);
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deregistering link for " + hostId + " with state " + nextStatus);
}
removeAgent(attache, nextStatus);
if (host != null) {
disconnectAgent(host, event, _nodeId);
}
return true;
}
protected boolean handleDisconnectWithInvestigation(AgentAttache attache, Status.Event event) {
long hostId = attache.getId();
HostVO host = _hostDao.findById(hostId);
if (host != null) {
Status nextStatus = null;
try {
nextStatus = host.getStatus().getNextStatus(event);
} catch (NoTransitionException ne) {
/* Agent may be currently in status of Down, Alert, Removed, namely there is no next status for some events.
* Why this can happen? Ask God not me. I hate there was no piece of comment for code handling race condition.
* God knew what race condition the code dealt with!
*/
}
if (nextStatus == Status.Alert) {
/* OK, we are going to the bad status, let's see what happened */
s_logger.info("Investigating why host " + hostId + " has disconnected with event " + event);
final Status determinedState = investigate(attache);
final Status currentStatus = host.getStatus();
s_logger.info("The state determined is " + determinedState);
if (determinedState == null || determinedState == Status.Down) {
s_logger.error("Host is down: " + host.getId() + "-" + host.getName() + ". Starting HA on the VMs");
event = Status.Event.HostDown;
} else if (determinedState == Status.Up) {
/* Got ping response from host, bring it back*/
s_logger.info("Agent is determined to be up and running");
agentStatusTransitTo(host, Status.Event.Ping, _nodeId);
return false;
} else if (determinedState == Status.Disconnected) {
s_logger.warn("Agent is disconnected but the host is still up: " + host.getId() + "-" + host.getName());
if (currentStatus == Status.Disconnected) {
if (((System.currentTimeMillis() >> 10) - host.getLastPinged()) > _alertWait) {
s_logger.warn("Host " + host.getId() + " has been disconnected pass the time it should be disconnected.");
event = Status.Event.WaitedTooLong;
} else {
s_logger.debug("Host has been determined to be disconnected but it hasn't passed the wait time yet.");
return false;
}
} else if (currentStatus == Status.Up) {
DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
HostPodVO podVO = _podDao.findById(host.getPodId());
String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
if ((host.getType() != Host.Type.SecondaryStorage) && (host.getType() != Host.Type.ConsoleProxy)) {
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host disconnected, " + hostDesc, "If the agent for host [" + hostDesc
+ "] is not restarted within " + _alertWait + " seconds, HA will begin on the VMs");
}
event = Status.Event.AgentDisconnected;
}
} else {
// if we end up here we are in alert state, send an alert
DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
HostPodVO podVO = _podDao.findById(host.getPodId());
String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host in ALERT state, " + hostDesc, "In availability zone " + host.getDataCenterId()
+ ", host is in alert state: " + host.getId() + "-" + host.getName());
}
} else {
s_logger.debug("The next status of Agent " + host.getId() + " is not Alert, no need to investigate what happened");
}
}
handleDisconnectWithoutInvestigation(attache, event);
host = _hostDao.findById(host.getId());
if (host.getStatus() == Status.Alert || host.getStatus() == Status.Down) {
_haMgr.scheduleRestartForVmsOnHost(host, true);
}
return true;
}
protected class DisconnectTask implements Runnable {
AgentAttache _attache;
Status.Event _event;
boolean _investigate;
DisconnectTask(final AgentAttache attache, final Status.Event event, final boolean investigate) {
_attache = attache;
_event = event;
_investigate = investigate;
}
@Override
public void run() {
try {
if (_investigate == true) {
handleDisconnectWithInvestigation(_attache, _event);
} else {
handleDisconnectWithoutInvestigation(_attache, _event);
}
} catch (final Exception e) {
s_logger.error("Exception caught while handling disconnect: ", e);
} finally {
StackMaid.current().exitCleanup();
}
}
}
@Override
public Answer easySend(final Long hostId, final Command cmd) {
try {
Host h = _hostDao.findById(hostId);
if (h == null || h.getRemoved() != null) {
s_logger.debug("Host with id " + hostId + " doesn't exist");
return null;
}
Status status = h.getStatus();
if (!status.equals(Status.Up) && !status.equals(Status.Connecting)) {
s_logger.debug("Can not send command " + cmd + " due to Host " + hostId + " is not up");
return null;
}
final Answer answer = send(hostId, cmd);
if (answer == null) {
s_logger.warn("send returns null answer");
return null;
}
if (s_logger.isDebugEnabled() && answer.getDetails() != null) {
s_logger.debug("Details from executing " + cmd.getClass() + ": " + answer.getDetails());
}
return answer;
} catch (final AgentUnavailableException e) {
s_logger.warn(e.getMessage());
return null;
} catch (final OperationTimedoutException e) {
s_logger.warn("Operation timed out: " + e.getMessage());
return null;
} catch (final Exception e) {
s_logger.warn("Exception while sending", e);
return null;
}
}
@Override
public Answer[] send(final Long hostId, Commands cmds) throws AgentUnavailableException, OperationTimedoutException {
int wait = 0;
for( Command cmd : cmds ) {
if ( cmd.getWait() > wait ) {
wait = cmd.getWait();
}
}
return send(hostId, cmds, wait);
}
@Override
public boolean reconnect(final long hostId) {
HostVO host;
host = _hostDao.findById(hostId);
if (host == null || host.getRemoved() != null) {
s_logger.warn("Unable to find host " + hostId);
return false;
}
if (host.getStatus() != Status.Up && host.getStatus() != Status.Alert && host.getStatus() != Status.Rebalancing) {
s_logger.info("Unable to disconnect host because it is not in the correct state: host=" + hostId + "; Status=" + host.getStatus());
return false;
}
AgentAttache attache = findAttache(hostId);
if (attache == null) {
s_logger.info("Unable to disconnect host because it is not connected to this server: " + hostId);
return false;
}
disconnectWithoutInvestigation(attache, Event.ShutdownRequested);
return true;
}
@Override
public boolean executeUserRequest(long hostId, Event event) throws AgentUnavailableException {
if (event == Event.AgentDisconnected) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Received agent disconnect event for host " + hostId);
}
AgentAttache attache = null;
attache = findAttache(hostId);
if (attache != null) {
handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected);
}
return true;
} else if (event == Event.ShutdownRequested) {
return reconnect(hostId);
}
return false;
}
protected AgentAttache createAttacheForConnect(HostVO host, Link link) throws ConnectionException {
s_logger.debug("create ConnectedAgentAttache for " + host.getId());
AgentAttache attache = new ConnectedAgentAttache(this, host.getId(), link, host.isInMaintenanceStates());
link.attach(attache);
AgentAttache old = null;
synchronized (_agents) {
old = _agents.put(host.getId(), attache);
}
if (old != null) {
old.disconnect(Status.Removed);
}
return attache;
}
//TODO: handle mycloud specific
private AgentAttache handleConnectedAgent(final Link link, final StartupCommand[] startup, Request request) {
AgentAttache attache = null;
StartupAnswer[] answers = new StartupAnswer[startup.length];
try {
HostVO host = _resourceMgr.createHostVOForConnectedAgent(startup);
if (host != null) {
attache = createAttacheForConnect(host, link);
}
Command cmd;
for (int i = 0; i < startup.length; i++) {
cmd = startup[i];
if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) {
answers[i] = new StartupAnswer(startup[i], attache.getId(), getPingInterval());
break;
}
}
}catch (ConnectionException e) {
Command cmd;
for (int i = 0; i < startup.length; i++) {
cmd = startup[i];
if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) {
answers[i] = new StartupAnswer(startup[i], e.toString());
break;
}
}
} catch (IllegalArgumentException e) {
Command cmd;
for (int i = 0; i < startup.length; i++) {
cmd = startup[i];
if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) {
answers[i] = new StartupAnswer(startup[i], e.toString());
break;
}
}
} catch (CloudRuntimeException e) {
Command cmd;
for (int i = 0; i < startup.length; i++) {
cmd = startup[i];
if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) {
answers[i] = new StartupAnswer(startup[i], e.toString());
break;
}
}
}
Response response = null;
if (attache != null) {
response = new Response(request, answers[0], _nodeId, attache.getId());
} else {
response = new Response(request, answers[0], _nodeId, -1);
}
try {
link.send(response.toBytes());
} catch (ClosedChannelException e) {
s_logger.debug("Failed to send startupanswer: " + e.toString());
return null;
}
if (attache == null) {
return null;
}
try {
attache = notifyMonitorsOfConnection(attache, startup, false);
return attache;
} catch (ConnectionException e) {
ReadyCommand ready = new ReadyCommand(null);
ready.setDetails(e.toString());
try {
easySend(attache.getId(), ready);
} catch (Exception e1) {
s_logger.debug("Failed to send readycommand, due to " + e.toString());
}
return null;
} catch (CloudRuntimeException e) {
ReadyCommand ready = new ReadyCommand(null);
ready.setDetails(e.toString());
try {
easySend(attache.getId(), ready);
} catch (Exception e1) {
s_logger.debug("Failed to send readycommand, due to " + e.toString());
}
return null;
}
}
protected class SimulateStartTask implements Runnable {
ServerResource resource;
Map<String, String> details;
long id;
ActionDelegate<Long> actionDelegate;
public SimulateStartTask(long id, ServerResource resource, Map<String, String> details, ActionDelegate<Long> actionDelegate) {
this.id = id;
this.resource = resource;
this.details = details;
this.actionDelegate = actionDelegate;
}
@Override
public void run() {
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Simulating start for resource " + resource.getName() + " id " + id);
}
_resourceMgr.createHostAndAgent(id, resource, details, false, null, false);
} catch (Exception e) {
s_logger.warn("Unable to simulate start on resource " + id + " name " + resource.getName(), e);
} finally {
if (actionDelegate != null) {
actionDelegate.action(new Long(id));
}
StackMaid.current().exitCleanup();
}
}
}
public class AgentHandler extends Task {
public AgentHandler(Task.Type type, Link link, byte[] data) {
super(type, link, data);
}
protected void processRequest(final Link link, final Request request) {
AgentAttache attache = (AgentAttache) link.attachment();
final Command[] cmds = request.getCommands();
Command cmd = cmds[0];
boolean logD = true;
Response response = null;
if (attache == null) {
request.logD("Processing the first command ");
if (!(cmd instanceof StartupCommand)) {
s_logger.warn("Throwing away a request because it came through as the first command on a connect: " + request);
return;
}
StartupCommand[] startups = new StartupCommand[cmds.length];
for (int i = 0; i < cmds.length; i++) {
startups[i] = (StartupCommand) cmds[i];
}
attache = handleConnectedAgent(link, startups, request);
if (attache == null) {
s_logger.warn("Unable to create attache for agent: " + request);
}
return;
}
final long hostId = attache.getId();
if (s_logger.isDebugEnabled()) {
if (cmd instanceof PingRoutingCommand) {
final PingRoutingCommand ping = (PingRoutingCommand) cmd;
if (ping.getNewStates().size() > 0) {
s_logger.debug("SeqA " + hostId + "-" + request.getSequence() + ": Processing " + request);
} else {
logD = false;
s_logger.debug("Ping from " + hostId);
s_logger.trace("SeqA " + hostId + "-" + request.getSequence() + ": Processing " + request);
}
} else if (cmd instanceof PingCommand) {
logD = false;
s_logger.debug("Ping from " + hostId);
s_logger.trace("SeqA " + attache.getId() + "-" + request.getSequence() + ": Processing " + request);
} else {
s_logger.debug("SeqA " + attache.getId() + "-" + request.getSequence() + ": Processing " + request);
}
}
final Answer[] answers = new Answer[cmds.length];
for (int i = 0; i < cmds.length; i++) {
cmd = cmds[i];
Answer answer = null;
try {
if (cmd instanceof StartupRoutingCommand) {
final StartupRoutingCommand startup = (StartupRoutingCommand) cmd;
answer = new StartupAnswer(startup, attache.getId(), getPingInterval());
} else if (cmd instanceof StartupProxyCommand) {
final StartupProxyCommand startup = (StartupProxyCommand) cmd;
answer = new StartupAnswer(startup, attache.getId(), getPingInterval());
} else if (cmd instanceof StartupSecondaryStorageCommand) {
final StartupSecondaryStorageCommand startup = (StartupSecondaryStorageCommand) cmd;
answer = new StartupAnswer(startup, attache.getId(), getPingInterval());
} else if (cmd instanceof StartupStorageCommand) {
final StartupStorageCommand startup = (StartupStorageCommand) cmd;
answer = new StartupAnswer(startup, attache.getId(), getPingInterval());
} else if (cmd instanceof ShutdownCommand) {
final ShutdownCommand shutdown = (ShutdownCommand) cmd;
final String reason = shutdown.getReason();
s_logger.info("Host " + attache.getId() + " has informed us that it is shutting down with reason " + reason + " and detail " + shutdown.getDetail());
if (reason.equals(ShutdownCommand.Update)) {
//disconnectWithoutInvestigation(attache, Event.UpdateNeeded);
throw new CloudRuntimeException("Agent update not implemented");
} else if (reason.equals(ShutdownCommand.Requested)) {
disconnectWithoutInvestigation(attache, Event.ShutdownRequested);
}
return;
} else if (cmd instanceof AgentControlCommand) {
answer = handleControlCommand(attache, (AgentControlCommand) cmd);
} else {
handleCommands(attache, request.getSequence(), new Command[] { cmd });
if (cmd instanceof PingCommand) {
long cmdHostId = ((PingCommand) cmd).getHostId();
// if the router is sending a ping, verify the
// gateway was pingable
if (cmd instanceof PingRoutingCommand) {
boolean gatewayAccessible = ((PingRoutingCommand) cmd).isGatewayAccessible();
HostVO host = _hostDao.findById(Long.valueOf(cmdHostId));
if (!gatewayAccessible) {
// alert that host lost connection to
// gateway (cannot ping the default route)
DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
HostPodVO podVO = _podDao.findById(host.getPodId());
String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId(), "Host lost connection to gateway, " + hostDesc, "Host [" + hostDesc
+ "] lost connection to gateway (default route) and is possibly having network connection issues.");
} else {
_alertMgr.clearAlert(AlertManager.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId());
}
}
answer = new PingAnswer((PingCommand) cmd);
} else if (cmd instanceof ReadyAnswer) {
HostVO host = _hostDao.findById(attache.getId());
if (host == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cant not find host " + attache.getId());
}
}
answer = new Answer(cmd);
} else {
answer = new Answer(cmd);
}
}
} catch (final Throwable th) {
s_logger.warn("Caught: ", th);
answer = new Answer(cmd, false, th.getMessage());
}
answers[i] = answer;
}
response = new Response(request, answers, _nodeId, attache.getId());
if (s_logger.isDebugEnabled()) {
if (logD) {
s_logger.debug("SeqA " + attache.getId() + "-" + response.getSequence() + ": Sending " + response);
} else {
s_logger.trace("SeqA " + attache.getId() + "-" + response.getSequence() + ": Sending " + response);
}
}
try {
link.send(response.toBytes());
} catch (final ClosedChannelException e) {
s_logger.warn("Unable to send response because connection is closed: " + response);
}
}
protected void processResponse(final Link link, final Response response) {
final AgentAttache attache = (AgentAttache) link.attachment();
if (attache == null) {
s_logger.warn("Unable to process: " + response);
}
if (!attache.processAnswers(response.getSequence(), response)) {
s_logger.info("Host " + attache.getId() + " - Seq " + response.getSequence() + ": Response is not processed: " + response);
}
}
@Override
protected void doTask(final Task task) throws Exception {
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
try {
final Type type = task.getType();
if (type == Task.Type.DATA) {
final byte[] data = task.getData();
try {
final Request event = Request.parse(data);
if (event instanceof Response) {
processResponse(task.getLink(), (Response) event);
} else {
processRequest(task.getLink(), event);
}
} catch (final UnsupportedVersionException e) {
s_logger.warn(e.getMessage());
// upgradeAgent(task.getLink(), data, e.getReason());
}
} else if (type == Task.Type.CONNECT) {
} else if (type == Task.Type.DISCONNECT) {
final Link link = task.getLink();
final AgentAttache attache = (AgentAttache) link.attachment();
if (attache != null) {
disconnectWithInvestigation(attache, Event.AgentDisconnected);
} else {
s_logger.info("Connection from " + link.getIpAddress() + " closed but no cleanup was done.");
link.close();
link.terminated();
}
}
} finally {
StackMaid.current().exitCleanup();
txn.close();
}
}
}
protected AgentManagerImpl() {
}
@Override
public boolean tapLoadingAgents(Long hostId, TapAgentsAction action) {
synchronized (_loadingAgents) {
if (action == TapAgentsAction.Add) {
_loadingAgents.add(hostId);
} else if (action == TapAgentsAction.Del) {
_loadingAgents.remove(hostId);
} else if (action == TapAgentsAction.Contains) {
return _loadingAgents.contains(hostId);
} else {
throw new CloudRuntimeException("Unkonwn TapAgentsAction " + action);
}
}
return true;
}
@Override
public boolean agentStatusTransitTo(HostVO host, Status.Event e, long msId) {
try {
_agentStatusLock.lock();
if (status_logger.isDebugEnabled()) {
ResourceState state = host.getResourceState();
StringBuilder msg = new StringBuilder("Transition:");
msg.append("[Resource state = ").append(state);
msg.append(", Agent event = ").append(e.toString());
msg.append(", Host id = ").append(host.getId()).append(", name = " + host.getName()).append("]");
status_logger.debug(msg);
}
host.setManagementServerId(msId);
try {
return _statusStateMachine.transitTo(host, e, host.getId(), _hostDao);
} catch (NoTransitionException e1) {
status_logger.debug("Cannot transit agent status with event " + e + " for host " + host.getId() + ", name=" + host.getName()
+ ", mangement server id is " + msId);
throw new CloudRuntimeException("Cannot transit agent status with event " + e + " for host " + host.getId() + ", mangement server id is "
+ msId + "," + e1.getMessage());
}
} finally {
_agentStatusLock.unlock();
}
}
public boolean disconnectAgent(HostVO host, Status.Event e, long msId) {
host.setDisconnectedOn(new Date());
if (e.equals(Status.Event.Remove)) {
host.setGuid(null);
host.setClusterId(null);
}
return agentStatusTransitTo(host, e, msId);
}
protected void disconnectWithoutInvestigation(AgentAttache attache, final Status.Event event) {
_executor.submit(new DisconnectTask(attache, event, false));
}
protected void disconnectWithInvestigation(AgentAttache attache, final Status.Event event) {
_executor.submit(new DisconnectTask(attache, event, true));
}
private void disconnectInternal(final long hostId, final Status.Event event, boolean invstigate) {
AgentAttache attache = findAttache(hostId);
if (attache != null) {
if (!invstigate) {
disconnectWithoutInvestigation(attache, event);
} else {
disconnectWithInvestigation(attache, event);
}
} else {
/* Agent is still in connecting process, don't allow to disconnect right away */
if (tapLoadingAgents(hostId, TapAgentsAction.Contains)) {
s_logger.info("Host " + hostId + " is being loaded so no disconnects needed.");
return;
}
HostVO host = _hostDao.findById(hostId);
if (host != null && host.getRemoved() == null) {
disconnectAgent(host, event, _nodeId);
}
}
}
public void disconnectWithInvestigation(final long hostId, final Status.Event event) {
disconnectInternal(hostId, event, true);
}
@Override
public void disconnectWithoutInvestigation(final long hostId, final Status.Event event) {
disconnectInternal(hostId, event, false);
}
@Override
public AgentAttache handleDirectConnectAgent(HostVO host, StartupCommand[] cmds, ServerResource resource, boolean forRebalance) throws ConnectionException {
AgentAttache attache;
attache = createAttacheForDirectConnect(host, resource);
StartupAnswer[] answers = new StartupAnswer[cmds.length];
for (int i = 0; i < answers.length; i++) {
answers[i] = new StartupAnswer(cmds[i], attache.getId(), _pingInterval);
}
attache.process(answers);
attache = notifyMonitorsOfConnection(attache, cmds, forRebalance);
return attache;
}
@Override
public void pullAgentToMaintenance(long hostId) {
AgentAttache attache = findAttache(hostId);
if (attache != null) {
attache.setMaintenanceMode(true);
// Now cancel all of the commands except for the active one.
attache.cancelAllCommands(Status.Disconnected, false);
}
}
@Override
public void pullAgentOutMaintenance(long hostId) {
AgentAttache attache = findAttache(hostId);
if (attache != null) {
attache.setMaintenanceMode(false);
}
}
}
|
package io.spine.server.commandbus;
import com.google.protobuf.Message;
import io.spine.base.Identifier;
import io.spine.core.CommandId;
import io.spine.type.TypeName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.validate.Validate.checkNotEmptyOrBlank;
import static java.lang.String.format;
/**
* Convenience wrapper for logging errors and warnings.
*
* @author Alexander Yevsyukov
*/
public class Log {
/** The logger instance used by {@code CommandBus}. */
static Logger log() {
return LogSingleton.INSTANCE.value;
}
void errorExpiredCommand(Message commandMsg, CommandId id) {
String msg = formatMessageTypeAndId(
"Expired scheduled command `%s` (ID: `%s`).",
commandMsg,
id);
log().error(msg);
}
/**
* Creates a formatted string with type of the command message and command ID.
*
* <p>The {@code format} string must have two {@code %s} format specifiers.
* The first specifier is for message type name. The second is for command ID.
*
* @param format the format string
* @param commandId the ID of the command
* @return formatted string
*/
private static String formatMessageTypeAndId(String format,
Message commandMessage,
CommandId commandId) {
checkNotNull(format);
checkNotEmptyOrBlank(format, "format string");
String cmdType = TypeName.of(commandMessage)
.value();
String id = Identifier.toString(commandId);
String result = format(format, cmdType, id);
return result;
}
private enum LogSingleton {
INSTANCE;
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private final Logger value = LoggerFactory.getLogger(CommandBus.class);
}
}
|
package org.mg.server;
import static org.jboss.netty.channel.Channels.pipeline;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.util.CharsetUtil;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.littleshoot.proxy.Launcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultXmppProxy implements XmppProxy {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ClientSocketChannelFactory channelFactory =
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
private final ConcurrentHashMap<String, ChannelFuture> connections =
new ConcurrentHashMap<String, ChannelFuture>();
public DefaultXmppProxy() {
// Start the HTTP proxy server that we relay data to. It has more
// developed logic for handling different types of requests, and we'd
// otherwise have to duplicate that here.
Launcher.main("7777");
}
public void start() throws XMPPException, IOException {
final Properties props = new Properties();
final File propsDir = new File(System.getProperty("user.home"), ".mg");
final File propsFile = new File(propsDir, "mg.properties");
if (!propsFile.isFile()) {
System.err.println("No properties file found at "+propsFile+
". That file is required and must contain a property for " +
"'user' and 'pass'.");
System.exit(0);
}
props.load(new FileInputStream(propsFile));
final String user = props.getProperty("google.server.user");
final String pass = props.getProperty("google.server.pwd");
final Collection<XMPPConnection> xmppConnections =
new ArrayList<XMPPConnection>();
for (int i = 0; i < 10; i++) {
// We create a bunch of connections to allow us to process as much
// incoming data as possible.
final XMPPConnection xmpp = newConnection(user, pass);
xmppConnections.add(xmpp);
log.info("Created connection for user: {}", xmpp.getUser());
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
for (final XMPPConnection conn : xmppConnections) {
log.info("Disconnecting user: {}", conn.getUser());
conn.disconnect();
}
}
}, "XMPP-Disconnect-On-Shutdown"));
}
private XMPPConnection newConnection(final String user, final String pass) {
for (int i = 0; i < 10; i++) {
try {
return newSingleConnection(user, pass);
} catch (final XMPPException e) {
log.error("Could not create XMPP connection", e);
}
}
throw new RuntimeException("Could not connect to XMPP server");
}
private XMPPConnection newSingleConnection(final String user,
final String pass) throws XMPPException {
final ConnectionConfiguration config =
new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
config.setCompressionEnabled(true);
final XMPPConnection conn = new XMPPConnection(config);
conn.connect();
conn.login(user, pass, "MG");
final Roster roster = conn.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
final ChatManager cm = conn.getChatManager();
final ChatManagerListener listener = new ChatManagerListener() {
private ChannelFuture cf;
public void chatCreated(final Chat chat,
final boolean createdLocally) {
log.info("Created a chat!!");
// We need to listen for the unavailability of clients we're
// chatting with so we can disconnect from their associated
// remote servers.
final PacketListener pl = new PacketListener() {
public void processPacket(final Packet pack) {
if (!(pack instanceof Presence)) return;
final Presence pres = (Presence) pack;
final String from = pres.getFrom();
final String participant = chat.getParticipant();
log.info("Comparing presence packet from "+from+
" to particant "+participant);
if (from.equals(participant) && !pres.isAvailable()) {
if (cf != null) {
log.info("Closing channel to local proxy");
cf.getChannel().close();
}
}
}
};
// Register the listener.
conn.addPacketListener(pl, null);
final MessageListener ml = new MessageListener() {
public void processMessage(final Chat ch, final Message msg) {
log.info("Got message!!");
log.info("Property names: {}", msg.getPropertyNames());
final String closeString =
(String) msg.getProperty("CLOSE");
final boolean close;
if (closeString.trim().equalsIgnoreCase("close")) {
close = true;
}
else {
close = false;
final String data = (String) msg.getProperty("HTTP");
if (StringUtils.isBlank(data)) {
log.warn("HTTP IS BLANK?? IGNORING...");
return;
}
}
// TODO: Check the sequence number??
final ChannelBuffer cb = xmppToHttpChannelBuffer(msg);
if (close) {
log.info("Received close from client...closing " +
"connection to the proxy");
cf.getChannel().close();
return;
}
log.info("Getting channel future...");
cf = getChannelFuture(msg, chat);
if (cf == null) {
log.warn("Null channel future! Returning");
return;
}
log.info("Got channel: {}", cf);
if (cf.getChannel().isConnected()) {
cf.getChannel().write(cb);
}
else {
cf.addListener(new ChannelFutureListener() {
public void operationComplete(
final ChannelFuture future)
throws Exception {
cf.getChannel().write(cb);
}
});
}
}
};
chat.addMessageListener(ml);
}
};
cm.addChatListener(listener);
return conn;
}
private ChannelBuffer xmppToHttpChannelBuffer(final Message msg) {
final String data = (String) msg.getProperty("HTTP");
final byte[] raw =
Base64.decodeBase64(data.getBytes(CharsetUtil.UTF_8));
return ChannelBuffers.wrappedBuffer(raw);
}
/**
* This gets a channel to connect to the local HTTP proxy on. This is
* slightly complex, as we're trying to mimic the state as if this HTTP
* request is coming in to a "normal" LittleProxy instance instead of
* having the traffic tunneled through XMPP. So we create a separate
* connection to the proxy just as those separate connections were made
* from the browser to the proxy originally on the remote end.
*
* If there's already an existing connection mimicking the original
* connection, we use that.
*
* @param key The key for the remote IP/port pair.
* @param chat The chat session across Google Talk -- we need this to
* send responses back to the original caller.
* @return The {@link ChannelFuture} that will connect to the local
* LittleProxy instance.
*/
private ChannelFuture getChannelFuture(final Message message,
final Chat chat) {
// The other side will also need to know where the
// request came from to differentiate incoming HTTP
// connections.
log.info("Getting properties...");
// Not these will fail if the original properties were not set as
// strings.
//final String remoteIp =
// (String) message.getProperty("LOCAL-IP");
//final String localIp =
// (String) message.getProperty("REMOTE-IP");
final String mac =
(String) message.getProperty("MAC");
final String hc =
(String) message.getProperty("HASHCODE");
// We can sometimes get messages back that were not intended for us.
// Just ignore them.
if (mac == null || hc == null) {
log.error("Message not intended for us?!?!?\n" +
"Null MAC and/or HASH and to: "+message.getTo());
return null;
}
final String key = mac + hc;
log.info("Getting channel future for key: {}", key);
synchronized (connections) {
if (connections.containsKey(key)) {
log.info("Using existing connection");
return connections.get(key);
}
// Configure the client.
final ClientBootstrap cb = new ClientBootstrap(this.channelFactory);
final ChannelPipelineFactory cpf = new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
final ChannelPipeline pipeline = pipeline();
final class HttpChatRelay extends SimpleChannelUpstreamHandler {
private long sequenceNumber = 0L;
@Override
public void messageReceived(
final ChannelHandlerContext ctx,
final MessageEvent me) throws Exception {
log.info("HTTP message received from proxy on " +
"relayer: {}", me.getMessage());
final Message msg = new Message();
final ByteBuffer buf =
((ChannelBuffer) me.getMessage()).toByteBuffer();
final byte[] raw = toRawBytes(buf);
final String base64 =
Base64.encodeBase64URLSafeString(raw);
msg.setTo(chat.getParticipant());
msg.setProperty("HTTP", base64);
msg.setProperty("MD5", toMd5(raw));
msg.setProperty("SEQ", sequenceNumber);
msg.setProperty("HASHCODE", hc);
chat.sendMessage(msg);
sequenceNumber++;
}
@Override
public void channelClosed(final ChannelHandlerContext ctx,
final ChannelStateEvent cse) {
// We need to send the CLOSE directive to the other
// side VIA google talk to simulate the proxy
// closing the connection to the browser.
log.info("Got channel closed on C in A->B->C->D chain...");
final Message msg = new Message();
msg.setProperty("CLOSE", "true");
try {
chat.sendMessage(msg);
} catch (final XMPPException e) {
log.warn("Error sending close message", e);
}
connections.remove(key);
}
}
pipeline.addLast("handler", new HttpChatRelay());
return pipeline;
}
};
// Set up the event pipeline factory.
cb.setPipelineFactory(cpf);
cb.setOption("connectTimeoutMillis", 40*1000);
log.info("Connecting to localhost proxy");
final ChannelFuture future =
cb.connect(new InetSocketAddress("127.0.0.1", 7777));
connections.put(key, future);
return future;
}
}
private String toMd5(final byte[] raw) {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
final byte[] digest = md.digest(raw);
return Base64.encodeBase64URLSafeString(digest);
} catch (final NoSuchAlgorithmException e) {
log.error("No MD5 -- will never happen", e);
return "NO MD5";
}
}
public static byte[] toRawBytes(final ByteBuffer buf) {
final int mark = buf.position();
final byte[] bytes = new byte[buf.remaining()];
buf.get(bytes);
buf.position(mark);
return bytes;
}
}
|
package org.mg.server;
import static org.jboss.netty.channel.Channels.pipeline;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.util.CharsetUtil;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.littleshoot.proxy.Launcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultXmppProxy implements XmppProxy {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ClientSocketChannelFactory channelFactory =
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
private final ConcurrentHashMap<String, ChannelFuture> connections =
new ConcurrentHashMap<String, ChannelFuture>();
public DefaultXmppProxy() {
// Start the HTTP proxy server that we relay data to. It has more
// developed logic for handling different types of requests, and we'd
// otherwise have to duplicate that here.
Launcher.main("7777");
}
public void start() throws XMPPException, IOException {
final Properties props = new Properties();
final File propsDir = new File(System.getProperty("user.home"), ".mg");
final File propsFile = new File(propsDir, "mg.properties");
if (!propsFile.isFile()) {
System.err.println("No properties file found at "+propsFile+
". That file is required and must contain a property for " +
"'user' and 'pass'.");
System.exit(0);
}
props.load(new FileInputStream(propsFile));
final String user = props.getProperty("google.server.user");
final String pass = props.getProperty("google.server.pwd");
for (int i = 0; i < 10; i++) {
// We create a bunch of connections to allow us to process as much
// incoming data as possible.
final XMPPConnection xmpp = newConnection(user, pass);
log.info("Created connection to: {}", xmpp);
}
}
private XMPPConnection newConnection(final String user, final String pass) {
for (int i = 0; i < 10; i++) {
try {
return newSingleConnection(user, pass);
} catch (final XMPPException e) {
log.error("Could not create XMPP connection", e);
}
}
throw new RuntimeException("Could not connect to XMPP server");
}
private XMPPConnection newSingleConnection(final String user,
final String pass)
throws XMPPException {
final ConnectionConfiguration config =
new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
config.setCompressionEnabled(true);
final XMPPConnection conn = new XMPPConnection(config);
conn.connect();
conn.login(user, pass, "MG");
final ChatManager cm = conn.getChatManager();
final ChatManagerListener listener = new ChatManagerListener() {
public void chatCreated(final Chat chat,
final boolean createdLocally) {
log.info("Created a chat!!");
final MessageListener ml = new MessageListener() {
public void processMessage(final Chat ch, final Message msg) {
log.info("Got message!!");
log.info("Property names: {}", msg.getPropertyNames());
final String data = (String) msg.getProperty("HTTP");
if (StringUtils.isBlank(data)) {
log.warn("HTTP IS BLANK?? IGNORING...");
return;
}
// TODO: Check the sequence number??
final ChannelBuffer cb = xmppToHttpChannelBuffer(msg);
log.info("Getting channel future...");
final ChannelFuture cf = getChannelFuture(msg, ch);
log.info("Got channel: {}", cf);
if (cf.getChannel().isConnected()) {
cf.getChannel().write(cb);
}
else {
cf.addListener(new ChannelFutureListener() {
public void operationComplete(
final ChannelFuture future)
throws Exception {
cf.getChannel().write(cb);
}
});
}
}
};
chat.addMessageListener(ml);
}
};
cm.addChatListener(listener);
return conn;
}
private ChannelBuffer xmppToHttpChannelBuffer(final Message msg) {
final String data = (String) msg.getProperty("HTTP");
final byte[] raw =
Base64.decodeBase64(data.getBytes(CharsetUtil.UTF_8));
return ChannelBuffers.wrappedBuffer(raw);
}
/**
* This gets a channel to connect to the local HTTP proxy on. This is
* slightly complex, as we're trying to mimic the state as if this HTTP
* request is coming in to a "normal" LittleProxy instance instead of
* having the traffic tunneled through XMPP. So we create a separate
* connection to the proxy just as those separate connections were made
* from the browser to the proxy originally on the remote end.
*
* If there's already an existing connection mimicking the original
* connection, we use that.
*
* @param key The key for the remote IP/port pair.
* @param chat The chat session across Google Talk -- we need this to
* send responses back to the original caller.
* @return The {@link ChannelFuture} that will connect to the local
* LittleProxy instance.
*/
private ChannelFuture getChannelFuture(final Message message,
final Chat chat) {
// The other side will also need to know where the
// request came from to differentiate incoming HTTP
// connections.
log.info("Getting properties...");
// Not these will fail if the original properties were not set as
// strings.
final String remoteIp =
(String) message.getProperty("LOCAL-IP");
final String localIp =
(String) message.getProperty("REMOTE-IP");
final String MAC =
(String) message.getProperty("MAC");
final String HASHCODE =
(String) message.getProperty("HASHCODE");
final String key = MAC + HASHCODE;
log.info("Getting channel future...");
synchronized (connections) {
if (connections.containsKey(key)) {
log.info("Using existing connection");
return connections.get(key);
}
// Configure the client.
final ClientBootstrap cb = new ClientBootstrap(this.channelFactory);
final ChannelPipelineFactory cpf = new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
final ChannelPipeline pipeline = pipeline();
final class HttpChatRelay extends SimpleChannelUpstreamHandler {
@Override
public void messageReceived(
final ChannelHandlerContext ctx,
final MessageEvent me) throws Exception {
log.info("HTTP message received from proxy on " +
"relayer: {}", me.getMessage());
final Message msg = new Message();
final ByteBuffer buf =
((ChannelBuffer) me.getMessage()).toByteBuffer();
final byte[] raw = toRawBytes(buf);
final String base64 = Base64.encodeBase64String(raw);
//TODO: Set the sequence number??
msg.setProperty("HTTP", base64);
msg.setProperty("MD5", toMd5(raw));
chat.sendMessage(msg);
}
@Override
public void channelClosed(final ChannelHandlerContext ctx,
final ChannelStateEvent cse) {
// We need to send the CLOSE directive to the other
// side VIA google talk to simulate the proxy
// closing the connection to the browser.
log.info("Got channel closed on C in A->B->C->D chain...");
final Message msg = new Message();
msg.setProperty("CLOSE", "true");
try {
chat.sendMessage(msg);
} catch (final XMPPException e) {
log.warn("Error sending close message", e);
}
connections.remove(key);
}
}
pipeline.addLast("handler", new HttpChatRelay());
return pipeline;
}
};
// Set up the event pipeline factory.
cb.setPipelineFactory(cpf);
cb.setOption("connectTimeoutMillis", 40*1000);
log.info("Connecting to localhost proxy");
final ChannelFuture future =
cb.connect(new InetSocketAddress("127.0.0.1", 7777));
connections.put(key, future);
return future;
}
}
private String toMd5(final byte[] raw) {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
final byte[] digest = md.digest(raw);
return Base64.encodeBase64String(digest);
} catch (final NoSuchAlgorithmException e) {
log.error("No MD5 -- will never happen", e);
return "NO MD5";
}
}
public static byte[] toRawBytes(final ByteBuffer buf) {
final int mark = buf.position();
final byte[] bytes = new byte[buf.remaining()];
buf.get(bytes);
buf.position(mark);
return bytes;
}
/*
private void readRequest(final FileTransferRequest request)
throws XMPPException, IOException {
final IncomingFileTransfer itf = request.accept();
final long fileSize = request.getFileSize();
final InputStream in = itf.recieveFile();
final byte[] b = new byte[BUFFER_SIZE];
int count = 0;
int amountWritten = 0;
// We actually write to a file here because it could be a large POST
// request.
final File tempFile =
File.createTempFile(String.valueOf(request.hashCode()), null);
final OutputStream out = new FileOutputStream(tempFile);
do {
// write to the output stream
try {
out.write(b, 0, count);
} catch (IOException e) {
throw new XMPPException("error writing to output stream", e);
}
amountWritten += count;
// read more bytes from the input stream
try {
count = in.read(b);
} catch (IOException e) {
throw new XMPPException("error reading from input stream", e);
}
} while (count != -1 && !itf.getStatus().equals(Status.cancelled));
// the connection was likely terminated abrubtly if these are not equal
if (!itf.getStatus().equals(Status.cancelled) &&
itf.getError() == Error.none && amountWritten != fileSize) {
itf.setStatus(Status.error);
itf.setError(Error.connection);
}
System.out.println("Read: "+IOUtils.toString(new FileInputStream(tempFile)));
}
*/
}
|
package com.edinarobotics.zeke.vision;
import com.edinarobotics.utils.log.Level;
import com.edinarobotics.utils.log.LogSystem;
import com.edinarobotics.utils.log.Logger;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
/**
*
* @author GreenMachine
*/
public class VisionConnectThread extends Thread {
private int port;
private Logger logger;
private volatile boolean stop;
private VisionServer server;
private VisionReadingThread currentReadingThread;
public VisionConnectThread(int port, VisionServer server) {
this.port = port;
this.logger = LogSystem.getLogger("zeke.vision.conn");
stop = false;
this.server = server;
}
public void requestStop() {
this.stop = true;
if (currentReadingThread != null) {
currentReadingThread.requestStop();
}
}
public VisionReadingThread getReadingThread() {
return currentReadingThread;
}
public void run() {
ServerSocketConnection serverSocket = null;
try {
serverSocket = (ServerSocketConnection) Connector.open("socket://:"+port);
while (!stop) {
try {
if (currentReadingThread != null && currentReadingThread.isAlive()) {
currentReadingThread.join();
}
SocketConnection connection = (SocketConnection) serverSocket.acceptAndOpen();
currentReadingThread = new VisionReadingThread(connection, server);
currentReadingThread.start();
Thread.sleep(100);
} catch (InterruptedException e) {
logger.log(Level.INFO, "Vision connect thread interrupted.");
e.printStackTrace();
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Failed to receive new connections.");
e.printStackTrace();
} finally {
// Close the server socket if we need to.
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ex) {
logger.log(Level.SEVERE, "Failed to close server socket.");
}
}
}
logger.log(Level.INFO, "Vision connect thread exited.");
}
}
|
package acr.browser.lightning.view;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import com.squareup.otto.Bus;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.util.Map;
import javax.inject.Inject;
import acr.browser.lightning.R;
import acr.browser.lightning.app.BrowserApp;
import acr.browser.lightning.bus.BrowserEvents;
import acr.browser.lightning.constant.BookmarkPage;
import acr.browser.lightning.constant.Constants;
import acr.browser.lightning.constant.HistoryPage;
import acr.browser.lightning.constant.StartPage;
import acr.browser.lightning.controller.UIController;
import acr.browser.lightning.dialog.LightningDialogBuilder;
import acr.browser.lightning.download.LightningDownloadListener;
import acr.browser.lightning.preference.PreferenceManager;
import acr.browser.lightning.utils.ProxyUtils;
import acr.browser.lightning.utils.ThemeUtils;
import acr.browser.lightning.utils.UrlUtils;
import acr.browser.lightning.utils.Utils;
public class LightningView {
public static final String HEADER_REQUESTED_WITH = "X-Requested-With";
public static final String HEADER_WAP_PROFILE = "X-Wap-Profile";
public static final String HEADER_DNT = "DNT";
final LightningViewTitle mTitle;
private WebView mWebView;
final boolean mIsIncognitoTab;
private final UIController mUIController;
private final GestureDetector mGestureDetector;
private final Activity mActivity;
private static String mHomepage;
private static String mDefaultUserAgent;
private final Paint mPaint = new Paint();
private boolean isForegroundTab;
private boolean mInvertPage = false;
private boolean mToggleDesktop = false;
private static float mMaxFling;
private static final int API = android.os.Build.VERSION.SDK_INT;
private static final int SCROLL_UP_THRESHOLD = Utils.dpToPx(10);
private static final float[] mNegativeColorArray = {
-1.0f, 0, 0, 0, 255, // red
0, -1.0f, 0, 0, 255, // green
0, 0, -1.0f, 0, 255, // blue
0, 0, 0, 1.0f, 0 // alpha
};
private final WebViewHandler mWebViewHandler = new WebViewHandler(this);
private final Map<String, String> mRequestHeaders = new ArrayMap<>();
@Inject
Bus mEventBus;
@Inject
PreferenceManager mPreferences;
@Inject
LightningDialogBuilder mBookmarksDialogBuilder;
@SuppressLint("NewApi")
public LightningView(Activity activity, String url, boolean isIncognito) {
BrowserApp.getAppComponent().inject(this);
mActivity = activity;
mUIController = (UIController) activity;
mWebView = new WebView(activity);
mIsIncognitoTab = isIncognito;
mTitle = new LightningViewTitle(activity, mUIController.getUseDarkTheme());
mMaxFling = ViewConfiguration.get(activity).getScaledMaximumFlingVelocity();
mWebView.setDrawingCacheBackgroundColor(Color.WHITE);
mWebView.setFocusableInTouchMode(true);
mWebView.setFocusable(true);
mWebView.setDrawingCacheEnabled(false);
mWebView.setWillNotCacheDrawing(true);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
//noinspection deprecation
mWebView.setAnimationCacheEnabled(false);
//noinspection deprecation
mWebView.setAlwaysDrawnWithCacheEnabled(false);
}
mWebView.setBackgroundColor(Color.WHITE);
mWebView.setScrollbarFadingEnabled(true);
mWebView.setSaveEnabled(true);
mWebView.setNetworkAvailable(true);
mWebView.setWebChromeClient(new LightningChromeClient(activity, this));
mWebView.setWebViewClient(new LightningWebClient(activity, this));
mWebView.setDownloadListener(new LightningDownloadListener(activity));
mGestureDetector = new GestureDetector(activity, new CustomGestureListener());
mWebView.setOnTouchListener(new TouchListener());
mDefaultUserAgent = mWebView.getSettings().getUserAgentString();
initializeSettings(mWebView.getSettings(), activity);
initializePreferences(mWebView.getSettings(), activity);
if (url != null) {
if (!url.trim().isEmpty()) {
mWebView.loadUrl(url, mRequestHeaders);
} else {
// don't load anything, the user is looking for a blank tab
}
} else {
loadHomepage();
}
}
public void loadHomepage() {
if (mWebView == null) {
return;
}
if (mHomepage.startsWith("about:home")) {
mWebView.loadUrl(StartPage.getHomepage(mActivity), mRequestHeaders);
} else if (mHomepage.startsWith("about:bookmarks")) {
loadBookmarkpage();
} else {
mWebView.loadUrl(mHomepage, mRequestHeaders);
}
}
/**
* Load the HTML bookmarks page in this view
*/
public void loadBookmarkpage() {
if (mWebView == null)
return;
Bitmap folderIcon = ThemeUtils.getThemedBitmap(mActivity, R.drawable.ic_folder, false);
FileOutputStream outputStream = null;
File image = new File(mActivity.getCacheDir(), "folder.png");
try {
outputStream = new FileOutputStream(image);
folderIcon.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
folderIcon.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
Utils.close(outputStream);
}
File bookmarkWebPage = new File(mActivity.getFilesDir(), BookmarkPage.FILENAME);
BrowserApp.getAppComponent().getBookmarkPage().buildBookmarkPage(null);
mWebView.loadUrl(Constants.FILE + bookmarkWebPage, mRequestHeaders);
}
/**
* Initialize the preference driven settings of the WebView
*
* @param settings the WebSettings object to use, you can pass in null
* if you don't have a reference to them
* @param context the context in which the WebView was created
*/
@SuppressLint({"NewApi", "SetJavaScriptEnabled"})
public synchronized void initializePreferences(@Nullable WebSettings settings, Context context) {
if (settings == null && mWebView == null) {
return;
} else if (settings == null) {
settings = mWebView.getSettings();
}
if (mPreferences.getDoNotTrackEnabled()) {
mRequestHeaders.put(HEADER_DNT, "1");
} else {
mRequestHeaders.remove(HEADER_DNT);
}
if (mPreferences.getRemoveIdentifyingHeadersEnabled()) {
mRequestHeaders.put(HEADER_REQUESTED_WITH, "");
mRequestHeaders.put(HEADER_WAP_PROFILE, "");
} else {
mRequestHeaders.remove(HEADER_REQUESTED_WITH);
mRequestHeaders.remove(HEADER_WAP_PROFILE);
}
settings.setDefaultTextEncodingName(mPreferences.getTextEncoding());
mHomepage = mPreferences.getHomepage();
setColorMode(mPreferences.getRenderingMode());
if (!mIsIncognitoTab) {
settings.setGeolocationEnabled(mPreferences.getLocationEnabled());
} else {
settings.setGeolocationEnabled(false);
}
if (API < Build.VERSION_CODES.KITKAT) {
switch (mPreferences.getFlashSupport()) {
case 0:
//noinspection deprecation
settings.setPluginState(PluginState.OFF);
break;
case 1:
//noinspection deprecation
settings.setPluginState(PluginState.ON_DEMAND);
break;
case 2:
//noinspection deprecation
settings.setPluginState(PluginState.ON);
break;
default:
break;
}
}
setUserAgent(context, mPreferences.getUserAgentChoice());
if (mPreferences.getSavePasswordsEnabled() && !mIsIncognitoTab) {
if (API < Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
settings.setSavePassword(true);
}
settings.setSaveFormData(true);
} else {
if (API < Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
settings.setSavePassword(false);
}
settings.setSaveFormData(false);
}
if (mPreferences.getJavaScriptEnabled()) {
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
} else {
settings.setJavaScriptEnabled(false);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
}
if (mPreferences.getTextReflowEnabled()) {
settings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
if (API >= android.os.Build.VERSION_CODES.KITKAT) {
try {
settings.setLayoutAlgorithm(LayoutAlgorithm.TEXT_AUTOSIZING);
} catch (Exception e) {
// This shouldn't be necessary, but there are a number
// of KitKat devices that crash trying to set this
Log.e(Constants.TAG, "Problem setting LayoutAlgorithm to TEXT_AUTOSIZING");
}
}
} else {
settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
}
settings.setBlockNetworkImage(mPreferences.getBlockImagesEnabled());
if (!mIsIncognitoTab) {
settings.setSupportMultipleWindows(mPreferences.getPopupsEnabled());
} else {
settings.setSupportMultipleWindows(false);
}
settings.setUseWideViewPort(mPreferences.getUseWideViewportEnabled());
settings.setLoadWithOverviewMode(mPreferences.getOverviewModeEnabled());
switch (mPreferences.getTextSize()) {
case 0:
settings.setTextZoom(200);
break;
case 1:
settings.setTextZoom(150);
break;
case 2:
settings.setTextZoom(125);
break;
case 3:
settings.setTextZoom(100);
break;
case 4:
settings.setTextZoom(75);
break;
case 5:
settings.setTextZoom(50);
break;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView,
!mPreferences.getBlockThirdPartyCookiesEnabled());
}
}
/**
* Initialize the settings of the WebView that are intrinsic to Lightning and cannot
* be altered by the user. Distinguish between Incognito and Regular tabs here.
*
* @param settings the WebSettings object to use.
* @param context the Context which was used to construct the WebView.
*/
@SuppressLint("NewApi")
private void initializeSettings(WebSettings settings, Context context) {
if (API < Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
settings.setAppCacheMaxSize(Long.MAX_VALUE);
}
if (API < Build.VERSION_CODES.JELLY_BEAN_MR1) {
//noinspection deprecation
settings.setEnableSmoothTransition(true);
}
if (API > Build.VERSION_CODES.JELLY_BEAN) {
settings.setMediaPlaybackRequiresUserGesture(true);
}
if (API >= Build.VERSION_CODES.LOLLIPOP && !mIsIncognitoTab) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
} else if (API >= Build.VERSION_CODES.LOLLIPOP) {
// We're in Incognito mode, reject
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
if (!mIsIncognitoTab) {
settings.setDomStorageEnabled(true);
settings.setAppCacheEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setDatabaseEnabled(true);
} else {
settings.setDomStorageEnabled(false);
settings.setAppCacheEnabled(false);
settings.setDatabaseEnabled(false);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
}
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setAllowContentAccess(true);
settings.setAllowFileAccess(true);
if (API >= Build.VERSION_CODES.JELLY_BEAN) {
settings.setAllowFileAccessFromFileURLs(false);
settings.setAllowUniversalAccessFromFileURLs(false);
}
settings.setAppCachePath(context.getDir("appcache", 0).getPath());
settings.setGeolocationDatabasePath(context.getDir("geolocation", 0).getPath());
if (API < Build.VERSION_CODES.KITKAT) {
//noinspection deprecation
settings.setDatabasePath(context.getDir("databases", 0).getPath());
}
}
public void toggleDesktopUA(@NonNull Context context) {
if (mWebView == null)
return;
if (!mToggleDesktop)
mWebView.getSettings().setUserAgentString(Constants.DESKTOP_USER_AGENT);
else
setUserAgent(context, mPreferences.getUserAgentChoice());
mToggleDesktop = !mToggleDesktop;
}
@SuppressLint("NewApi")
private void setUserAgent(Context context, int choice) {
if (mWebView == null) return;
WebSettings settings = mWebView.getSettings();
switch (choice) {
case 1:
if (API >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setUserAgentString(WebSettings.getDefaultUserAgent(context));
} else {
settings.setUserAgentString(mDefaultUserAgent);
}
break;
case 2:
settings.setUserAgentString(Constants.DESKTOP_USER_AGENT);
break;
case 3:
settings.setUserAgentString(Constants.MOBILE_USER_AGENT);
break;
case 4:
String ua = mPreferences.getUserAgentString(mDefaultUserAgent);
if (ua == null || ua.isEmpty()) {
ua = " ";
}
settings.setUserAgentString(ua);
break;
}
}
@NonNull
protected Map<String, String> getRequestHeaders() {
return mRequestHeaders;
}
public boolean isShown() {
return mWebView != null && mWebView.isShown();
}
public synchronized void onPause() {
if (mWebView != null)
mWebView.onPause();
}
public synchronized void onResume() {
if (mWebView != null)
mWebView.onResume();
}
public synchronized void freeMemory() {
if (mWebView != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
//noinspection deprecation
mWebView.freeMemory();
}
}
public void setForegroundTab(boolean isForeground) {
isForegroundTab = isForeground;
mEventBus.post(new BrowserEvents.TabsChanged());
}
public boolean isForegroundTab() {
return isForegroundTab;
}
public int getProgress() {
if (mWebView != null) {
return mWebView.getProgress();
} else {
return 100;
}
}
public synchronized void stopLoading() {
if (mWebView != null) {
mWebView.stopLoading();
}
}
private void setHardwareRendering() {
mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, mPaint);
}
private void setNormalRendering() {
mWebView.setLayerType(View.LAYER_TYPE_NONE, null);
}
public void setSoftwareRendering() {
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
private void setColorMode(int mode) {
mInvertPage = false;
switch (mode) {
case 0:
mPaint.setColorFilter(null);
// setSoftwareRendering(); // Some devices get segfaults
// in the WebView with Hardware Acceleration enabled,
// the only fix is to disable hardware rendering
setNormalRendering();
mInvertPage = false;
break;
case 1:
ColorMatrixColorFilter filterInvert = new ColorMatrixColorFilter(
mNegativeColorArray);
mPaint.setColorFilter(filterInvert);
setHardwareRendering();
mInvertPage = true;
break;
case 2:
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter filterGray = new ColorMatrixColorFilter(cm);
mPaint.setColorFilter(filterGray);
setHardwareRendering();
break;
case 3:
ColorMatrix matrix = new ColorMatrix();
matrix.set(mNegativeColorArray);
ColorMatrix matrixGray = new ColorMatrix();
matrixGray.setSaturation(0);
ColorMatrix concat = new ColorMatrix();
concat.setConcat(matrix, matrixGray);
ColorMatrixColorFilter filterInvertGray = new ColorMatrixColorFilter(concat);
mPaint.setColorFilter(filterInvertGray);
setHardwareRendering();
mInvertPage = true;
break;
}
}
public synchronized void pauseTimers() {
if (mWebView != null) {
mWebView.pauseTimers();
}
}
public synchronized void resumeTimers() {
if (mWebView != null) {
mWebView.resumeTimers();
}
}
public void requestFocus() {
if (mWebView != null && !mWebView.hasFocus()) {
mWebView.requestFocus();
}
}
public void setVisibility(int visible) {
if (mWebView != null) {
mWebView.setVisibility(visible);
}
}
public synchronized void reload() {
// Check if configured proxy is available
if (!ProxyUtils.getInstance().isProxyReady()) {
// User has been notified
return;
}
if (mWebView != null) {
mWebView.reload();
}
}
/**
* Naive caching of the favicon according to the domain name of the URL
*
* @param icon the icon to cache
*/
private void cacheFavicon(final Bitmap icon) {
if (icon == null) return;
final Uri uri = Uri.parse(getUrl());
if (uri.getHost() == null) {
return;
}
new Thread(new IconCacheTask(uri, icon)).start();
}
@SuppressLint("NewApi")
public synchronized void find(String text) {
if (mWebView != null) {
if (API >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mWebView.findAllAsync(text);
} else {
//noinspection deprecation
mWebView.findAll(text);
}
}
}
public synchronized void onDestroy() {
if (mWebView != null) {
mWebView.stopLoading();
mWebView.onPause();
mWebView.clearHistory();
mWebView.setVisibility(View.GONE);
mWebView.removeAllViews();
mWebView.destroyDrawingCache();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
//this is causing the segfault occasionally below 4.2
mWebView.destroy();
}
mWebView = null;
}
}
public synchronized void goBack() {
if (mWebView != null) {
mWebView.goBack();
}
}
private String getUserAgent() {
if (mWebView != null) {
return mWebView.getSettings().getUserAgentString();
} else {
return "";
}
}
public synchronized void goForward() {
if (mWebView != null) {
mWebView.goForward();
}
}
public synchronized void findNext() {
if (mWebView != null) {
mWebView.findNext(true);
}
}
public synchronized void findPrevious() {
if (mWebView != null) {
mWebView.findNext(false);
}
}
public synchronized void clearFindMatches() {
if (mWebView != null) {
mWebView.clearMatches();
}
}
/**
* Used by {@link LightningWebClient}
*
* @return true if the page is in inverted mode, false otherwise
*/
public boolean getInvertePage() {
return mInvertPage;
}
/**
* handles a long click on the page, parameter String url
* is the url that should have been obtained from the WebView touch node
* thingy, if it is null, this method tries to deal with it and find a workaround
*/
private void longClickPage(final String url) {
final WebView.HitTestResult result = mWebView.getHitTestResult();
String currentUrl = mWebView.getUrl();
if (currentUrl != null && UrlUtils.isSpecialUrl(currentUrl)) {
if (currentUrl.endsWith(HistoryPage.FILENAME)) {
if (url != null) {
mBookmarksDialogBuilder.showLongPressedHistoryLinkDialog(mActivity, url);
} else if (result != null && result.getExtra() != null) {
final String newUrl = result.getExtra();
mBookmarksDialogBuilder.showLongPressedHistoryLinkDialog(mActivity, newUrl);
}
} else if (currentUrl.endsWith(BookmarkPage.FILENAME)) {
if (url != null) {
mBookmarksDialogBuilder.showLongPressedDialogForBookmarkUrl(mActivity, url);
} else if (result != null && result.getExtra() != null) {
final String newUrl = result.getExtra();
mBookmarksDialogBuilder.showLongPressedDialogForBookmarkUrl(mActivity, newUrl);
}
}
} else {
if (url != null) {
if (result != null) {
if (result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE || result.getType() == WebView.HitTestResult.IMAGE_TYPE) {
mBookmarksDialogBuilder.showLongPressImageDialog(mActivity, url, getUserAgent());
} else {
mBookmarksDialogBuilder.showLongPressLinkDialog(mActivity, url);
}
} else {
mBookmarksDialogBuilder.showLongPressLinkDialog(mActivity, url);
}
} else if (result != null && result.getExtra() != null) {
final String newUrl = result.getExtra();
if (result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE || result.getType() == WebView.HitTestResult.IMAGE_TYPE) {
mBookmarksDialogBuilder.showLongPressImageDialog(mActivity, newUrl, getUserAgent());
} else {
mBookmarksDialogBuilder.showLongPressLinkDialog(mActivity, newUrl);
}
}
}
}
public boolean canGoBack() {
return mWebView != null && mWebView.canGoBack();
}
public boolean canGoForward() {
return mWebView != null && mWebView.canGoForward();
}
@Nullable
public synchronized WebView getWebView() {
return mWebView;
}
public Bitmap getFavicon() {
return mTitle.getFavicon();
}
public synchronized void loadUrl(String url) {
// Check if configured proxy is available
if (!ProxyUtils.getInstance().isProxyReady()) {
return;
}
if (mWebView != null) {
mWebView.loadUrl(url, mRequestHeaders);
}
}
public String getTitle() {
return mTitle.getTitle();
}
@NonNull
public String getUrl() {
if (mWebView != null && mWebView.getUrl() != null) {
return mWebView.getUrl();
} else {
return "";
}
}
private class TouchListener implements OnTouchListener {
float mLocation;
float mY;
int mAction;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View view, MotionEvent arg1) {
if (view == null)
return false;
if (!view.hasFocus()) {
view.requestFocus();
}
mAction = arg1.getAction();
mY = arg1.getY();
if (mAction == MotionEvent.ACTION_DOWN) {
mLocation = mY;
} else if (mAction == MotionEvent.ACTION_UP) {
final float distance = (mY - mLocation);
if (distance > SCROLL_UP_THRESHOLD && view.getScrollY() < SCROLL_UP_THRESHOLD) {
mUIController.showActionBar();
} else if (distance < -SCROLL_UP_THRESHOLD) {
mUIController.hideActionBar();
}
mLocation = 0;
}
mGestureDetector.onTouchEvent(arg1);
return false;
}
}
private class CustomGestureListener extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
int power = (int) (velocityY * 100 / mMaxFling);
if (power < -10) {
mUIController.hideActionBar();
} else if (power > 15) {
mUIController.showActionBar();
}
return super.onFling(e1, e2, velocityX, velocityY);
}
/**
* Without this, onLongPress is not called when user is zooming using
* two fingers, but is when using only one.
* <p/>
* The required behaviour is to not trigger this when the user is
* zooming, it shouldn't matter how much fingers the user's using.
*/
private boolean mCanTriggerLongPress = true;
@Override
public void onLongPress(MotionEvent e) {
if (mCanTriggerLongPress) {
Message msg = mWebViewHandler.obtainMessage();
if (msg != null) {
msg.setTarget(mWebViewHandler);
mWebView.requestFocusNodeHref(msg);
}
}
}
/**
* Is called when the user is swiping after the doubletap, which in our
* case means that he is zooming.
*/
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
mCanTriggerLongPress = false;
return false;
}
/**
* Is called when something is starting being pressed, always before
* onLongPress.
*/
@Override
public void onShowPress(MotionEvent e) {
mCanTriggerLongPress = true;
}
}
private static class WebViewHandler extends Handler {
private final WeakReference<LightningView> mReference;
public WebViewHandler(LightningView view) {
mReference = new WeakReference<>(view);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
final String url = msg.getData().getString("url");
LightningView view = mReference.get();
if (view != null) {
view.longClickPage(url);
}
}
}
}
|
package com.apps.adrcotfas.goodtime;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adrcotfas.goodtime.about.AboutActivity;
import com.apps.adrcotfas.goodtime.settings.CustomNotification;
import com.apps.adrcotfas.goodtime.settings.SettingsActivity;
import java.util.Locale;
import static android.graphics.Typeface.createFromAsset;
import static android.os.PowerManager.ACQUIRE_CAUSES_WAKEUP;
import static android.os.PowerManager.FULL_WAKE_LOCK;
import static android.os.PowerManager.ON_AFTER_RELEASE;
import static android.os.PowerManager.SCREEN_BRIGHT_WAKE_LOCK;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
import static android.view.animation.AnimationUtils.loadAnimation;
import static android.widget.Toast.LENGTH_SHORT;
import static com.apps.adrcotfas.goodtime.Preferences.FIRST_RUN;
import static com.apps.adrcotfas.goodtime.Preferences.PREFERENCES_NAME;
import static com.apps.adrcotfas.goodtime.Preferences.SESSION_DURATION;
import static com.apps.adrcotfas.goodtime.Preferences.TOTAL_SESSION_COUNT;
import static com.apps.adrcotfas.goodtime.SessionType.BREAK;
import static com.apps.adrcotfas.goodtime.SessionType.LONG_BREAK;
import static com.apps.adrcotfas.goodtime.SessionType.WORK;
import static com.apps.adrcotfas.goodtime.TimerState.INACTIVE;
import static java.lang.String.format;
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final int MAXIMUM_MILLISECONDS_BETWEEN_BACK_PRESSES = 2000;
private static final String TAG = "MainActivity";
public static final int NOTIFICATION_TAG = 2;
private long mBackPressedAt;
private FloatingActionButton mStartButton;
private Button mPauseButton;
private Button mStopButton;
private TextView mTimeLabel;
private View mHorizontalSeparator;
private Preferences mPref;
private SharedPreferences mPrivatePref;
private AlertDialog mAlertDialog;
private OrientationListener mOrientationListener;
private TimerService mTimerService;
private BroadcastReceiver mBroadcastReceiver;
private boolean mIsBoundToTimerService = false;
private ServiceConnection mTimerServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
TimerService.TimerBinder binder = (TimerService.TimerBinder) iBinder;
mTimerService = binder.getService();
mIsBoundToTimerService = true;
mTimerService.sendToBackground();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mIsBoundToTimerService = false;
}
};
private class OrientationListener extends OrientationEventListener{
final int ROTATION_O = 1;
final int ROTATION_90 = 2;
final int ROTATION_MINUS90 = 3;
private int rotation = ROTATION_O;
public OrientationListener(Context context) { super(context); }
@Override public void onOrientationChanged(int orientation) {
if( (orientation < 35 || orientation > 325)){
if (rotation == ROTATION_90) {
mTimeLabel.startAnimation(loadAnimation(getApplicationContext(), R.anim.landscape_to_portrait));
}
else if (rotation == ROTATION_MINUS90) {
mTimeLabel.startAnimation(loadAnimation(getApplicationContext(), R.anim.revlandscape_to_portrait));
}
rotation = ROTATION_O;
}
else if(orientation > 55 && orientation < 125 && rotation != ROTATION_MINUS90){
rotation = ROTATION_MINUS90;
mTimeLabel.startAnimation(loadAnimation(getApplicationContext(), R.anim.portrait_to_revlandscape));
}
else if(orientation > 235 && orientation < 305 && rotation != ROTATION_90){
rotation = ROTATION_90;
mTimeLabel.startAnimation(loadAnimation(getApplicationContext(), R.anim.portrait_to_landscape));
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPref = setUpPreferences();
installCustomRingtones();
setUpUi();
loadInitialState();
setUpAndroidNougatSettings();
setupBroadcastReceiver();
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, TimerService.class);
startService(intent);
bindService(intent, mTimerServiceConnection, Context.BIND_AUTO_CREATE);
if (mPref.getRotateTimeLabel()) {
mOrientationListener.enable();
}
}
@Override
protected void onResume() {
super.onResume();
if (mIsBoundToTimerService) {
mTimerService.sendToBackground();
}
removeCompletionNotification();
if (mPrivatePref.getBoolean(FIRST_RUN, true)) {
Intent introIntent = new Intent(this, ProductTourActivity.class);
startActivity(introIntent);
mPrivatePref.edit().putBoolean(FIRST_RUN, false).apply();
}
}
@Override
protected void onStop() {
if (mIsBoundToTimerService && mTimerService.getTimerState() != INACTIVE) {
mTimerService.bringToForegroundAndUpdateNotification();
}
if (mPref.getRotateTimeLabel()) {
mOrientationListener.disable();
}
super.onStop();
}
@Override
protected void onDestroy() {
if (mIsBoundToTimerService) {
mTimerService.removeTimer();
stopService(new Intent(this, TimerService.class));
unbindService(mTimerServiceConnection);
mIsBoundToTimerService = false;
}
if (mAlertDialog != null) {
mAlertDialog.dismiss();
}
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
private void setupBroadcastReceiver(){
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (mIsBoundToTimerService) {
int remainingTime = intent.getIntExtra(TimerService.REMAINING_TIME, 0);
Log.d(TAG, "Updating timer, " + remainingTime + " remaining");
updateTimerLabel(remainingTime);
if (remainingTime == 0) {
onCountdownFinished();
}
}
}
};
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver((mBroadcastReceiver),
new IntentFilter(TimerService.ACTION_TIMERSERVICE)
);
}
private Preferences setUpPreferences() {
SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
preferences.registerOnSharedPreferenceChangeListener(this);
mPrivatePref = getSharedPreferences("preferences_private", Context.MODE_PRIVATE);
mPrivatePref.registerOnSharedPreferenceChangeListener(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
return new Preferences(preferences);
}
private void setUpAndroidNougatSettings() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
if (!notificationManager.isNotificationPolicyAccessGranted()) {
mPref.setDisableSoundAndVibration(false);
}
}
}
private void installCustomRingtones() {
if (!mPref.getRingtonesCopied()) {
CustomNotification.installToStorage(this);
}
}
private void setUpUi() {
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setUpToolbar(toolbar);
setUpSessionCounter();
mStartButton = (FloatingActionButton) findViewById(R.id.startButton);
setUpStartButton();
mPauseButton = (Button) findViewById(R.id.pauseButton);
setUpPauseButton();
mStopButton = (Button) findViewById(R.id.stopButton);
setUpStopButton();
mHorizontalSeparator = findViewById(R.id.horizontalSeparator);
mTimeLabel = (TextView) findViewById(R.id.textView);
setUpTimerLabel();
mOrientationListener = new OrientationListener(this);
}
private void setUpToolbar(Toolbar toolbar) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
private void setUpSessionCounter() {
Button sessionCounterButton = (Button) findViewById(R.id.totalSessionsButton);
if (sessionCounterButton != null) {
sessionCounterButton.setText(String.valueOf(mPrivatePref.getInt(TOTAL_SESSION_COUNT, 0)));
sessionCounterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showSessionCounterDialog();
}
});
}
}
private void setUpStartButton() {
final RelativeLayout buttons = (RelativeLayout) findViewById(R.id.buttons);
mStartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mStartButton.startAnimation(loadAnimation(getApplicationContext(), R.anim.implode));
if (buttons != null) {
buttons.startAnimation(loadAnimation(getApplicationContext(), R.anim.fade));
}
startTimer(300, WORK);
enablePauseButton();
mStartButton.setEnabled(false);
mStartButton.postDelayed(new Runnable() {
@Override
public void run() {
mStartButton.setEnabled(true);
}
}, 300);
}
});
}
private void setUpPauseButton() {
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pauseTimer();
}
});
}
private void setUpStopButton() {
final RelativeLayout buttons = (RelativeLayout) findViewById(R.id.buttons);
mStopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPauseButton.clearAnimation();
if (buttons != null) {
buttons.startAnimation(loadAnimation(getApplicationContext(), R.anim.fade_reverse));
}
mStartButton.startAnimation(loadAnimation(getApplicationContext(), R.anim.implode_reverse));
loadInitialState();
}
});
}
private void setUpTimerLabel() {
if (mTimeLabel != null) {
mTimeLabel.setTypeface(createFromAsset(getAssets(), "fonts/Roboto-Thin.ttf"));
updateTimerLabel(mPref.getSessionDuration() * 60);
}
}
private void removeCompletionNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_TAG);
}
private void disablePauseButton() {
mPauseButton.setEnabled(false);
mPauseButton.setTextColor(getResources().getColor(R.color.gray));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
if (id == R.id.action_about) {
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(TAG, "A preference has changed");
if (key.equals(TOTAL_SESSION_COUNT)) {
Button button = (Button) findViewById(R.id.totalSessionsButton);
if (button != null) {
button.setText(String.valueOf(mPrivatePref.getInt(TOTAL_SESSION_COUNT, 0)));
}
} else if (key.equals(SESSION_DURATION)) {
if (mTimerService.getTimerState() == INACTIVE) {
updateTimerLabel(mPref.getSessionDuration() * 60);
}
}
}
@Override
public void onBackPressed() {
if (mTimerService.getTimerState() != INACTIVE) {
/// move app to background
moveTaskToBack(true);
} else {
if (mBackPressedAt + MAXIMUM_MILLISECONDS_BETWEEN_BACK_PRESSES > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
try {
Toast.makeText(getBaseContext(), R.string.toast_back_press, LENGTH_SHORT)
.show();
} catch (Throwable th) {
// ignoring this exception
}
}
mBackPressedAt = System.currentTimeMillis();
}
}
private void loadInitialState() {
Log.d(TAG, "Loading initial state");
if (mIsBoundToTimerService) {
updateTimerLabel(mPref.getSessionDuration() * 60);
mTimerService.removeTimer();
shutScreenOffIfPreferred();
}
mTimeLabel.setTextColor(getResources().getColor(R.color.lightGray));
mStartButton.setVisibility(VISIBLE);
mPauseButton.setVisibility(INVISIBLE);
mPauseButton.setText(getString(R.string.pause));
mStopButton.setVisibility(INVISIBLE);
mHorizontalSeparator.setVisibility(INVISIBLE);
}
private void shutScreenOffIfPreferred() {
if (mPref.getKeepScreenOn()) {
getWindow().clearFlags(FLAG_KEEP_SCREEN_ON);
}
}
private void startTimer(
long delay,
SessionType sessionType
) {
Log.i(TAG, "Timer has been started");
mTimeLabel.setTextColor(Color.WHITE);
loadRunningTimerUiState();
keepScreenOnIfPreferred();
mTimerService.scheduleTimer(delay, sessionType);
}
private void loadRunningTimerUiState() {
updateTimerLabel(mTimerService.getRemainingTime());
mStartButton.setVisibility(INVISIBLE);
mPauseButton.setVisibility(VISIBLE);
mStopButton.setVisibility(VISIBLE);
mHorizontalSeparator.setVisibility(VISIBLE);
}
private void keepScreenOnIfPreferred() {
if (mPref.getKeepScreenOn()) {
getWindow().addFlags(FLAG_KEEP_SCREEN_ON);
}
}
private void pauseTimer() {
Log.i(TAG, "Timer has been paused");
mTimeLabel.setTextColor(getResources().getColor(R.color.lightGray));
long timeOfButtonPress = System.currentTimeMillis();
switch (mTimerService.getTimerState()) {
case ACTIVE:
mTimerService.pauseTimer();
mPauseButton.setText(getString(R.string.resume));
mPauseButton.startAnimation(loadAnimation(getApplicationContext(), R.anim.blink));
break;
case PAUSED:
mTimerService.unpauseTimer(
System.currentTimeMillis() - timeOfButtonPress > 1000
? 0
: 1000 - (System.currentTimeMillis() - timeOfButtonPress)
);
mPauseButton.setText(getString(R.string.pause));
mPauseButton.clearAnimation();
break;
}
}
private void onCountdownFinished() {
Log.i(TAG, "Countdown has finished");
acquireScreenWakelock();
shutScreenOffIfPreferred();
increaseTotalSessions();
if (mPref.getContinuousMode()) {
goOnContinuousMode();
} else {
showContinueDialog();
}
}
private void increaseTotalSessions() {
if (mTimerService.getTimerState() == INACTIVE && mTimerService.getSessionType() == WORK) {
mTimerService.increaseCurrentSessionStreak();
int totalSessions = mPrivatePref.getInt(TOTAL_SESSION_COUNT, 0);
mPrivatePref.edit()
.putInt(TOTAL_SESSION_COUNT, ++totalSessions)
.apply();
}
}
private void acquireScreenWakelock() {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock screenWakeLock = powerManager.newWakeLock(
SCREEN_BRIGHT_WAKE_LOCK | ON_AFTER_RELEASE | ACQUIRE_CAUSES_WAKEUP,
"wake screen lock"
);
screenWakeLock.acquire();
screenWakeLock.release();
}
private void showContinueDialog() {
wakeScreen();
switch (mTimerService.getSessionType()) {
case WORK:
loadInitialState();
mAlertDialog = buildStartBreakDialog();
mAlertDialog.setCanceledOnTouchOutside(false);
mAlertDialog.show();
break;
case BREAK:
case LONG_BREAK:
loadInitialState();
enablePauseButton();
if (mTimerService.getCurrentSessionStreak() >= mPref.getSessionsBeforeLongBreak()) {
mTimerService.resetCurrentSessionStreak();
}
mAlertDialog = buildStartSessionDialog();
mAlertDialog.setCanceledOnTouchOutside(false);
mAlertDialog.show();
}
}
private AlertDialog buildStartSessionDialog() {
return new AlertDialog.Builder(this)
.setTitle(getString(R.string.dialog_break_message))
.setPositiveButton(getString(R.string.dialog_break_session), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startTimer(0, WORK);
}
})
.setNegativeButton(getString(R.string.dialog_session_cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mTimerService.sendToBackground();
}
})
.create();
}
private AlertDialog buildStartBreakDialog() {
return new AlertDialog.Builder(this)
.setTitle(getString(R.string.dialog_session_message))
.setPositiveButton(
getString(R.string.dialog_session_break),
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which
) {
startBreak();
}
}
)
.setNegativeButton(
getString(R.string.dialog_session_skip),
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which
) {
startTimer(0, WORK);
}
}
)
.setNeutralButton(getString(R.string.dialog_session_close), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mTimerService.sendToBackground();
}
})
.create();
}
private void startBreak() {
disablePauseButton();
startTimer(
0,
mTimerService.getCurrentSessionStreak() >= mPref.getSessionsBeforeLongBreak()
? LONG_BREAK
: BREAK
);
}
private void wakeScreen() {
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(
SCREEN_BRIGHT_WAKE_LOCK | FULL_WAKE_LOCK,
"waking screen up"
);
wakeLock.acquire();
wakeLock.release();
}
private void goOnContinuousMode() {
switch (mTimerService.getSessionType()) {
case WORK:
loadInitialState();
startBreak();
break;
case BREAK:
case LONG_BREAK:
loadInitialState();
enablePauseButton();
if (mTimerService.getCurrentSessionStreak() >= mPref.getSessionsBeforeLongBreak()) {
mTimerService.resetCurrentSessionStreak();
}
startTimer(0, WORK);
}
}
private void enablePauseButton() {
mPauseButton.setEnabled(true);
mPauseButton.setTextColor(getResources().getColor(R.color.yellow));
}
private void updateTimerLabel(
final int remainingTime
) {
int minutes = remainingTime / 60;
int seconds = remainingTime % 60;
String currentTick = (minutes > 0 ? minutes : "") +
"." +
format(Locale.US, "%02d", seconds);
SpannableString currentFormattedTick = new SpannableString(currentTick);
currentFormattedTick.setSpan(new RelativeSizeSpan(2f), 0, currentTick.indexOf("."), 0);
mTimeLabel.setText(currentFormattedTick);
}
private void showSessionCounterDialog() {
mAlertDialog = new AlertDialog.Builder(this)
.setTitle(getString(R.string.dialog_reset_title))
.setMessage(getString(R.string.dialog_reset_message))
.setPositiveButton(getString(R.string.dialog_reset_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mTimerService.resetCurrentSessionStreak();
mPrivatePref.edit()
.putInt(TOTAL_SESSION_COUNT, 0)
.apply();
}
})
.setNegativeButton(getString(R.string.dialog_reset_cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
mAlertDialog.show();
}
}
|
package com.gmail.alexellingsen.g2skintweaks;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import android.graphics.Color;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XposedHelpers.ClassNotFoundError;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class G2SkinTweaks implements IXposedHookZygoteInit, IXposedHookLoadPackage, IXposedHookInitPackageResources {
private static String MODULE_PATH = null;
private static boolean ENABLE_REPLACE_SWITCH = false;
private static boolean ENABLE_SQUARE_BUBBLE = false;
private static int SQUARE_COLOR_LEFT = Color.WHITE;
private static int SQUARE_COLOR_RIGHT = Color.WHITE;
private static SettingsHelper settings;
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
MODULE_PATH = startupParam.modulePath;
settings = new SettingsHelper();
ENABLE_REPLACE_SWITCH = settings.getBoolean(Prefs.ENABLE_REPLACE_SWICTH, ENABLE_REPLACE_SWITCH);
ENABLE_SQUARE_BUBBLE = settings.getBoolean(Prefs.ENABLE_SQUARE_BUBBLE, ENABLE_SQUARE_BUBBLE);
SQUARE_COLOR_LEFT = settings.getInt(Prefs.SQUARE_COLOR_LEFT, Color.WHITE);
SQUARE_COLOR_RIGHT = settings.getInt(Prefs.SQUARE_COLOR_RIGHT, Color.WHITE);
if (ENABLE_REPLACE_SWITCH) {
XModuleResources modRes = XModuleResources.createInstance(MODULE_PATH, null);
XResources.setSystemWideReplacement("com.lge.internal", "drawable", "switch_track_holo_dark", modRes.fwd(R.drawable.replacement_switch));
XResources.setSystemWideReplacement("com.lge.internal", "drawable", "switch_track_holo_light", modRes.fwd(R.drawable.replacement_switch));
}
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
if (ENABLE_SQUARE_BUBBLE) {
String packageName = "com.android.mms";
if (!resparam.packageName.equals(packageName))
return;
final XModuleResources modRes = XModuleResources.createInstance(MODULE_PATH, resparam.res);
resparam.res.setReplacement(packageName, "drawable", "message_set_bubble_04", modRes.fwd(R.drawable.message_set_bubble_04));
resparam.res.setReplacement(packageName, "drawable", "bubble_inbox_bg_04", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
Drawable mDrawable = modRes.getDrawable(R.drawable.balloon_bg_04_left_normal);
mDrawable.setColorFilter(new PorterDuffColorFilter(SQUARE_COLOR_LEFT, android.graphics.PorterDuff.Mode.MULTIPLY));
return mDrawable;
}
});
resparam.res.setReplacement(packageName, "drawable", "bubble_outbox_bg_04", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
Drawable mDrawable = modRes.getDrawable(R.drawable.balloon_bg_04_right_normal);
mDrawable.setColorFilter(new PorterDuffColorFilter(SQUARE_COLOR_RIGHT, android.graphics.PorterDuff.Mode.MULTIPLY));
return mDrawable;
}
});
resparam.res.setReplacement(packageName, "drawable", "bubble_reserved_bg_04", new XResources.DrawableLoader() {
@Override
public Drawable newDrawable(XResources res, int id) throws Throwable {
Drawable mDrawable = modRes.getDrawable(R.drawable.balloon_bg_04_right_normal);
mDrawable.setColorFilter(new PorterDuffColorFilter(SQUARE_COLOR_RIGHT, android.graphics.PorterDuff.Mode.MULTIPLY));
return mDrawable;
}
});
}
}
@Override
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals("com.android.mms")) {
hookMessageListItem(lpparam);
hookMessagingNotification(lpparam);
}
}
private void hookMessagingNotification(final LoadPackageParam lpparam) {
final Class<?> finalClass;
try {
Class<?> findClass = XposedHelpers.findClass(
"com.android.mms.transaction.MessagingNotification",
lpparam.classLoader);
finalClass = findClass;
} catch (ClassNotFoundError e) {
XposedBridge.log(e);
return;
}
XposedHelpers.findAndHookMethod(
finalClass,
"turnOnBacklight",
"android.content.Context",
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
boolean turnOnScreenNewSms = settings.getBoolean(Prefs.TURN_ON_SCREEN_NEW_SMS, true);
if (!turnOnScreenNewSms) {
param.setResult(null);
// To-Do: Make SuperSU detect the call from my app,
// not the Messaging app
RootFunctions.flashRearPowerLed(1000);
}
}
});
}
private void hookMessageListItem(final LoadPackageParam lpparam) {
final Class<?> finalClass;
try {
Class<?> findClass = XposedHelpers.findClass("com.android.mms.ui.MessageListItem", lpparam.classLoader);
finalClass = findClass;
} catch (ClassNotFoundError e) {
XposedBridge.log(e);
return;
}
// mBodyTextView seems to be initialized after 'bind' method
XposedHelpers.findAndHookMethod(
finalClass,
"bind",
"com.android.mms.ui.MessageListAdapter$AvatarCache",
"com.android.mms.ui.MessageItem",
"android.widget.ListView",
"int",
"boolean",
"boolean",
new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
try {
TextView tvBody = (TextView) XposedHelpers.getObjectField(param.thisObject, "mBodyTextView");
TextView tvDate = (TextView) XposedHelpers.getObjectField(param.thisObject, "mSmallTextView");
boolean enableSmsFontSize = settings.getBoolean(Prefs.ENABLE_SMS_TEXT_COLOR, false);
boolean enableSmsTextColor = settings.getBoolean(Prefs.ENABLE_SMS_TEXT_COLOR, false);
if (enableSmsFontSize) {
int body = settings.getInt(Prefs.SMS_BODY_SIZE, 18);
int date = settings.getInt(Prefs.SMS_DATE_SIZE, 18);
tvBody.setTextSize(body);
tvDate.setTextSize(date);
}
if (enableSmsTextColor) {
int color = settings.getInt(Prefs.SMS_TEXT_COLOR, Color.BLACK);
tvBody.setTextColor(color);
tvDate.setTextColor(color);
}
} catch (NoSuchFieldError e) {
XposedBridge.log("'mBodyTextView' not found.");
} catch (IllegalArgumentException e) {
XposedBridge.log("Can't get value of 'mBodyTextView'.");
} catch (Exception e) {
XposedBridge.log(e);
}
}
});
}
}
|
package smoothy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
public @interface BindExtra {
//boolean optional() default false; // not implemented
//String defaultValue() default ""; // not implemented
}
|
package com.bedrock.padder.adapter;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bedrock.padder.R;
import com.bedrock.padder.helper.WindowHelper;
import com.bedrock.padder.model.about.About;
public class DetailAdapter extends RecyclerView.Adapter<DetailAdapter.DetailViewHolder> {
private About about;
private int rowLayout;
private Context context;
private Activity activity;
WindowHelper window = new WindowHelper();
public static class DetailViewHolder extends RecyclerView.ViewHolder {
TextView detailTitle;
RecyclerView itemRecycleView;
public DetailViewHolder(View view) {
super(view);
detailTitle = (TextView) view.findViewById(R.id.layout_detail_title);
itemRecycleView = (RecyclerView) view.findViewById(R.id.layout_item_recycler_view);
}
}
public DetailAdapter(About about, int rowLayout, Context context, Activity activity) {
this.about = about;
this.rowLayout = rowLayout;
this.context = context;
this.activity = activity;
}
@Override
public DetailViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new DetailViewHolder(view);
}
@Override
public void onBindViewHolder(final DetailViewHolder holder, int position) {
holder.detailTitle.setText(about.getDetail(position).getTitle());
holder.detailTitle.setTextColor(about.getColor());
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
holder.itemRecycleView.setLayoutManager(layoutManager);
holder.itemRecycleView.setAdapter(new ItemAdapter(about.getDetail(position).getItems(), R.layout.adapter_item, context, activity));
}
@Override
public int getItemCount() {
return about.getDetails().length;
}
}
|
package com.florafinder.invasive_species;
class Species {
int name;
int scienceName;
int description;
int photoId;
Species(int name, int scienceName, int description, int photoId) {
this.name = name;
this.scienceName = scienceName;
this.description = description;
this.photoId = photoId;
}
}
|
package com.haxademic.demo.render.joons;
import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.constants.AppSettings;
import com.haxademic.core.draw.context.DrawUtil;
import com.haxademic.core.draw.shapes.PShapeUtil;
import com.haxademic.core.file.FileUtil;
import com.haxademic.core.render.JoonsWrapper;
import processing.core.PShape;
public class JoonsPShapeRender
extends PAppletHax {
public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }
protected PShape obj;
protected float objHeight;
protected float frames = 200;
protected void overridePropsFile() {
p.appConfig.setProperty( AppSettings.SUNFLOW, true );
p.appConfig.setProperty( AppSettings.SUNFLOW_ACTIVE, true );
p.appConfig.setProperty( AppSettings.SUNFLOW_QUALITY, AppSettings.SUNFLOW_QUALITY_HIGH );
p.appConfig.setProperty( AppSettings.WIDTH, 960 );
p.appConfig.setProperty( AppSettings.HEIGHT, 720 );
p.appConfig.setProperty( AppSettings.RENDERING_IMAGE_SEQUENCE, true );
p.appConfig.setProperty( AppSettings.RENDERING_IMAGE_SEQUENCE_START_FRAME, 3 );
p.appConfig.setProperty( AppSettings.RENDERING_IMAGE_SEQUENCE_STOP_FRAME, 3 + (int) frames );
}
public void setup() {
super.setup();
// load & normalize shape
obj = p.loadShape( FileUtil.getFile("models/skull-realistic.obj"));
obj = p.loadShape( FileUtil.getFile("models/poly-hole-penta.obj"));
PShapeUtil.centerSvg(obj);
PShapeUtil.scaleObjToExtentVerticesAdjust(obj, p.height * 0.4f);
objHeight = PShapeUtil.getObjHeight(obj);
}
public void drawApp() {
if(p.appConfig.getBoolean(AppSettings.SUNFLOW_ACTIVE, false) == false) {
p.background(0);
p.lights();
p.noStroke();
}
// joons.jr.background(JoonsWrapper.BACKGROUND_GI);
joons.jr.background(JoonsWrapper.BACKGROUND_AO);
p.translate(0, 0, -width);
// progress
float progress = (p.frameCount % frames) / frames;
// draw environment
p.pushMatrix();
setUpRoom();
p.popMatrix();
// draw shape
p.pushMatrix();
p.rotateZ(P.PI);
p.rotateY(progress * P.TWO_PI);
joons.jr.fill(JoonsWrapper.MATERIAL_PHONG, 205, 150, 205); p.fill( 205, 150, 205 );
PShapeUtil.drawTrianglesJoons(p, obj, 1);
p.popMatrix();
// draw sphere
p.pushMatrix();
// joons.jr.fill(JoonsWrapper.MATERIAL_LIGHT, 5, 5, 5); p.fill( 255, 255, 255 );
joons.jr.fill(JoonsWrapper.MATERIAL_AMBIENT_OCCLUSION, 10, 10, 30 + 20f * P.sin(progress * P.TWO_PI), 0, 0, 0, 50, 16);
p.rotateY(1);
p.rotateZ(1);
p.sphere(210);
p.popMatrix();
// draw floor
p.pushMatrix();
DrawUtil.setDrawCenter(p);
p.translate(0, objHeight/2);
joons.jr.fill(JoonsWrapper.MATERIAL_PHONG, 30, 10, 10); p.fill( 30, 10, 10 );
p.box(p.height * 4, 2, p.height * 4);
p.popMatrix();
}
protected void setUpRoom() {
pushMatrix();
translate(0, 0, 0);
float radiance = 10;
int samples = 16;
joons.jr.background(JoonsWrapper.CORNELL_BOX,
4000, 3000, 5000, // width, height, depth
radiance, radiance, radiance, samples, // radiance rgb & samples
40, 40, 40, // left rgb
40, 40, 40, // right rgb
0, 0, 0, // back rgb
60, 60, 60, // top rgb
60, 60, 60 // bottom rgb
);
popMatrix();
}
}
|
package com.gabmus.co2photoeditor;
import android.app.AlertDialog;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.security.Timestamp;
import java.sql.Time;
import java.util.Random;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.EGLConfig;
public class FilterRenderer implements GLSurfaceView.Renderer
{
private int hShaderProgramBase;
private int hShaderProgramFinalPass;
private int hShaderProgramBlackAndWhite;
private int hShaderProgramSepia;
private int hShaderProgramToneMapping;
private int hShaderProgramCathodeRayTube;
private int hShaderProgramFilmGrain;
private int hShaderProgramNegative;
public boolean PARAMS_EnableBlackAndWhite = false;
public boolean PARAMS_EnableSepia = false;
public boolean PARAMS_EnableToneMapping = false;
public float PARAMS_ToneMappingExposure = 2.0f;
public float PARAMS_ToneMappingVignetting = 1.0f;
public boolean PARAMS_EnableCathodeRayTube = false;
public int PARAMS_CathodeRayTubeLineWidth = 1;
public boolean PARAMS_CathodeRayTubeIsHorizontal = false;
public boolean PARAMS_EnableFilmGrain = false;
public float PARAMS_FilmGrainAmount = 0.35f;
public float PARAMS_FilmGrainParticleSize = 2.6f;
public float PARAMS_FilmGrainLuminance = 1f;
public float PARAMS_FilmGrainColorAmount = 0.0f;
public float PARAMS_FilmGrainSeed = 0.0f;
public boolean BOOL_LoadTexture = false;
public RenderTarget2D target1, target2;
private FilterSurfaceView fsv;
public int ImageWidth = 0;
public int ImageHeigth = 0;
private FloatBuffer VB;
private ShortBuffer IB;
private FloatBuffer TC;
public int[] hToFilterTexture;
public FilterRenderer(FilterSurfaceView fsv_) { fsv = fsv_;}
public void onSurfaceCreated(GL10 unused, EGLConfig config)
{
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
float[] vertices = new float[]
{
-1f, 1f, 0.0f,
-1f, -1f, 0.0f,
1f, -1f, 0.0f,
1f, 1f, 0.0f,
-1f, 1f, 0.0f,
1f, -1f, 0.0f
};
short[] indices = new short[]
{
0, 1, 2, 0, 2, 3
};
float[] texCoords =
{
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
1.0f, 1.0f
};
ByteBuffer bVB = ByteBuffer.allocateDirect(vertices.length * 4); bVB.order(ByteOrder.nativeOrder());
ByteBuffer bIB = ByteBuffer.allocateDirect(indices.length * 2); bIB.order(ByteOrder.nativeOrder());
ByteBuffer bTC = ByteBuffer.allocateDirect(texCoords.length * 4); bTC.order(ByteOrder.nativeOrder());
VB = bVB.asFloatBuffer();
IB = bIB.asShortBuffer();
TC = bTC.asFloatBuffer();
VB.put(vertices); VB.position(0);
IB.put(indices); IB.position(0);
TC.put(texCoords); TC.position(0);
loadShaders();
fsv.LoadBitmap(fsv.generateTestBitmap());
}
private String generalVS =
"attribute vec4 vPosition;" +
"attribute vec2 texCoords;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" gl_Position = vPosition;" +
" UV = texCoords;" +
"}";
private String generalreverseVS =
"attribute vec4 vPosition;" +
"attribute vec2 texCoords;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" gl_Position = vPosition;" +
" vec2 tc = vec2(1, 1) - texCoords;" +
" tc.x = texCoords.x;" +
" UV = tc;" +
"}";
private void loadShaders()
{
//BASE SHADER
String baseshader_FS =
"precision mediump float;" +
"varying vec2 UV;" +
"void main() {" +
" gl_FragColor = vec4(UV.x, UV.y, 0, 1);" +
"}";
hShaderProgramBase = createprogram(baseshader_FS);
//CRT
String crt_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"uniform int horizontal;\n" +
"uniform int linewidth;\n" +
"uniform float pixheigth;\n" +
"uniform float pixwidth;\n" +
"varying vec2 UV;" +
"" +
"" +
"void main() {\n" +
"vec4 c;\n" +
" float fv;\n" +
" float val;\n" +
" c = texture2D( filteredPhoto, UV);\n" +
" if ( (UV.x > 0.000000) ){\n" +
" fv = (UV.x / pixwidth);\n" +
" if ( horizontal == 1 ){\n" +
" fv = (UV.y / pixheigth);\n" +
" }\n" +
" val = mod(float(fv), float(3 * linewidth));\n" +
"val = val -0.008f;" +
" if ( ((val >= 0.0) && (val < float(linewidth))) ){\n" +
" c = vec4( c.x , 0.000000, 0.000000, 1.00000);\n" +
" }\n" +
" else{\n" +
" if ( ((val >= float(linewidth)) && (val < float(linewidth * 2))) ){\n" +
" c = vec4( 0.000000, c.y , 0.000000, 1.00000);\n" +
" }\n" +
" else{\n" +
" c = vec4(0.000000, 0.000000, c.z , 1.00000);\n" +
" }\n" +
" }\n" +
" }\n" +
" gl_FragColor = c;\n" +
"}";
hShaderProgramCathodeRayTube = createprogram(generalreverseVS, crt_FS);
//NEGATIVE
String neg_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" vec4 col = texture2D(filteredPhoto, UV);" +
" gl_FragColor = vec4(1.0 - col.r, 1.0 - col.g, 1.0 - col.b, 1);" +
"}";
hShaderProgramNegative = createprogram(generalreverseVS, neg_FS);
//Black & White
String bandw_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" vec4 col = texture2D(filteredPhoto, UV);" +
" float gravg = (col.r + col.g + col.b) / 3.0f;" +
" gl_FragColor = vec4(gravg, gravg, gravg, 1);" +
"}";
hShaderProgramBlackAndWhite = createprogram(generalreverseVS, bandw_FS);
//Sepia
String sepia_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" vec4 color = texture2D(filteredPhoto, UV);" +
" gl_FragColor = vec4(1, 1, 1, 1);" +
" gl_FragColor.r = color.r * 0.393f + color.g * 0.769f + color.b * 0.189f;" +
" gl_FragColor.g = color.r * 0.349f + color.g * 0.686f + color.b * 0.168f;" +
" gl_FragColor.b = color.r * 0.272f + color.g * 0.534f + color.b * 0.131f;" +
"}";
hShaderProgramSepia = createprogram(generalreverseVS, sepia_FS);
//ToneMapping+
String tonemapping_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"uniform float exposure;" +
"uniform float vign;" +
"varying vec2 UV;" +
"void main() {" +
"vec4 color;\n" +
"float vignette;\n" +
"vec2 vtc = vec2( (UV - 0.500000));" +
"color = texture2D( filteredPhoto, UV);\n" +
"vignette = pow( (1.00000 - (dot( vtc, vtc) * vign)), 2.00000);\n" +
"gl_FragColor = vec4(color.r * vignette, color.g * vignette, color.b * vignette, 1);" +
"}";
hShaderProgramToneMapping = createprogram(generalreverseVS, tonemapping_FS);
//Film Grain
String filmGrain_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto; //rendered scene sampler\n" +
"uniform float bgl_RenderedTextureWidth; //scene sampler width\n" +
"uniform float bgl_RenderedTextureHeight; //scene sampler height\n" +
"uniform float timer;\n" +
"uniform float grainamount; //grain amount\n" +
"uniform float coloramount;\n" +
"uniform float grainsize;\n" +
"uniform float lumamount;\n" +
"\n" +
"float permTexUnit = 1.0/ 1024.0;\t\t// Perm texture texel-size\n" +
"float permTexUnitHalf = 0.5/1024.0;\t// Half perm texture texel-size\n" +
"\n" +
"float width = bgl_RenderedTextureWidth;\n" +
"float height = bgl_RenderedTextureHeight;\n" +
"\n" +
"varying vec2 UV;" +
" \n" +
"//a random texture generator, but you can also use a pre-computed perturbation texture\n" +
"vec4 rnm(in vec2 tc) \n" +
"{\n" +
" float noise = sin(dot(tc + vec2(timer,timer),vec2(12.9898,78.233))) * 43758.5453;\n" +
"\n" +
"\tfloat noiseR = fract(noise)*2.0-1.0;\n" +
"\tfloat noiseG = fract(noise*1.2154)*2.0-1.0; \n" +
"\tfloat noiseB = fract(noise*1.3453)*2.0-1.0;\n" +
"\tfloat noiseA = fract(noise*1.3647)*2.0-1.0;\n" +
"\t\n" +
"\treturn vec4(noiseR,noiseG,noiseB,noiseA);\n" +
"}\n" +
"\n" +
"float fade(in float t) {\n" +
"\treturn t*t*t*(t*(t*6.0-15.0)+10.0);\n" +
"}\n" +
"\n" +
"float pnoise3D(in vec3 p)\n" +
"{\n" +
"\tvec3 pi = permTexUnit*floor(p)+permTexUnitHalf; // Integer part, scaled so +1 moves permTexUnit texel\n" +
"\t// and offset 1/2 texel to sample texel centers\n" +
"\tvec3 pf = fract(p); // Fractional part for interpolation\n" +
"\n" +
"\t// Noise contributions from (x=0, y=0), z=0 and z=1\n" +
"\tfloat perm00 = rnm(pi.xy).a ;\n" +
"\tvec3 grad000 = rnm(vec2(perm00, pi.z)).rgb * 4.0 - 1.0;\n" +
"\tfloat n000 = dot(grad000, pf);\n" +
"\tvec3 grad001 = rnm(vec2(perm00, pi.z + permTexUnit)).rgb * 4.0 - 1.0;\n" +
"\tfloat n001 = dot(grad001, pf - vec3(0.0, 0.0, 1.0));\n" +
"\n" +
"\t// Noise contributions from (x=0, y=1), z=0 and z=1\n" +
"\tfloat perm01 = rnm(pi.xy + vec2(0.0, permTexUnit)).a ;\n" +
"\tvec3 grad010 = rnm(vec2(perm01, pi.z)).rgb * 4.0 - 1.0;\n" +
"\tfloat n010 = dot(grad010, pf - vec3(0.0, 1.0, 0.0));\n" +
"\tvec3 grad011 = rnm(vec2(perm01, pi.z + permTexUnit)).rgb * 4.0 - 1.0;\n" +
"\tfloat n011 = dot(grad011, pf - vec3(0.0, 1.0, 1.0));\n" +
"\n" +
"\t// Noise contributions from (x=1, y=0), z=0 and z=1\n" +
"\tfloat perm10 = rnm(pi.xy + vec2(permTexUnit, 0.0)).a ;\n" +
"\tvec3 grad100 = rnm(vec2(perm10, pi.z)).rgb * 4.0 - 1.0;\n" +
"\tfloat n100 = dot(grad100, pf - vec3(1.0, 0.0, 0.0));\n" +
"\tvec3 grad101 = rnm(vec2(perm10, pi.z + permTexUnit)).rgb * 4.0 - 1.0;\n" +
"\tfloat n101 = dot(grad101, pf - vec3(1.0, 0.0, 1.0));\n" +
"\n" +
"\t// Noise contributions from (x=1, y=1), z=0 and z=1\n" +
"\tfloat perm11 = rnm(pi.xy + vec2(permTexUnit, permTexUnit)).a ;\n" +
"\tvec3 grad110 = rnm(vec2(perm11, pi.z)).rgb * 4.0 - 1.0;\n" +
"\tfloat n110 = dot(grad110, pf - vec3(1.0, 1.0, 0.0));\n" +
"\tvec3 grad111 = rnm(vec2(perm11, pi.z + permTexUnit)).rgb * 4.0 - 1.0;\n" +
"\tfloat n111 = dot(grad111, pf - vec3(1.0, 1.0, 1.0));\n" +
"\n" +
"\t// Blend contributions along x\n" +
"\tvec4 n_x = mix(vec4(n000, n001, n010, n011), vec4(n100, n101, n110, n111), fade(pf.x));\n" +
"\n" +
"\t// Blend contributions along y\n" +
"\tvec2 n_xy = mix(n_x.xy, n_x.zw, fade(pf.y));\n" +
"\n" +
"\t// Blend contributions along z\n" +
"\tfloat n_xyz = mix(n_xy.x, n_xy.y, fade(pf.z));\n" +
"\n" +
"\t// We're done, return the final noise value.\n" +
"\treturn n_xyz;\n" +
"}\n" +
"\n" +
"//2d coordinate orientation thing\n" +
"vec2 coordRot(in vec2 tc, in float angle)\n" +
"{\n" +
"\tfloat aspect = width/height;\n" +
"\tfloat rotX = ((tc.x*2.0-1.0)*aspect*cos(angle)) - ((tc.y*2.0-1.0)*sin(angle));\n" +
"\tfloat rotY = ((tc.y*2.0-1.0)*cos(angle)) + ((tc.x*2.0-1.0)*aspect*sin(angle));\n" +
"\trotX = ((rotX/aspect)*0.5+0.5);\n" +
"\trotY = rotY*0.5+0.5;\n" +
"\treturn vec2(rotX,rotY);\n" +
"}\n" +
"\n" +
"void main() \n" +
"{\n" +
"\tvec2 texCoord = UV;\n" +
"\t\n" +
"\tvec3 rotOffset = vec3(1.425,3.892,5.835); //rotation offset values\t\n" +
"\tvec2 rotCoordsR = coordRot(texCoord, timer + rotOffset.x);\n" +
"\tvec3 noise = vec3(pnoise3D(vec3(rotCoordsR*vec2(width/grainsize,height/grainsize),0.0)));\n" +
" \n" +
"\tif (coloramount > 0.0)\n" +
"\t{\n" +
"\t\tvec2 rotCoordsG = coordRot(texCoord, timer + rotOffset.y);\n" +
"\t\tvec2 rotCoordsB = coordRot(texCoord, timer + rotOffset.z);\n" +
"\t\tnoise.g = mix(noise.r,pnoise3D(vec3(rotCoordsG*vec2(width/grainsize,height/grainsize),1.0)),coloramount);\n" +
"\t\tnoise.b = mix(noise.r,pnoise3D(vec3(rotCoordsB*vec2(width/grainsize,height/grainsize),2.0)),coloramount);\n" +
"\t}\n" +
"\n" +
"\tvec3 col = texture2D(filteredPhoto, texCoord).rgb;\n" +
"\n" +
"\t//noisiness response curve based on scene luminance\n" +
"\tvec3 lumcoeff = vec3(0.299,0.587,0.114);\n" +
"\tfloat luminance = mix(0.0,dot(col, lumcoeff),lumamount);\n" +
"\tfloat lum = smoothstep(0.2,0.0,luminance);\n" +
"\tlum += luminance;\n" +
"\t\n" +
"\t\n" +
"\tnoise = mix(noise,vec3(0.0),pow(lum,4.0));\n" +
"\tcol = col+noise*grainamount;\n" +
" \n" +
"\tgl_FragColor = vec4(col,1.0);\n" +
"}";
hShaderProgramFilmGrain = createprogram(generalreverseVS, filmGrain_FS);
//FINALPASS
String finalPass_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" gl_FragColor = texture2D(filteredPhoto, UV);" +
"}";
hShaderProgramFinalPass = createprogram(finalPass_FS);
}
private int createprogram(String fssource) { return createprogram(generalVS, fssource);}
private int createprogram(String vssource, String fssource)
{
int toRet;
toRet = GLES20.glCreateProgram();
GLES20.glAttachShader(toRet, compileshader(GLES20.GL_VERTEX_SHADER, vssource));
GLES20.glAttachShader(toRet, compileshader(GLES20.GL_FRAGMENT_SHADER, fssource));
GLES20.glLinkProgram(toRet);
return toRet;
}
String ERROR = "";
private int compileshader(int type, String shaderCode)
{
int shader = GLES20.glCreateShader(type);
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
ERROR = GLES20.glGetShaderInfoLog(shader);
if (ERROR.length() > 0)
throw(new RuntimeException(ERROR));
return shader;
}
private int hPos, hTex;
private int cmp_W, cmp_H, cmp_X, cmp_Y;
public void onDrawFrame(GL10 unused) {
if (BOOL_LoadTexture) {
if (fsv.toLoad != null)
{
fsv.LoadTexture(fsv.toLoad);
int scrW = fsv.getWidth();
int scrH = fsv.getHeight();
float wRat = (float)ImageWidth/(float)scrW;
float hRat = (float)ImageHeigth/(float)scrH;
boolean majW = wRat > hRat ? true : false;
float aspect = (float)(majW ? (float)ImageWidth / (float)ImageHeigth : (float)ImageHeigth / (float)ImageWidth);
if (majW)
{
cmp_W = scrW; cmp_X = 0;
cmp_H = (int)((float)scrW / aspect);
cmp_Y = (int)(((float)scrH-(float)cmp_H) / 2f);
//throw(new RuntimeException("IW: " + ImageWidth + "\nIH: " + ImageHeigth + "\nwRat = " + wRat + "\nhRat = " + hRat + "\nX: " + cmp_X + "\nY: " + cmp_Y + "\nW: " + cmp_W + "\nH: " + cmp_H + "\nscW: " + scrW + "\nscH: " + scrH));
}
else
{
cmp_H = scrH; cmp_Y = 0;
cmp_W = (int)((float)scrH / (float)aspect);
cmp_X = (int)(((float)scrW -(float)cmp_W) / 2f);
}
}
BOOL_LoadTexture =false;
}
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
if (PARAMS_EnableCathodeRayTube)
{
SetRenderTarget();
GLES20.glUseProgram(hShaderProgramCathodeRayTube);
setVSParams(hShaderProgramCathodeRayTube);
setShaderParamPhoto(hShaderProgramCathodeRayTube, GetCurTexture());
int pxw = GLES20.glGetUniformLocation(hShaderProgramCathodeRayTube, "pixwidth");
int pxh = GLES20.glGetUniformLocation(hShaderProgramCathodeRayTube, "pixheigth");
int hrz = GLES20.glGetUniformLocation(hShaderProgramCathodeRayTube, "horizontal");
int lnw = GLES20.glGetUniformLocation(hShaderProgramCathodeRayTube, "linewidth");
if (pxw < 0 || pxh < 0 || hrz < 0 || lnw < 0) throw(new RuntimeException("ff"));
//if (true) throw new RuntimeException("pxw = " + (float)(1f / (float)ImageWidth));
GLES20.glUniform1f(pxw, (float)(1f / (float)ImageWidth));
GLES20.glUniform1f(pxh, (float)(1f / (float)ImageHeigth));
GLES20.glUniform1i(lnw, PARAMS_CathodeRayTubeLineWidth);
GLES20.glUniform1i(hrz, PARAMS_CathodeRayTubeIsHorizontal ? 1 : 0);
drawquad();
}
if (PARAMS_EnableBlackAndWhite)
{
SetRenderTarget();
GLES20.glUseProgram(hShaderProgramBlackAndWhite);
setVSParams(hShaderProgramBlackAndWhite);
setShaderParamPhoto(hShaderProgramBlackAndWhite, GetCurTexture());
drawquad();
}
if (PARAMS_EnableSepia)
{
SetRenderTarget();
GLES20.glUseProgram(hShaderProgramSepia);
setVSParams(hShaderProgramSepia);
setShaderParamPhoto(hShaderProgramSepia, GetCurTexture());
drawquad();
}
if (PARAMS_EnableToneMapping && (PARAMS_ToneMappingExposure != 0 || PARAMS_ToneMappingVignetting != 0))
{
SetRenderTarget();
GLES20.glUseProgram(hShaderProgramToneMapping);
setVSParams(hShaderProgramToneMapping);
setShaderParamPhoto(hShaderProgramToneMapping, GetCurTexture());
int exposure = GLES20.glGetUniformLocation(hShaderProgramToneMapping, "exposure");
int vign = GLES20.glGetUniformLocation(hShaderProgramToneMapping, "vign");
GLES20.glUniform1f(exposure, PARAMS_ToneMappingExposure);
GLES20.glUniform1f(vign, PARAMS_ToneMappingVignetting);
drawquad();
}
if (PARAMS_EnableFilmGrain)
{
SetRenderTarget();
GLES20.glUseProgram(hShaderProgramFilmGrain);
setVSParams(hShaderProgramFilmGrain);
setShaderParamPhoto(hShaderProgramFilmGrain, GetCurTexture());
int w = GLES20.glGetUniformLocation(hShaderProgramFilmGrain, "bgl_RenderedTextureWidth");
int h = GLES20.glGetUniformLocation(hShaderProgramFilmGrain, "bgl_RenderedTextureHeight");
int t = GLES20.glGetUniformLocation(hShaderProgramFilmGrain, "timer");
int ga = GLES20.glGetUniformLocation(hShaderProgramFilmGrain, "grainamount");
int ca = GLES20.glGetUniformLocation(hShaderProgramFilmGrain, "coloramount");
int gs = GLES20.glGetUniformLocation(hShaderProgramFilmGrain, "grainsize");
int la = GLES20.glGetUniformLocation(hShaderProgramFilmGrain, "lumamount");
GLES20.glUniform1f(w, ImageWidth);
GLES20.glUniform1f(h, ImageHeigth);
GLES20.glUniform1f(ga, PARAMS_FilmGrainAmount);
GLES20.glUniform1f(gs, PARAMS_FilmGrainParticleSize);
GLES20.glUniform1f(la, PARAMS_FilmGrainLuminance);
GLES20.glUniform1f(ca,PARAMS_FilmGrainColorAmount );
GLES20.glUniform1f(t, PARAMS_FilmGrainSeed);
drawquad();
}
if (didshit)
firstshit= false;
first=!first;
RenderTarget2D.SetDefault(cmp_X, cmp_Y, cmp_W, cmp_H);
GLES20.glUseProgram(hShaderProgramFinalPass);
setVSParams(hShaderProgramFinalPass);
int tx = GetCurTexture();
setShaderParamPhoto(hShaderProgramFinalPass, tx);
drawquad();
didshit = false;
firstshit = true;
}
public void setPARAMS_FilmGrainSeed(float v)
{
Random r = new Random();
v*= 10;
float a = (float)(r.nextInt(10) - 1);
v+=a;
PARAMS_FilmGrainSeed = v;
}
public int rtid;
private void setShaderParamPhoto(int program, int texID)
{
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID);
int loc = GLES20.glGetUniformLocation(program, "filteredPhoto");
if (loc == -1) throw(new RuntimeException("SHEEEET"));
GLES20.glUniform1i(loc, 0);
}
boolean first = true;
boolean didshit = false;
boolean firstshit = true;
private void SetRenderTarget()
{
if (didshit) firstshit = false;
didshit = true;
if (first)
{
target1.Set();
first = false;
}
else
{
target2.Set();
first = true;
}
}
private int GetCurTexture()
{
if (firstshit) return hToFilterTexture[0];
if (first) {rtid = 1;return target1.GetTex();}
else { rtid = 2;return target2.GetTex();}
}
private void drawquad(){ GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);
GLES20.glDisableVertexAttribArray(hPos);
GLES20.glDisableVertexAttribArray(hTex);}
private void setVSParams(int program){setVSParamspos(program); setVSParamstc(program);}
private void setVSParamspos(int program) {
hPos = GLES20.glGetAttribLocation(program, "vPosition");
GLES20.glEnableVertexAttribArray(hPos);
GLES20.glVertexAttribPointer(hPos, 3,
GLES20.GL_FLOAT, false,
12, VB);
}
private void setVSParamstc(int program) {
hTex = GLES20.glGetAttribLocation(program, "texCoords");
GLES20.glEnableVertexAttribArray(hTex);
GLES20.glVertexAttribPointer(hTex, 2,
GLES20.GL_FLOAT, false,
8, TC);
}
public void onSurfaceChanged(GL10 unused, int width, int height)
{
GLES20.glViewport(0, 0, width, height);
}
}
|
// Package
package com.hp.hpl.jena.ontology.impl.test;
// Imports
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
import com.hp.hpl.jena.enhanced.EnhGraph;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.graph.impl.*;
import com.hp.hpl.jena.mem.GraphMem;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.ontology.daml.*;
import com.hp.hpl.jena.ontology.daml.DAMLModel;
import com.hp.hpl.jena.ontology.impl.OntClassImpl;
import com.hp.hpl.jena.ontology.tidy.SyntaxProblem;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.rdf.model.impl.ModelMakerImpl;
import com.hp.hpl.jena.reasoner.*;
import com.hp.hpl.jena.reasoner.ReasonerRegistry;
import com.hp.hpl.jena.reasoner.test.TestUtil;
import com.hp.hpl.jena.util.FileUtils;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.*;
import com.hp.hpl.jena.vocabulary.OWL;
import junit.framework.*;
/**
* <p>
* Unit tests that are derived from user bug reports
* </p>
*
* @author Ian Dickinson, HP Labs (<a href="mailto:Ian.Dickinson@hp.com" >
* email</a>)
* @version CVS $Id: TestBugReports.java,v 1.23 2003/11/20 17:53:10
* ian_dickinson Exp $
*/
public class TestBugReports
extends TestCase
{
// Constants
public static String NS = "http://example.org/test
// Static variables
// Instance variables
public TestBugReports(String name) {
super(name);
}
// Constructors
// External signature methods
public void setUp() {
// ensure the ont doc manager is in a consistent state
OntDocumentManager.getInstance().reset( true );
}
/** Bug report by Danah Nada - listIndividuals returning too many results */
public void test_dn_0() {
OntModel schema = ModelFactory.createOntologyModel( OntModelSpec.OWL_LITE_MEM_RULES_INF, null );
schema.read( "file:doc/inference/data/owlDemoSchema.xml", null );
int count = 0;
for (Iterator i = schema.listIndividuals(); i.hasNext(); ) {
//Resource r = (Resource) i.next();
i.next();
count++;
System.out.println("----------");
/* Bug report by Danah Nada - duplicate elements in property domain */
/** Bug report by Danah Nada - cannot remove import */
/**
* Bug report by Mariano Rico Almodvar [Mariano.Rico@uam.es] on June 16th.
* Said to raise exception.
*/
public void test_mra_01() {
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.DAML_MEM, null, null);
String myDicURI = "http://somewhere/myDictionaries/1.0
String damlURI = "http://www.daml.org/2001/03/daml+oil
m.setNsPrefix("DAML", damlURI);
String c1_uri = myDicURI + "C1";
OntClass c1 = m.createClass(c1_uri);
DatatypeProperty p1 = m.createDatatypeProperty(myDicURI + "P1");
p1.setDomain(c1);
ByteArrayOutputStream strOut = new ByteArrayOutputStream();
m.write(strOut, "RDF/XML-ABBREV", myDicURI);
//m.write(System.out,"RDF/XML-ABBREV", myDicURI);
}
/**
* Bug report from Holger Knublauch on July 25th 2003. Cannot convert
* owl:Class to an OntClass
*/
public void test_hk_01() {
// synthesise a mini-document
String base = "http://jena.hpl.hp.com/test
String doc =
"<rdf:RDF"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl
+ " <owl:Ontology rdf:about=\"\">"
+ " <owl:imports rdf:resource=\"http:
+ " </owl:Ontology>"
+ "</rdf:RDF>";
// read in the base ontology, which includes the owl language
// definition
// note OWL_MEM => no reasoner is used
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
m.getDocumentManager().setMetadataSearchPath( "file:etc/ont-policy-test.rdf", true );
m.read(new ByteArrayInputStream(doc.getBytes()), base);
// we need a resource corresponding to OWL Class but in m
Resource owlClassRes = m.getResource(OWL.Class.getURI());
// now can we see this as an OntClass?
OntClass c = (OntClass) owlClassRes.as(OntClass.class);
assertNotNull("OntClass c should not be null", c);
//(OntClass) (ontModel.getProfile().CLASS()).as(OntClass.class);
}
/**
* Bug report from Hoger Knublauch on Aug 19th 2003. NPE when setting all
* distinct members
*/
public void test_hk_02() {
OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM);
spec.setReasoner(null);
OntModel ontModel = ModelFactory.createOntologyModel(spec, null); // ProfileRegistry.OWL_LANG);
ontModel.createAllDifferent();
assertTrue(ontModel.listAllDifferent().hasNext());
AllDifferent allDifferent = (AllDifferent) ontModel.listAllDifferent().next();
//allDifferent.setDistinct(ontModel.createList());
assertFalse(allDifferent.listDistinctMembers().hasNext());
}
/** Bug report from Holger Knublauch on Aug 19th, 2003. Initialisation error */
public void test_hk_03() {
OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM);
spec.setReasoner(null);
OntModel ontModel = ModelFactory.createOntologyModel(spec, null);
OntProperty property = ontModel.createObjectProperty("http://www.aldi.de#property");
/* MinCardinalityRestriction testClass = */
ontModel.createMinCardinalityRestriction(null, property, 42);
}
/**
* Bug report from Holger Knublauch on Aug 19th, 2003. Document manager alt
* mechanism breaks relative name translation
*/
public void test_hk_04() {
OntModel m = ModelFactory.createOntologyModel();
m.getDocumentManager().addAltEntry(
"http://jena.hpl.hp.com/testing/ontology/relativenames",
"file:testing/ontology/relativenames.rdf");
m.read("http://jena.hpl.hp.com/testing/ontology/relativenames");
assertTrue(
"#A should be a class",
m.getResource("http://jena.hpl.hp.com/testing/ontology/relativenames#A").canAs(OntClass.class));
assertFalse(
"file: #A should not be a class",
m.getResource("file:testing/ontology/relativenames.rdf#A").canAs(OntClass.class));
}
/** Bug report from Holger Knublach: not all elements of a union are removed */
public void test_hk_05() {
OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM);
spec.setReasoner(null);
OntModel ontModel = ModelFactory.createOntologyModel(spec, null);
String ns = "http://foo.bar/fu
OntClass a = ontModel.createClass(ns + "A");
OntClass b = ontModel.createClass(ns + "B");
int oldCount = getStatementCount(ontModel);
RDFList members = ontModel.createList(new RDFNode[] { a, b });
IntersectionClass intersectionClass = ontModel.createIntersectionClass(null, members);
intersectionClass.remove();
assertEquals("Before and after statement counts are different", oldCount, getStatementCount(ontModel));
}
/**
* Bug report from Holger Knublach: moving between ontology models - comes
* down to a test for a resource being in the base model
*/
public void test_hk_06() throws Exception {
OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
ontModel.read("file:testing/ontology/bugs/test_hk_06/a.owl");
String NSa = "http://jena.hpl.hp.com/2003/03/testont/a
String NSb = "http://jena.hpl.hp.com/2003/03/testont/b
OntClass A = ontModel.getOntClass(NSa + "A");
assertTrue("class A should be in the base model", ontModel.isInBaseModel(A));
OntClass B = ontModel.getOntClass(NSb + "B");
assertFalse("class B should not be in the base model", ontModel.isInBaseModel(B));
assertTrue(
"A rdf:type owl:Class should be in the base model",
ontModel.isInBaseModel(ontModel.createStatement(A, RDF.type, OWL.Class)));
assertFalse(
"B rdf:type owl:Class should not be in the base model",
ontModel.isInBaseModel(ontModel.createStatement(B, RDF.type, OWL.Class)));
}
public void test_hk_importCache() {
final String BASE = "http://protege.stanford.edu/plugins/owl/testdata/";
OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM);
spec.setReasoner(null);
OntDocumentManager dm = OntDocumentManager.getInstance();
dm.reset();
dm.setCacheModels(false);
dm.addAltEntry( "http://protege.stanford.edu/plugins/owl/testdata/Import-normalizerBug.owl",
"file:testing/ontology/bugs/test_hk_import/Import-normalizerBug.owl" );
dm.addAltEntry( "http://protege.stanford.edu/plugins/owl/testdata/normalizerBug.owl",
"file:testing/ontology/bugs/test_hk_import/normalizerBug.owl" );
spec.setDocumentManager(dm);
OntModel oldOntModel = ModelFactory.createOntologyModel(spec, null);
oldOntModel.read(BASE + "Import-normalizerBug.owl", FileUtils.langXMLAbbrev);
Graph oldSubGraph = (Graph) oldOntModel.getSubGraphs().iterator().next();
final int oldTripleCount = getTripleCount(oldSubGraph);
OntClass ontClass = oldOntModel.getOntClass(BASE + "normalizerBug.owl#SuperClass");
oldSubGraph.add(new Triple(ontClass.getNode(), RDF.type.getNode(), OWL.DeprecatedClass.getNode()));
assertEquals(oldTripleCount + 1, getTripleCount(oldSubGraph));
// TODO this workaround to be removed
SimpleGraphMaker sgm = (SimpleGraphMaker) ((ModelMakerImpl) spec.getImportModelMaker()).getGraphMaker();
List toGo = new ArrayList();
for (Iterator i = sgm.listGraphs(); i.hasNext(); toGo.add( i.next() ));
for (Iterator i = toGo.iterator(); i.hasNext(); sgm.removeGraph( (String) i.next() ));
dm.clearCache();
OntModel newOntModel = ModelFactory.createOntologyModel(spec, null);
newOntModel.read(BASE + "Import-normalizerBug.owl", FileUtils.langXMLAbbrev);
Graph newSubGraph = (Graph) newOntModel.getSubGraphs().iterator().next();
assertFalse(newOntModel == oldOntModel);
assertFalse(newSubGraph == oldSubGraph); // FAILS!
final int newTripleCount = getTripleCount(newSubGraph);
assertEquals(oldTripleCount, newTripleCount);
}
private int getTripleCount(Graph graph) {
int count = 0;
for (Iterator it = graph.find(null, null, null); it.hasNext();) {
it.next();
count++;
}
return count;
}
/**
* Bug report by federico.carbone@bt.com, 30-July-2003. A literal can be
* turned into an individual.
*/
public void test_fc_01() {
OntModel m = ModelFactory.createOntologyModel();
ObjectProperty p = m.createObjectProperty(NS + "p");
Restriction r = m.createRestriction(p);
HasValueRestriction hv = r.convertToHasValueRestriction(m.createLiteral(1));
RDFNode n = hv.getHasValue();
assertFalse("Should not be able to convert literal to individual", n.canAs(Individual.class));
}
/**
* Bug report by Christoph Kunze (Christoph.Kunz@iao.fhg.de). 18/Aug/03 No
* transaction support in ontmodel.
*/
public void test_ck_01() {
Graph g = new GraphMem() {
TransactionHandler m_t = new MockTransactionHandler();
public TransactionHandler getTransactionHandler() {
return m_t;
}
};
Model m0 = ModelFactory.createModelForGraph(g);
OntModel m1 = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM, m0);
assertFalse(
"Transaction not started yet",
((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction);
m1.begin();
assertTrue(
"Transaction started",
((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction);
m1.abort();
assertFalse(
"Transaction aborted",
((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction);
assertTrue("Transaction aborted", ((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_aborted);
m1.begin();
assertTrue(
"Transaction started",
((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction);
m1.commit();
assertFalse(
"Transaction committed",
((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction);
assertTrue(
"Transaction committed",
((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_committed);
}
/**
* Bug report by Christoph Kunz, 26/Aug/03. CCE when creating a statement
* from a vocabulary
*
*/
public void test_ck_02() {
OntModel vocabModel = ModelFactory.createOntologyModel();
ObjectProperty p = vocabModel.createObjectProperty("p");
OntClass A = vocabModel.createClass("A");
OntModel workModel = ModelFactory.createOntologyModel();
Individual sub = workModel.createIndividual("uri1", A);
Individual obj = workModel.createIndividual("uri2", A);
workModel.createStatement(sub, p, obj);
}
/**
* Bug report from Christoph Kunz - reification problems and
* UnsupportedOperationException
*/
public void test_ck_03() {
// part A - surprising reification
OntModel model1 = ModelFactory.createOntologyModel(OntModelSpec.DAML_MEM, null);
OntModel model2 = ModelFactory.createOntologyModel(OntModelSpec.DAML_MEM_RULE_INF, null);
Individual sub = model1.createIndividual("http://mytest#i1", model1.getProfile().CLASS());
OntProperty pred = model1.createOntProperty("http://mytest
Individual obj = model1.createIndividual("http://mytest#i2", model1.getProfile().CLASS());
OntProperty probabilityP = model1.createOntProperty("http://mytest#prob");
Statement st = model1.createStatement(sub, pred, obj);
model1.add(st);
st.createReifiedStatement().addProperty(probabilityP, 0.9);
assertTrue("st should be reified", st.isReified());
Statement st2 = model2.createStatement(sub, pred, obj);
model2.add(st2);
st2.createReifiedStatement().addProperty(probabilityP, 0.3);
assertTrue("st2 should be reified", st2.isReified());
sub.addProperty(probabilityP, 0.3);
sub.removeAll(probabilityP).addProperty(probabilityP, 0.3);
// exception
// Part B - exception in remove All
Individual sub2 = model2.createIndividual("http://mytest#i1", model1.getProfile().CLASS());
sub.addProperty(probabilityP, 0.3);
sub.removeAll(probabilityP); //!!! exception
sub2.addProperty(probabilityP, 0.3);
sub2.removeAll(probabilityP); //!!! exception
}
/**
* Bug report by sjooseng [sjooseng@hotmail.com]. CCE in listOneOf in
* Enumerated Class with DAML profile.
*/
public void test_sjooseng_01() {
String source =
"<rdf:RDF xmlns:daml='http://www.daml.org/2001/03/daml+oil
+ " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns
+ " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema
+ " <daml:Class rdf:about='http://localhost:8080/kc2c
+ " <daml:subClassOf>"
+ " <daml:Restriction>"
+ " <daml:onProperty rdf:resource='http://localhost:8080/kc2c
+ " <daml:hasClass>"
+ " <daml:Class>"
+ " <daml:oneOf rdf:parseType=\"daml:collection\">"
+ " <daml:Thing rdf:about='http://localhost:8080/kc2c
+ " <daml:Thing rdf:about='http://localhost:8080/kc2c
+ " </daml:oneOf>"
+ " </daml:Class>"
+ " </daml:hasClass>"
+ " </daml:Restriction>"
+ " </daml:subClassOf>"
+ " </daml:Class>"
+ " <daml:ObjectProperty rdf:about='http://localhost:8080/kc2c
+ " <rdfs:label>p1</rdfs:label>"
+ " </daml:ObjectProperty>"
+ "</rdf:RDF>";
OntModel m = ModelFactory.createOntologyModel(ProfileRegistry.DAML_LANG);
m.read(new ByteArrayInputStream(source.getBytes()), "http://localhost:8080/kc2c");
OntClass kc1 = m.getOntClass("http://localhost:8080/kc2c
boolean found = false;
Iterator it = kc1.listSuperClasses(false);
while (it.hasNext()) {
OntClass oc = (OntClass) it.next();
if (oc.isRestriction()) {
Restriction r = oc.asRestriction();
if (r.isSomeValuesFromRestriction()) {
SomeValuesFromRestriction sr = r.asSomeValuesFromRestriction();
OntClass sc = (OntClass) sr.getSomeValuesFrom();
if (sc.isEnumeratedClass()) {
EnumeratedClass ec = sc.asEnumeratedClass();
assertEquals("Enumeration size should be 2", 2, ec.getOneOf().size());
found = true;
}
}
}
}
assertTrue(found);
}
/**
* Problem reported by Andy Seaborne - combine abox and tbox in RDFS with
* ontmodel
*/
public void test_afs_01() {
String sourceT =
"<rdf:RDF "
+ " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns
+ " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl
+ " <owl:Class rdf:about='http://example.org/foo
+ " </owl:Class>"
+ "</rdf:RDF>";
String sourceA =
"<rdf:RDF "
+ " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns
+ " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl
+ " <rdf:Description rdf:about='http://example.org/foo
+ " <rdf:type rdf:resource='http://example.org/foo
+ " </rdf:Description>"
+ "</rdf:RDF>";
Model tBox = ModelFactory.createDefaultModel();
tBox.read(new ByteArrayInputStream(sourceT.getBytes()), "http://example.org/foo");
Model aBox = ModelFactory.createDefaultModel();
aBox.read(new ByteArrayInputStream(sourceA.getBytes()), "http://example.org/foo");
Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
reasoner = reasoner.bindSchema(tBox);
OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM_RULE_INF);
spec.setReasoner(reasoner);
OntModel m = ModelFactory.createOntologyModel(spec, aBox);
List inds = new ArrayList();
for (Iterator i = m.listIndividuals(); i.hasNext();) {
inds.add(i.next());
}
assertTrue("x should be an individual", inds.contains(m.getResource("http://example.org/foo
}
/**
* Bug report by Thorsten Ottmann [Thorsten.Ottmann@rwth-aachen.de] -
* problem accessing elements of DAML list
*/
public void test_to_01() {
String sourceT =
"<rdf:RDF "
+ " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns
+ " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema
+ " xmlns:daml='http://www.daml.org/2001/03/daml+oil
+ " <daml:Class rdf:about='http://example.org/foo
+ " <daml:intersectionOf rdf:parseType=\"daml:collection\">"
+ " <daml:Class rdf:ID=\"B\" />"
+ " <daml:Class rdf:ID=\"C\" />"
+ " </daml:intersectionOf>"
+ " </daml:Class>"
+ "</rdf:RDF>";
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.DAML_MEM, null);
m.read(new ByteArrayInputStream(sourceT.getBytes()), "http://example.org/foo");
OntClass A = m.getOntClass("http://example.org/foo
assertNotNull(A);
IntersectionClass iA = A.asIntersectionClass();
assertNotNull(iA);
RDFList intersection = iA.getOperands();
assertNotNull(intersection);
assertEquals(2, intersection.size());
assertTrue(intersection.contains(m.getOntClass("http://example.org/foo
assertTrue(intersection.contains(m.getOntClass("http://example.org/foo
}
/**
* Bug report by Thorsten Liebig [liebig@informatik.uni-ulm.de] -
* SymmetricProperty etc not visible in list ont properties
*/
public void test_tl_01() {
String sourceT =
"<rdf:RDF "
+ " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns
+ " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl
+ " <owl:SymmetricProperty rdf:about='http://example.org/foo
+ " </owl:SymmetricProperty>"
+ " <owl:TransitiveProperty rdf:about='http://example.org/foo
+ " </owl:TransitiveProperty>"
+ " <owl:InverseFunctionalProperty rdf:about='http://example.org/foo
+ " </owl:InverseFunctionalProperty>"
+ "</rdf:RDF>";
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF, null);
m.read(new ByteArrayInputStream(sourceT.getBytes()), "http://example.org/foo");
boolean foundP1 = false;
boolean foundP2 = false;
boolean foundP3 = false;
// iterator of properties should include p1-3
for (Iterator i = m.listOntProperties(); i.hasNext();) {
Resource r = (Resource) i.next();
foundP1 = foundP1 || r.getURI().equals("http://example.org/foo
foundP2 = foundP2 || r.getURI().equals("http://example.org/foo
foundP3 = foundP3 || r.getURI().equals("http://example.org/foo
}
assertTrue("p1 not listed", foundP1);
assertTrue("p2 not listed", foundP2);
assertTrue("p3 not listed", foundP3);
foundP1 = false;
foundP2 = false;
foundP3 = false;
// iterator of object properties should include p1-3
for (Iterator i = m.listObjectProperties(); i.hasNext();) {
Resource r = (Resource) i.next();
foundP1 = foundP1 || r.getURI().equals("http://example.org/foo
foundP2 = foundP2 || r.getURI().equals("http://example.org/foo
foundP3 = foundP3 || r.getURI().equals("http://example.org/foo
}
assertTrue("p1 not listed", foundP1);
assertTrue("p2 not listed", foundP2);
assertTrue("p3 not listed", foundP3);
}
/** Bug report by Dave Reynolds - SF bug report 810492 */
public void test_der_01() {
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM_TRANS_INF, null);
Resource a = m.createResource("http://example.org
Resource b = m.createResource("http://example.org
OntClass A = new OntClassImpl(a.getNode(), (EnhGraph) m) {
protected boolean hasSuperClassDirect(Resource cls) {
throw new RuntimeException("did not find direct reasoner");
}
};
// will throw an exception if the wrong code path is taken
A.hasSuperClass(b, true);
}
/**
* Bug report by Ivan Ferrari (ivan_ferrari_75 [ivan_ferrari_75@yahoo.it]) -
* duplicate nodes in output
*/
public void test_if_01() {
//create a new default model
OntModel m = ModelFactory.createOntologyModel();
m.getDocumentManager().addAltEntry(
"http:
"file:testing/reasoners/bugs/wine.owl");
m.getDocumentManager().addAltEntry(
"http:
"file:testing/reasoners/bugs/food.owl");
// note: due to bug in the Wine example, we have to manually read the
// imported food document
m.getDocumentManager().setProcessImports(false);
m.read("http:
m.getDocumentManager().setProcessImports(true);
m.getDocumentManager().loadImport(m, "http:
OntClass ontclass = m.getOntClass("http://www.w3.org/2001/sw/WebOnt/guide-src/wine#Wine");
int nNamed = 0;
int nRestriction = 0;
int nAnon = 0;
for (ExtendedIterator iter2 = ontclass.listSuperClasses(true); iter2.hasNext();) {
OntClass ontsuperclass = (OntClass) iter2.next();
//this is to view different anonymous IDs
if (!ontsuperclass.isAnon()) {
nNamed++;
}
else if (ontsuperclass.canAs(Restriction.class)) {
ontsuperclass.asRestriction();
nRestriction++;
}
else {
//System.out.println("anon. super: " + ontsuperclass.getId());
nAnon++;
}
}
assertEquals("Should be two named super classes ", 2, nNamed);
assertEquals("Should be nine named super classes ", 9, nRestriction);
assertEquals("Should be no named super classes ", 0, nAnon);
}
/** Bug report by Lawrence Tay - missing datatype property */
public void test_lt_01() {
OntModel m = ModelFactory.createOntologyModel();
DatatypeProperty p = m.createDatatypeProperty(NS + "p");
OntClass c = m.createClass(NS + "A");
Individual i = m.createIndividual(NS + "i", c);
i.addProperty(p, "testData");
int count = 0;
for (Iterator j = i.listPropertyValues(p); j.hasNext();) {
//System.err.println("Individual i has p value: " + j.next());
j.next();
count++;
}
assertEquals("i should have one property", 1, count);
}
/** Bug report by David Kensche [david.kensche@post.rwth-aachen.de] - NPE in listDeclaredProperties */
public void test_dk_01() {
OntModel m = ModelFactory.createOntologyModel();
m.read( "file:testing/ontology/bugs/test_dk_01.xml" );
String NS = "http://localhost:8080/Repository/QueryAgent/UserOntology/qgen-example-1
String[] classes = new String[] {NS+"C1", NS+"C3", NS+"C2"};
for (int i = 0; i < classes.length; i++) {
OntClass c = m.getOntClass( classes[i] );
for (Iterator j = c.listDeclaredProperties(); j.hasNext(); j.next() );
}
}
/** Bug report by Paulo Pinheiro da Silva [pp@ksl.stanford.edu] - exception while accessing PropertyAccessor.getDAMLValue */
public void test_ppds_01() {
DAMLModel m = ModelFactory.createDAMLModel();
DAMLClass c = m.createDAMLClass( NS + "C" );
DAMLInstance x = m.createDAMLInstance( c, NS + "x" );
DAMLProperty p = m.createDAMLProperty( NS + "p" );
x.addProperty( p, "(s (s 0))" );
PropertyAccessor a = x.accessProperty( p );
assertNull( "Property accessor value should be null", a.getDAMLValue() );
}
/** Bug report by anon at SourceForge - Bug ID 887409 */
public void test_anon_0() {
String NS = "http://example.org/foo
String sourceT =
"<rdf:RDF "
+ " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns
+ " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema
+ " xmlns:ex='http://example.org/foo
+ " xmlns:owl='http://www.w3.org/2002/07/owl
+ " <owl:ObjectProperty rdf:about='http://example.org/foo
+ " <owl:Class rdf:about='http://example.org/foo
+ " <ex:A rdf:about='http://example.org/foo
+ " <owl:Class rdf:about='http://example.org/foo
+ " <owl:equivalentClass>"
+ " <owl:Restriction>"
+ " <owl:onProperty rdf:resource='http://example.org/foo
+ " <owl:hasValue rdf:resource='http://example.org/foo
+ " </owl:Restriction>"
+ " </owl:equivalentClass>"
+ " </owl:Class>"
+ "</rdf:RDF>";
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
m.read(new ByteArrayInputStream(sourceT.getBytes()), "http://example.org/foo");
OntClass B = m.getOntClass( NS + "B");
Restriction r = B.getEquivalentClass().asRestriction();
HasValueRestriction hvr = r.asHasValueRestriction();
RDFNode n = hvr.getHasValue();
assertTrue( "Should be an individual", n instanceof Individual );
}
/** Bug report by Zhao Jun [jeff@seu.edu.cn] - throws no such element exception */
public void test_zj_0() {
String NS = "file:/C:/orel/orel0_5.owl
String sourceT =
"<rdf:RDF " +
" xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns
" xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema
" xmlns:ex='http://example.org/foo
" xmlns:owl='http://www.w3.org/2002/07/owl
" xmlns:orel='file:/C:/orel/orel0_5.owl
" xml:base='file:/C:/orel/orel0_5.owl
" xmlns='file:/C:/orel/orel0_5.owl
" <owl:ObjectProperty rdf:ID='hasAgent' />" +
" <owl:ObjectProperty rdf:ID='hasResource' />" +
" <owl:Class rdf:ID='MyPlay'>" +
" <rdfs:subClassOf>" +
" <owl:Restriction>" +
" <owl:onProperty rdf:resource='file:/C:/orel/orel0_5.owl#hasResource'/>" +
" <owl:hasValue>" +
" <orel:Resource rdf:ID='myResource'>" +
" <orel:resourceURI>http://mp3.com/newcd/sample.mp3</orel:resourceURI>" +
" </orel:Resource>" +
" </owl:hasValue>" +
" </owl:Restriction>" +
" </rdfs:subClassOf>" +
" <rdfs:subClassOf rdf:resource='http://www.w3.org/2002/07/owl#Thing'/>" +
" <rdfs:subClassOf>" +
" <owl:Restriction>" +
" <owl:onProperty rdf:resource='file:/C:/orel/orel0_5.owl#hasAgent'/>" +
" <owl:hasValue>" +
" <orel:Agent rdf:ID='myAgent'>" +
" <orel:agentPK>123456789</orel:agentPK>" +
" </orel:Agent>" +
" </owl:hasValue>" +
" </owl:Restriction>" +
" </rdfs:subClassOf>" +
" <rdfs:subClassOf rdf:resource='file:/C:/orel/orel0_5.owl#Play'/>" +
" </owl:Class>" +
"</rdf:RDF>";
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF, null);
m.read(new ByteArrayInputStream(sourceT.getBytes()), "file:/C:/orel/orel0_5.owl");
OntClass myPlay = m.getOntClass( NS + "MyPlay");
for (Iterator i = myPlay.listDeclaredProperties(); i.hasNext(); ) {
//System.err.println( "prop " + i.next() );
i.next();
}
}
/* Bug reprort by E. Johnson ejohnson@carolina.rr.com - ill formed list in writer */
public void test_ej_01() {
String BASE = "http://jena.hpl.hp.com/testing/ontology";
String NS = BASE + "
DAMLModel m = ModelFactory.createDAMLModel();
DAMLClass A = m.createDAMLClass(NS + "A");
DAMLClass B = m.createDAMLClass(NS + "B");
DAMLClass C = m.createDAMLClass(NS + "C");
DAMLList l = m.createDAMLList(new RDFNode[] {A, B, C});
assertTrue( l.isValid() );
Model baseModel = m.getBaseModel();
RDFWriter writer = baseModel.getWriter("RDF/XML-ABBREV");
// will generate warnings, so suppress until Jeremy has fixed
ByteArrayOutputStream out = new ByteArrayOutputStream();
//writer.write(baseModel, out, BASE );
}
/** Bug report by Harry Chen - closed exception when reading many models */
public void test_hc_01()
throws Exception
{
for (int i = 0; i < 5; i++) {
OntModel m = ModelFactory.createOntologyModel();
FileInputStream ifs = new FileInputStream("testing/ontology/relativenames.rdf");
//System.out.println("Start reading...");
m.read(ifs, "http://example.org/foo");
//System.out.println("Done reading...");
ifs.close();
//System.out.println("Closed ifs");
m.close();
//System.out.println("Closed model");
}
}
/** Bug report by sinclair bain (slbain) SF bugID 912202 - NPE in createOntResource() when 2nd param is null */
public void test_sb_01() {
OntModel model= ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RDFS_INF, null);
Resource result= null;
Resource nullValueForResourceType= null;
result= model.createOntResource( OntResource.class, nullValueForResourceType, "http://www.somewhere.com/models#SomeResourceName" );
assertNotNull( result );
}
/* Bug report from Dave Reynolds: listDeclaredProperties not complete */
public void test_der_02() {
String SOURCE=
"<?xml version='1.0'?>" +
"<!DOCTYPE owl [" +
" <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns
" <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema
" <!ENTITY xsd 'http://www.w3.org/2001/XMLSchema
" <!ENTITY owl 'http://www.w3.org/2002/07/owl
" <!ENTITY dc 'http://purl.org/dc/elements/1.1/' >" +
" <!ENTITY base 'http://jena.hpl.hp.com/test' >" +
" ]>" +
"<rdf:RDF xmlns:owl ='&owl;' xmlns:rdf='&rdf;' xmlns:rdfs='&rdfs;' xmlns:dc='&dc;' xmlns='&base;#' xml:base='&base;'>" +
" <owl:ObjectProperty rdf:ID='hasPublications'>" +
" <rdfs:domain>" +
" <owl:Class>" +
" <owl:unionOf rdf:parseType='Collection'>" +
" <owl:Class rdf:about='#Project'/>" +
" <owl:Class rdf:about='#Task'/>" +
" </owl:unionOf>" +
" </owl:Class>" +
" </rdfs:domain>" +
" <rdfs:domain rdf:resource='#Dummy' />" +
" <rdfs:range rdf:resource='#Publications'/>" +
" </owl:ObjectProperty>" +
" <owl:Class rdf:ID='Dummy'>" +
" </owl:Class>" +
"</rdf:RDF>";
String NS = "http://jena.hpl.hp.com/test
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
m.read(new ByteArrayInputStream( SOURCE.getBytes()), NS );
OntClass dummy = m.getOntClass( NS + "Dummy" );
// assert commented out - bug not accepted -ijd
//TestUtil.assertIteratorValues( this, dummy.listDeclaredProperties(),
// new Object[] {m.getObjectProperty( NS+"hasPublications")} );
}
/**
* Bug report by pierluigi.damadio@katamail.com: raises conversion exception
*/
public void test_pd_01() {
String SOURCE =
"<?xml version='1.0'?>" +
"<rdf:RDF" +
" xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns
" xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema
" xmlns:owl='http://www.w3.org/2002/07/owl
" xml:base='http://iasi.cnr.it/leks/localSchema1
" xmlns:test='http://iasi.cnr.it/test/test1
" xmlns='http://iasi.cnr.it/test/test1
" <owl:Ontology rdf:about=''/>" +
" <owl:Class rdf:ID='Hotel'/>" +
" <owl:Class rdf:ID='Hotel5Stars'>" +
" <rdfs:subClassOf>" +
" <owl:Restriction>" +
" <owl:onProperty rdf:resource='#hasCategory'/>" +
" <owl:hasValue rdf:resource='#Category5'/>" +
" </owl:Restriction>" +
" </rdfs:subClassOf>" +
" </owl:Class>" +
" <owl:DatatypeProperty rdf:ID='hasCategory'>" +
" <rdfs:range rdf:resource='http://www.w3.org/2001/XMLSchema#string'/>" +
" <rdfs:domain rdf:resource='#Hotel'/>" +
" <rdf:type rdf:resource='http://www.w3.org/2002/07/owl#FunctionalProperty'/>" +
" </owl:DatatypeProperty>" +
" <owl:Thing rdf:ID='Category5'/>" +
"</rdf:RDF>";
String NS = "http://iasi.cnr.it/leks/localSchema1
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, null);
m.read(new ByteArrayInputStream( SOURCE.getBytes()), NS );
for (ExtendedIterator j = m.listRestrictions(); j.hasNext(); ) {
Restriction r = (Restriction) j.next();
if (r.isHasValueRestriction()) {
HasValueRestriction hv = r.asHasValueRestriction();
String s = hv.getHasValue().toString();
//System.out.println( s );
}
}
}
/** Bug report from Ole Hjalmar - direct subClassOf not reporting correct result with rule reasoner */
public void xxtest_oh_01() {
String NS = "http:
Resource[] expected = new Resource[] {
ResourceFactory.createResource( NS+"reiseliv.owl#Reiseliv" ),
ResourceFactory.createResource( NS+"hotell.owl#Hotell" ),
ResourceFactory.createResource( NS+"restaurant.owl#Restaurant" ),
ResourceFactory.createResource( NS+"restaurant.owl#UteRestaurant" ),
ResourceFactory.createResource( NS+"restaurant.owl#UteBadRestaurant" ),
ResourceFactory.createResource( NS+"restaurant.owl#UteDoRestaurant" ),
ResourceFactory.createResource( NS+"restaurant.owl#SkogRestaurant" ),
};
test_oh_01scan( OntModelSpec.OWL_MEM, "No inf", expected );
test_oh_01scan( OntModelSpec.OWL_MEM_MINI_RULE_INF, "Mini rule inf", expected );
test_oh_01scan( OntModelSpec.OWL_MEM_RULE_INF, "Full rule inf", expected );
test_oh_01scan( OntModelSpec.OWL_MEM_MICRO_RULE_INF, "Micro rule inf", expected );
}
private void test_oh_01scan( OntModelSpec s, String prompt, Resource[] expected ) {
String NS = "http://www.idi.ntnu.no/~herje/ja/reiseliv.owl
OntModel m = ModelFactory.createOntologyModel(s, null);
m.read( "file:testing/ontology/bugs/test_oh_01.owl");
System.out.println( prompt );
OntClass r = m.getOntClass( NS + "Reiseliv" );
List q = new ArrayList();
Set seen = new HashSet();
q.add( r );
while (!q.isEmpty()) {
OntClass c = (OntClass) q.remove( 0 );
seen.add( c );
for (Iterator i = c.listSubClasses( true ); i.hasNext(); ) {
OntClass sub = (OntClass) i.next();
if (!seen.contains( sub )) {
q.add( sub );
}
}
System.out.println( " Seen class " + c );
}
// check we got all classes
int mask = (1 << expected.length) - 1;
for (int j = 0; j < expected.length; j++) {
if (seen.contains( expected[j] )) {
mask &= ~(1 << j);
}
else {
System.out.println( "Expected but did not see " + expected[j] );
}
}
for (Iterator k = seen.iterator(); k.hasNext(); ) {
Resource res = (Resource) k.next();
boolean isExpected = false;
for (int j = 0; !isExpected && j < expected.length; j++) {
isExpected = expected[j].equals( res );
}
if (!isExpected) {
System.out.println( "Got unexpected result " + res );
}
}
assertEquals( "Some expected results were not seen", 0, mask );
}
/** Test case for SF bug 927641 - list direct subclasses */
public void test_sf_927641() {
String NS = "http://example.org/test
OntModel m0 = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
OntClass c0 = m0.createClass( NS + "C0" );
OntClass c1 = m0.createClass( NS + "C1" );
OntClass c2 = m0.createClass( NS + "C2" );
OntClass c3 = m0.createClass( NS + "C3" );
c0.addSubClass( c1 );
c1.addSubClass( c2 );
c2.addEquivalentClass( c3 );
// now c1 is the direct super-class of c2, even allowing for the equiv with c3
assertFalse( "pass 1: c0 should not be a direct super of c2", c2.hasSuperClass( c0, true ) );
assertFalse( "pass 1: c3 should not be a direct super of c2", c2.hasSuperClass( c3, true ) );
assertFalse( "pass 1: c2 should not be a direct super of c2", c2.hasSuperClass( c2, true ) );
assertTrue( "pass 1: c1 should be a direct super of c2", c2.hasSuperClass( c1, true ) );
// second pass - with inference
m0 = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_RULE_INF );
c0 = m0.createClass( NS + "C0" );
c1 = m0.createClass( NS + "C1" );
c2 = m0.createClass( NS + "C2" );
c3 = m0.createClass( NS + "C3" );
c0.addSubClass( c1 );
c1.addSubClass( c2 );
c2.addEquivalentClass( c3 );
// now c1 is the direct super-class of c2, even allowing for the equiv with c3
assertFalse( "pass 2: c0 should not be a direct super of c2", c2.hasSuperClass( c0, true ) );
assertFalse( "pass 2: c3 should not be a direct super of c2", c2.hasSuperClass( c3, true ) );
assertFalse( "pass 2: c2 should not be a direct super of c2", c2.hasSuperClass( c2, true ) );
assertTrue( "pass 2: c1 should be a direct super of c2", c2.hasSuperClass( c1, true ) );
}
/** Test case for SF bug 934528 - conversion exception with owl:Thing and owl:Nothing when no reasoner */
public void test_sf_934528() {
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
Resource r = (Resource) OWL.Thing.inModel( m );
OntClass thingClass = (OntClass) r.as( OntClass.class );
assertNotNull( thingClass );
r = (Resource) OWL.Nothing.inModel( m );
OntClass nothingClass = (OntClass) r.as( OntClass.class );
assertNotNull( nothingClass );
}
/** Test case for SF bug 937810 - NPE from ModelSpec.getDescription() */
public void test_sf_937810() throws IllegalAccessException {
Field[] specs = OntModelSpec.class.getDeclaredFields();
for (int i = 0; i < specs.length; i++) {
if (Modifier.isPublic( specs[i].getModifiers()) &&
Modifier.isStatic( specs[i].getModifiers()) &&
specs[i].getType().equals( OntModelSpec.class )) {
OntModelSpec s = (OntModelSpec) specs[i].get( null );
assertNotNull( s.getDescription() );
}
}
}
/** Test case for SF bug 940570 - listIndividuals not working with RDFS_INF
*/
public void test_sf_940570() {
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_RDFS_INF );
OntClass C = m.createClass( NS + "C" );
Resource a = m.createResource( NS + "a", C );
TestUtil.assertIteratorValues( this, m.listIndividuals(), new Object[] {a} );
OntModel dm = ModelFactory.createOntologyModel( OntModelSpec.DAML_MEM_RULE_INF );
OntClass D = dm.createClass( NS + "D" );
Resource b = dm.createResource( NS + "b", D );
TestUtil.assertIteratorValues( this, dm.listIndividuals(), new Object[] {b} );
}
/** Test case for SF bug 945436 - a xml:lang='' in the dataset causes sring index exception in getLabel() */
public void test_sf_945436() {
String SOURCE=
"<?xml version='1.0'?>" +
"<!DOCTYPE owl [" +
" <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns
" <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema
" <!ENTITY xsd 'http://www.w3.org/2001/XMLSchema
" <!ENTITY owl 'http://www.w3.org/2002/07/owl
" <!ENTITY dc 'http://purl.org/dc/elements/1.1/' >" +
" <!ENTITY base 'http://jena.hpl.hp.com/test' >" +
" ]>" +
"<rdf:RDF xmlns:owl ='&owl;' xmlns:rdf='&rdf;' xmlns:rdfs='&rdfs;' xmlns:dc='&dc;' xmlns='&base;#' xml:base='&base;'>" +
" <C rdf:ID='x'>" +
" <rdfs:label xml:lang=''>a_label</rdfs:label>" +
" </C>" +
" <owl:Class rdf:ID='C'>" +
" </owl:Class>" +
"</rdf:RDF>";
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
m.read( new StringReader( SOURCE ), null );
Individual x = m.getIndividual( "http://jena.hpl.hp.com/test
assertEquals( "Label on resource x", "a_label", x.getLabel( null) );
assertEquals( "Label on resource x", "a_label", x.getLabel( "" ) );
assertSame( "fr label on resource x", null, x.getLabel( "fr" ) );
}
/** Test case for SF bug 948995 - OWL full should allow inverse functional datatype properties */
public void test_sf_948995() {
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_DL_MEM ); // OWL dl
DatatypeProperty dp = m.createDatatypeProperty( NS + "dp" );
dp.addRDFType( OWL.InverseFunctionalProperty );
boolean ex = false;
try {
dp.as( InverseFunctionalProperty.class );
}
catch (ConversionException e) {
ex = true;
}
assertTrue( "Should have been a conversion exception", ex );
m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM ); // OWL full
dp = m.createDatatypeProperty( NS + "dp" );
dp.addRDFType( OWL.InverseFunctionalProperty );
ex = false;
try {
dp.as( InverseFunctionalProperty.class );
}
catch (ConversionException e) {
ex = true;
}
assertFalse( "Should not have been a conversion exception", ex );
}
/** Test case for SF bug 969475 - the return value for getInverse() on an ObjectProperty should be an object property */
public void test_sf_969475() {
String SOURCE=
"<?xml version='1.0'?>" +
"<!DOCTYPE owl [" +
" <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns
" <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema
" <!ENTITY xsd 'http://www.w3.org/2001/XMLSchema
" <!ENTITY owl 'http://www.w3.org/2002/07/owl
" <!ENTITY dc 'http://purl.org/dc/elements/1.1/' >" +
" <!ENTITY base 'http://jena.hpl.hp.com/test' >" +
" ]>" +
"<rdf:RDF xmlns:owl ='&owl;' xmlns:rdf='&rdf;' xmlns:rdfs='&rdfs;' xmlns:dc='&dc;' xmlns='&base;#' xml:base='&base;'>" +
" <owl:ObjectProperty rdf:ID='p0'>" +
" <owl:inverseOf>" +
" <owl:ObjectProperty rdf:ID='q0' />" +
" </owl:inverseOf>" +
" </owl:ObjectProperty>" +
" <owl:ObjectProperty rdf:ID='p1'>" +
" <owl:inverseOf>" +
" <owl:ObjectProperty rdf:ID='q1' />" +
" </owl:inverseOf>" +
" </owl:ObjectProperty>" +
"</rdf:RDF>";
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
m.read( new StringReader( SOURCE ), null );
ObjectProperty p0 = m.getObjectProperty( "http://jena.hpl.hp.com/test
Object invP0 = p0.getInverseOf();
assertEquals( m.getResource( "http://jena.hpl.hp.com/test#q0"), invP0 );
assertTrue( "Should be an ObjectProperty facet", invP0 instanceof ObjectProperty );
ObjectProperty q1 = m.getObjectProperty( "http://jena.hpl.hp.com/test
Object invQ1 = q1.getInverse();
assertEquals( m.getResource( "http://jena.hpl.hp.com/test#p1"), invQ1 );
assertTrue( "Should be an ObjectProperty facet", invQ1 instanceof ObjectProperty );
}
/** Test case for SF bug 978259 - missing supports() checks in OWL DL and Lite profiles */
public void test_sf_978259() {
OntModel md = ModelFactory.createOntologyModel( OntModelSpec.OWL_DL_MEM );
OntModel ml = ModelFactory.createOntologyModel( OntModelSpec.OWL_LITE_MEM );
DataRange drd = md.createDataRange( md.createList( new Resource[] {OWL.Thing}) );
assertNotNull( drd );
HasValueRestriction hvrd = md.createHasValueRestriction( null, RDFS.seeAlso, OWL.Thing );
assertNotNull( hvrd );
}
/** Test case from Robert N Gonzalez [mailto:rngonzal@us.ibm.com] via jena-dev: exception while checking an ontology that imports a URN */
public void test_rng_01() {
String SOURCE=
"<?xml version='1.0'?>" +
"<!DOCTYPE owl [" +
" <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns
" <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema
" <!ENTITY xsd 'http://www.w3.org/2001/XMLSchema
" <!ENTITY owl 'http://www.w3.org/2002/07/owl
" <!ENTITY dc 'http://purl.org/dc/elements/1.1/' >" +
" <!ENTITY base 'http://jena.hpl.hp.com/test' >" +
" ]>" +
"<rdf:RDF xmlns:owl ='&owl;' xmlns:rdf='&rdf;' xmlns:rdfs='&rdfs;' xmlns:dc='&dc;' xmlns='&base;#' xml:base='&base;'>" +
" <owl:Ontology rdf:about='urn:someURN:'> " +
" <owl:imports>" +
" <owl:Ontology rdf:about='urn:ALegalURN:' />" +
" </owl:imports>" +
" </owl:Ontology>" +
"</rdf:RDF>";
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
m.getDocumentManager()
.addAltEntry( "urn:ALegalURN:", "file:testing/ontology/bugs/test_hk_07B.owl" );
m.getDocumentManager().setProcessImports( false );
m.read( new StringReader( SOURCE ), null );
List problems = new ArrayList();
Resource level = m.getOWLLanguageLevel( problems );
//System.out.println( "level = " + level );
for (Iterator i = problems.iterator(); i.hasNext(); ) {
SyntaxProblem sp = (SyntaxProblem) i.next();
//System.out.println( "problem = " + sp.longDescription() );
}
}
// Internal implementation methods
private int getStatementCount(OntModel ontModel) {
int count = 0;
for (Iterator it = ontModel.listStatements(); it.hasNext(); it.next()) {
count++;
}
return count;
}
// Inner class definitions
class MockTransactionHandler extends SimpleTransactionHandler {
boolean m_inTransaction = false;
boolean m_aborted = false;
boolean m_committed = false;
public void begin() {
m_inTransaction = true;
}
public void abort() {
m_inTransaction = false;
m_aborted = true;
}
public void commit() {
m_inTransaction = false;
m_committed = true;
}
}
}
|
package com.gabmus.co2photoeditor;
import android.app.AlertDialog;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.EGLConfig;
public class FilterRenderer implements GLSurfaceView.Renderer
{
private int hShaderProgramBase;
private int hShaderProgramFinalPass;
private int hShaderProgramBlackAndWhite;
private int hShaderProgramSepia;
public boolean PARAMS_EnableBlackAndWhite = false;
public boolean PARAMS_EnableSepia = false;
public boolean BOOL_LoadTexture = false;
public RenderTarget2D target1, target2;
private FilterSurfaceView fsv;
private FloatBuffer VB;
private ShortBuffer IB;
private FloatBuffer TC;
public int[] hToFilterTexture;
public FilterRenderer(FilterSurfaceView fsv_) { fsv = fsv_;}
public void onSurfaceCreated(GL10 unused, EGLConfig config)
{
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
float[] vertices = new float[]
{
-1f, 1f, 0.0f,
-1f, -1f, 0.0f,
1f, -1f, 0.0f,
1f, 1f, 0.0f,
-1f, 1f, 0.0f,
1f, -1f, 0.0f
};
short[] indices = new short[]
{
0, 1, 2, 0, 2, 3
};
float[] texCoords =
{
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
1.0f, 1.0f
};
ByteBuffer bVB = ByteBuffer.allocateDirect(vertices.length * 4); bVB.order(ByteOrder.nativeOrder());
ByteBuffer bIB = ByteBuffer.allocateDirect(indices.length * 2); bIB.order(ByteOrder.nativeOrder());
ByteBuffer bTC = ByteBuffer.allocateDirect(texCoords.length * 4); bTC.order(ByteOrder.nativeOrder());
VB = bVB.asFloatBuffer();
IB = bIB.asShortBuffer();
TC = bTC.asFloatBuffer();
VB.put(vertices); VB.position(0);
IB.put(indices); IB.position(0);
TC.put(texCoords); TC.position(0);
loadShaders();
fsv.LoadTexture(fsv.generateTestBitmap());
}
private String generalVS =
"attribute vec4 vPosition;" +
"attribute vec2 texCoords;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" gl_Position = vPosition;" +
" UV = texCoords;" +
"}";
private String generalreverseVS =
"attribute vec4 vPosition;" +
"attribute vec2 texCoords;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" gl_Position = vPosition;" +
" vec2 tc = vec2(1, 1) - texCoords;" +
" tc.x = texCoords.x;" +
" UV = tc;" +
"}";
private void loadShaders()
{
//BASE SHADER
String baseshader_FS =
"precision mediump float;" +
"varying vec2 UV;" +
"void main() {" +
" gl_FragColor = vec4(UV.x, UV.y, 0, 1);" +
"}";
hShaderProgramBase = createprogram(baseshader_FS);
//Black & White
String bandw_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" vec4 col = texture2D(filteredPhoto, UV);" +
" float gravg = (col.r + col.g + col.b) / 3.0f;" +
" gl_FragColor = vec4(gravg, gravg, gravg, 1);" +
"}";
hShaderProgramBlackAndWhite = createprogram(generalreverseVS, bandw_FS);
//Sepia
String sepia_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" vec4 color = texture2D(filteredPhoto, UV);" +
" gl_FragColor.r = dot(color, vec3(.393, .769, .189));" +
" gl_FragColor.g = dot(color, vec3(.349, .686, .168));" +
" gl_FragColor.b = dot(color, vec3(.272, .534, .131));" +
" gl_FragColor.a = 1;" +
"}";
//hShaderProgramSepia = createprogram(generalreverseVS, sepia_FS);
//FINALPASS
String finalPass_FS =
"precision mediump float;" +
"uniform sampler2D filteredPhoto;" +
"varying vec2 UV;" +
"void main() {" +
" gl_FragColor = texture2D(filteredPhoto, UV);" +
"}";
hShaderProgramFinalPass = createprogram(finalPass_FS);
}
private int createprogram(String fssource) { return createprogram(generalVS, fssource);}
private int createprogram(String vssource, String fssource)
{
int toRet;
toRet = GLES20.glCreateProgram();
GLES20.glAttachShader(toRet, compileshader(GLES20.GL_VERTEX_SHADER, vssource));
GLES20.glAttachShader(toRet, compileshader(GLES20.GL_FRAGMENT_SHADER, fssource));
GLES20.glLinkProgram(toRet);
return toRet;
}
String ERROR = "";
private int compileshader(int type, String shaderCode)
{
int shader = GLES20.glCreateShader(type);
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
ERROR = GLES20.glGetShaderInfoLog(shader);
if (ERROR.length() > 0)
throw(new RuntimeException(ERROR));
return shader;
}
private int hPos, hTex;
public void onDrawFrame(GL10 unused) {
if (BOOL_LoadTexture) {
if (fsv.toLoad != null)
fsv.LoadTexture(fsv.toLoad);
BOOL_LoadTexture =false;
}
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
if (PARAMS_EnableBlackAndWhite)
{
SetRenderTarget();
GLES20.glUseProgram(hShaderProgramBlackAndWhite);
setVSParams(hShaderProgramBlackAndWhite);
setShaderParamPhoto(hShaderProgramBlackAndWhite, GetCurTexture());
drawquad();
}
if (PARAMS_EnableSepia)
{
SetRenderTarget();
GLES20.glUseProgram(hShaderProgramSepia);
setVSParams(hShaderProgramSepia);
setShaderParamPhoto(hShaderProgramSepia, GetCurTexture());
drawquad();
}
if (didshit)
firstshit= false;
RenderTarget2D.SetDefault(fsv.getWidth(), fsv.getHeight());
GLES20.glUseProgram(hShaderProgramFinalPass);
setVSParams(hShaderProgramFinalPass);
int tx = GetCurTexture();
setShaderParamPhoto(hShaderProgramFinalPass, tx);
drawquad();
didshit = false;
firstshit = true;
}
private void setShaderParamPhoto(int program, int texID)
{
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID);
int loc = GLES20.glGetUniformLocation(program, "filteredPhoto");
if (loc == -1) throw(new RuntimeException("SHEEEET"));
GLES20.glUniform1i(loc, 0);
}
boolean first = true;
boolean didshit = false;
boolean firstshit = true;
private void SetRenderTarget()
{
if (didshit) firstshit = false;
didshit = true;
if (first)
{
target1.Set();
first = false;
}
else
{
target2.Set();
first = true;
}
}
private int GetCurTexture()
{
if (firstshit) return hToFilterTexture[0];
if (first) return target2.GetTex();
else return target1.GetTex();
}
private void drawquad(){ GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);
GLES20.glDisableVertexAttribArray(hPos);
GLES20.glDisableVertexAttribArray(hTex);}
private void setVSParams(int program){setVSParamspos(program); setVSParamstc(program);}
private void setVSParamspos(int program) {
hPos = GLES20.glGetAttribLocation(program, "vPosition");
GLES20.glEnableVertexAttribArray(hPos);
GLES20.glVertexAttribPointer(hPos, 3,
GLES20.GL_FLOAT, false,
12, VB);
}
private void setVSParamstc(int program) {
hTex = GLES20.glGetAttribLocation(program, "texCoords");
GLES20.glEnableVertexAttribArray(hTex);
GLES20.glVertexAttribPointer(hTex, 2,
GLES20.GL_FLOAT, false,
8, TC);
}
public void onSurfaceChanged(GL10 unused, int width, int height)
{
GLES20.glViewport(0, 0, width, height);
}
}
|
package com.jcwhatever.bukkit.arborianquests.quests;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.jcwhatever.bukkit.arborianquests.ArborianQuests;
import com.jcwhatever.bukkit.arborianquests.quests.QuestStatus.CurrentQuestStatus;
import com.jcwhatever.nucleus.mixins.IHierarchyNode;
import com.jcwhatever.nucleus.mixins.INamed;
import com.jcwhatever.nucleus.storage.DataBatchOperation;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.utils.CollectionUtils;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.text.TextUtils;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
/**
* Represents a quest and players within the quest.
*/
public abstract class Quest implements INamed, IHierarchyNode<Quest> {
private static Multimap<UUID, Quest> _playerQuests =
MultimapBuilder.hashKeys(100).hashSetValues().build();
private final String _questName;
private String _displayName;
private final IDataNode _dataNode;
private final IDataNode _playerNode;
private final IDataNode _questNode;
private final Map<String, Quest> _subQuests = new HashMap<>(5);
/**
* Get an unmodifiable {@code Set} of {@code Quest}'s that
* the player is in
* .
* @param p The player.
*/
public static Set<Quest> getPlayerQuests(Player p) {
return CollectionUtils.unmodifiableSet(_playerQuests.get(p.getUniqueId()));
}
@Nullable
public static Quest getQuestFromPath(String questPath) {
PreCon.notNull(questPath, "questPath");
String[] pathComponents = TextUtils.PATTERN_DOT.split(questPath);
Quest quest = ArborianQuests.getQuestManager().getPrimary(pathComponents[0]);
if (quest == null)
return null;
for (int i=1; i < pathComponents.length; i++) {
quest = quest.getQuest(pathComponents[i]);
if (quest == null)
return null;
}
return quest;
}
/**
* Constructor.
*
* @param questName The name of the quest.
* @param displayName The quest display name.
* @param dataNode The quest data node.
*/
public Quest(String questName, String displayName, IDataNode dataNode) {
PreCon.notNullOrEmpty(questName);
PreCon.notNullOrEmpty(displayName);
PreCon.notNull(dataNode);
_questName = questName;
_displayName = displayName;
_dataNode = dataNode;
_playerNode = dataNode.getNode("players");
_questNode = dataNode.getNode("quests");
}
/**
* Get the quests data node name.
*/
@Override
public String getName() {
return _questName;
}
public String getPathName() {
return _questName;
}
/**
* Get the quests display name.
*/
public String getDisplayName() {
return _displayName;
}
/**
* Set the quests display name.
*
* @param displayName The display name.
*/
public void setDisplayName(String displayName) {
_displayName = displayName;
}
/**
* Get the current assignment description. This
* is used to explain what the player needs to
* do in order to complete their current objective.
*/
@Nullable
public String getAssignment() {
return _dataNode.getString("assignment");
}
/**
* Set the current assignment description.
*
* @param assignment The assignment description.
*/
public void setAssignment(@Nullable String assignment) {
_dataNode.set("assignment", assignment);
}
/**
* Get a sub quest of the quest by name.
*
* @param questName The name of the sub quest.
*/
@Nullable
public Quest getQuest(String questName) {
PreCon.notNullOrEmpty(questName);
return _subQuests.get(questName.toLowerCase());
}
/**
* Get all sub quests.
*/
public List<Quest> getQuests() {
return new ArrayList<>(_subQuests.values());
}
/**
* Get or create a sub quest of the quest.
*
* @param questName The quest name.
* @param displayName The quest display name.
*/
public Quest createQuest(String questName, String displayName) {
PreCon.notNullOrEmpty(questName);
PreCon.notNullOrEmpty(displayName);
questName = questName.toLowerCase();
Quest quest = _subQuests.get(questName);
if (quest != null) {
quest.setDisplayName(displayName);
return quest;
}
IDataNode node = _dataNode.getNode("quests." + questName);
quest = new SubQuest(this, questName, displayName, node);
node.set("display", displayName);
node.saveAsync(null);
_subQuests.put(questName, quest);
return quest;
}
public boolean removeQuest(String questName) {
PreCon.notNullOrEmpty(questName);
questName = questName.toLowerCase();
Quest quest = _subQuests.remove(questName);
if (quest == null)
return false;
IDataNode node = _dataNode.getNode("quests." + questName);
node.remove();
node.saveAsync(null);
return true;
}
/**
* Get a players current status in the quest.
*
* @param p The player to check.
*/
public QuestStatus getStatus(Player p) {
//noinspection ConstantConditions
return getStatus(p.getUniqueId());
}
/**
* Get a players current status in the quest.
*
* @param playerId The id of the player to check.
*/
public QuestStatus getStatus(UUID playerId) {
//noinspection ConstantConditions
return _playerNode.getEnum(playerId.toString() + ".status", QuestStatus.NONE, QuestStatus.class);
}
/**
* Accept the player into the quest.
*
* @param p The player to accept.
*/
public void accept(Player p) {
accept(p.getUniqueId());
}
/**
* Accept the player into the quest.
*
* @param playerId The id of the player.
*/
public void accept(UUID playerId) {
QuestStatus status = getStatus(playerId);
switch (status) {
case NONE:
setStatus(playerId, QuestStatus.INCOMPLETE);
break;
case COMPLETED:
setStatus(playerId, QuestStatus.RERUN);
break;
case INCOMPLETE:
// fall through
case RERUN:
// do nothing
break;
}
}
/**
* Flag a player as having completed the quest.
*
* @param p The player to flag.
*/
public void finish(Player p) {
finish(p.getUniqueId());
}
/**
* Flag a player as having completed the quest.
*
* @param playerId The id of the player to flag.
*/
public void finish(UUID playerId) {
QuestStatus status = getStatus(playerId);
switch (status) {
case RERUN:
setStatus(playerId, QuestStatus.COMPLETED);
break;
case INCOMPLETE:
setStatus(playerId, QuestStatus.NONE);
break;
case NONE:
// fall through
case COMPLETED:
break;
}
}
/**
* Cancel the quest for a player.
*
* @param p The player.
*/
public void cancel(Player p) {
cancel(p.getUniqueId());
}
/**
* Cancel the quest for a player.
*
* @param playerId The id of the player.
*/
public void cancel(UUID playerId) {
QuestStatus status = getStatus(playerId);
switch (status) {
case RERUN:
// fall through
case COMPLETED:
setStatus(playerId, QuestStatus.COMPLETED);
break;
case NONE:
// fall through
case INCOMPLETE:
setStatus(playerId, QuestStatus.NONE);
break;
}
}
/**
* Determine if a player has a flag set.
*
* @param playerId The ID of the player to check
* @param flagName The name of the flag
*
* @return True if the flag is set.
*/
public boolean hasFlag(UUID playerId, String flagName) {
PreCon.notNull(playerId);
PreCon.notNullOrEmpty(flagName);
return _playerNode.getBoolean(playerId.toString() + ".flags." + flagName, false);
}
/**
* Set a flag on a player.
*
* @param playerId The players ID.
* @param flagName The name of the flag.
*/
public void setFlag(UUID playerId, String flagName) {
PreCon.notNull(playerId);
PreCon.notNullOrEmpty(flagName);
_playerNode.set(playerId.toString() + ".flags." + flagName, true);
_playerNode.saveAsync(null);
}
/**
* Clear a flag on a player.
*
* @param playerId The players ID.
* @param flagName The name of the flag.
*/
public void clearFlag(UUID playerId, String flagName) {
PreCon.notNull(playerId);
PreCon.notNullOrEmpty(flagName);
_playerNode.remove(playerId.toString() + ".flags." + flagName);
_playerNode.saveAsync(null);
}
/**
* Clear all flags set on a player.
*
* @param playerId The ID of the player.
*/
public void clearFlags(final UUID playerId) {
PreCon.notNull(playerId);
cancel(playerId);
_playerNode.runBatchOperation(new DataBatchOperation() {
@Override
public void run(IDataNode dataNode) {
_playerNode.remove(playerId.toString() + ".flags");
_playerNode.saveAsync(null);
for (Quest quest : _subQuests.values()) {
quest.clearFlags(playerId);
quest.setStatus(playerId, QuestStatus.NONE);
}
}
});
}
/**
* Get the flags set on a player.
*
* @param playerId The unique ID of the player.
*/
public Set<String> getFlags(UUID playerId) {
PreCon.notNull(playerId);
IDataNode flagNode = _playerNode.getNode(playerId.toString() + ".flags");
Set<String> flagNames = flagNode.getSubNodeNames();
return CollectionUtils.unmodifiableSet(flagNames);
}
// Set the quest status of a player
private void setStatus(UUID playerId, QuestStatus status) {
if (status == QuestStatus.NONE) {
_playerNode.remove(playerId.toString() + ".status");
}
else {
_playerNode.set(playerId.toString() + ".status", status);
}
if (status.getCurrentStatus() == CurrentQuestStatus.NONE) {
_playerQuests.remove(playerId, this);
}
else if (status.getCurrentStatus() == CurrentQuestStatus.IN_PROGRESS) {
_playerQuests.put(playerId, this);
}
_playerNode.saveAsync(null);
}
// initial settings load
private void loadSettings() {
// load players
Set<String> rawPlayerIds = _playerNode.getSubNodeNames();
for (String rawId : rawPlayerIds) {
UUID id = TextUtils.parseUUID(rawId);
if (id == null)
continue;
QuestStatus status = _playerNode.getEnum(rawId, QuestStatus.NONE, QuestStatus.class);
//noinspection ConstantConditions
if (status.getCurrentStatus() != CurrentQuestStatus.IN_PROGRESS)
continue;
_playerQuests.put(id, this);
}
// load sub quests
Set<String> questNames = _questNode.getSubNodeNames();
for (String questName : questNames) {
IDataNode node = _questNode.getNode(questName);
String displayName = node.getString("display", questName);
if (displayName == null)
throw new AssertionError();
SubQuest quest = new SubQuest(this, questName, displayName, node);
_subQuests.put(questName.toLowerCase(), quest);
}
}
}
|
package model;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import location.ToroidalLocation;
import state.AntState;
import cell.AntCell;
import grid.SquareGrid;
import gui.CellSocietyGUI;
public class AntModel extends AbstractModel{
private double myEvaporationRate = 0.25; //default value
private double myDiffusionRate = 0.25; //default value
private static final int EMPTY_STATE = 0;
private static final int NEST_STATE = 1;
private static final int FOOD_SOURCE_STATE = 2;
private static final int HOME_PHEROMONE_STATE = 3;
private static final int FOOD_PHEROMONE_STATE = 4;
private static final int ANT_STATE = 5;
AntModel(CellSocietyGUI CSGUI) {
super(CSGUI);
}
@Override
public void setParameters(Map<String,String> parameters){
super.setParameters(parameters);
}
@Override
protected void setBasicConfig(java.util.Map<String,String> parameters) {
super.setBasicConfig(parameters);
if(parameters.containsKey("evapRate")){
double tmp = Double.parseDouble(parameters.get("evapRate"));
myEvaporationRate = (tmp<=1 && tmp>=0)?tmp:myEvaporationRate;
}
if(parameters.containsKey("diffusionRate")){
double tmp = Double.parseDouble(parameters.get("diffusionRate"));
myDiffusionRate = (tmp<=1 && tmp>=0)?tmp:myDiffusionRate;
}
Map<Integer,String> map = new HashMap<>();
map.put(EMPTY_STATE, "Empty");
map.put(NEST_STATE, "Nest");
map.put(FOOD_SOURCE_STATE, "Food");
map.put(HOME_PHEROMONE_STATE, "Home Pheromone");
map.put(FOOD_PHEROMONE_STATE, "Food Pheromone");
map.put(ANT_STATE, "Ant");
setupGraph(map);
};
@Override
public void initialize(Map<String, String> parameters, List<Map<String, String>> cells) {
setBasicConfig(parameters);
cells.forEach(map -> {
int x = Integer.parseInt(map.get("x"));
int y = Integer.parseInt(map.get("y"));
int state = Integer.parseInt(map.get("state"));
addCell(x,y,state);
});
if(myCells.size()<getWidth()*getHeight())
System.err.println("Missing Cell Info!");
myGrid = new SquareGrid(getWidth(), getHeight(), myCells);
myGrid.setNeighbors();
}
@Override
public void initialize(Map<String, String> parameters) {
setBasicConfig(parameters);
int mat[][] = new int[getWidth()][getHeight()];
int total = getWidth()*getHeight();
double pA = 0.1;
if(myParameters.containsKey("percentAnts")){
double tmp = Double.parseDouble(myParameters.get("percentAnts"));
pA = (tmp>=0 && tmp<=1)?tmp:pA;
}
int numAnts = (int)(total*pA);
double percentNestWidth = 0.3;
int nestWidth = (int) (getWidth()*percentNestWidth);
for(int i=0;i<mat.length;i++){
Arrays.fill(mat[i], EMPTY_STATE);
}
int t = myRandom.nextInt(total);
int x = t % getWidth(), y = t / getWidth();
System.out.println(x + " hi");
if(mat[x][y]==EMPTY_STATE){
mat[x][y] = NEST_STATE;
}
int i=0;
while(i < numAnts){
for(int p=0; p<=nestWidth; p++){
if ((x+p) < getWidth()){
if(mat[x+p][y]==EMPTY_STATE){
mat[x+p][y] = NEST_STATE;
i++;
}
} else {
break;
}
}
x = t % getWidth();
if (y < getHeight()-1){y++;}
else{ break;}
}
double percentFood = 0.1;
int numFood = (int) (total*percentFood);
int j = 0;
while(j < numFood){
int t1 = myRandom.nextInt(total);
int x1 = t1 % getWidth(), y1 = t1 / getWidth();
if(mat[x1][y1]==EMPTY_STATE){
mat[x1][y1] = FOOD_SOURCE_STATE;
j++;
}
}
for (int x1 = 0; x1 < mat.length; x1++)
for (int y1 = 0; y1 < mat[x1].length; y1++)
addCell(x1,y1,mat[x1][y1]);
myGrid = new SquareGrid(getWidth(), getHeight(), myCells);
myGrid.setNeighbors();
}
private void addCell(int x,int y,int state){
AntCell cell = new AntCell(new AntState(state), new ToroidalLocation(x,y, myWidth, getHeight()), myCSGUI);
cell.setParameters(myEvaporationRate, myDiffusionRate);
myCells.add(cell);
}
@Override
protected Map<Integer, Double> getDataPoints() {
int[] states = new int[6];
myCells.forEach(cell->{states[cell.getState().getStateInt()]++;});
Map<Integer, Double> stateMap = new HashMap<>();
stateMap.put(EMPTY_STATE, (double)states[EMPTY_STATE]);
stateMap.put(NEST_STATE, (double)states[NEST_STATE]);
stateMap.put(FOOD_SOURCE_STATE, (double)states[FOOD_SOURCE_STATE]);
stateMap.put(HOME_PHEROMONE_STATE, (double)states[HOME_PHEROMONE_STATE]);
stateMap.put(FOOD_PHEROMONE_STATE, (double)states[FOOD_PHEROMONE_STATE]);
stateMap.put(ANT_STATE, (double)states[ANT_STATE]);
return stateMap;
}
}
|
package com.mambu.ant.order.model;
/**
* Pojo class used for posting order requests
*
* @author aifrim.
*/
public class RequestCreateOrderModel {
/**
* Mandatory. Name of the LSP(translations provider) that should process this order. Can be one of gengo, textmaster.
*/
private String lsp;
/**
* Mandatory. Source locale for the order. Can be the name or public id of the source locale. Preferred is the public id.
*/
private String source_locale_id;
/**
* Mandatory. List of target locales you want the source content translate to. Can be the name or public id of the target locales. Preferred is the public id.
*/
private String[] target_locale_ids;
/**
* Mandatory. Name of the quality level, availability depends on the LSP. Can be one of: standard, pro (for orders processed by Gengo) and one of regular, premium, enterprise (for orders processed by TextMaster)
*/
private String translation_type;
/**
* Optional. Style guide for translators to be sent with the order.
*/
private String styleguide_id;
/**
* Optional. Message that is displayed to the translators for description.
*/
private String message;
/**
* Optional(Default: true). Order translations for keys with untranslated content in the selected target locales.
*/
private Boolean include_untranslated_keys;
/**
* Optional(Default: false). Order translations for keys with unverified content in the selected target locales. Default: false
*/
private Boolean include_unverified_translations;
private String category ;//Banking/Financial Services/Insurance
protected RequestCreateOrderModel(){}
private RequestCreateOrderModel(Builder builder) {
lsp = builder.lsp;
source_locale_id = builder.source_locale_id;
target_locale_ids = builder.target_locale_ids;
translation_type = builder.translation_type;
styleguide_id = builder.styleguide_id;
message = builder.message;
include_untranslated_keys = builder.include_untranslated_keys;
include_unverified_translations = builder.include_unverified_translations;
category = builder.category;
}
public static final class Builder {
private String lsp;
private String source_locale_id;
private String[] target_locale_ids;
private String translation_type;
private String styleguide_id;
private String message;
private Boolean include_untranslated_keys = true;
private Boolean include_unverified_translations = false;
private String category;
private Builder() {
}
public Builder lsp(String val) {
lsp = val;
return this;
}
public Builder source_locale_id(String val) {
source_locale_id = val;
return this;
}
public Builder target_locale_ids(String[] val) {
target_locale_ids = val;
return this;
}
public Builder translation_type(String val) {
translation_type = val;
return this;
}
public Builder styleguide_id(String val) {
styleguide_id = val;
return this;
}
public Builder message(String val) {
message = val;
return this;
}
public Builder include_untranslated_keys(Boolean val) {
include_untranslated_keys = val;
return this;
}
public Builder include_unverified_translations(Boolean val) {
include_unverified_translations = val;
return this;
}
public Builder category(String val) {
category = val;
return this;
}
public RequestCreateOrderModel build() {
return new RequestCreateOrderModel(this);
}
}
public static Builder newBuilder() {
return new Builder();
}
}
|
package com.marzhillstudios.quizme;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.marzhillstudios.quizme.data.Card;
import com.marzhillstudios.quizme.data.CardDatabase;
import com.marzhillstudios.quizme.util.L;
/**
* Custom activity class for creating new cards.
*
* @author Jeremy Wall <jeremy@marzhillstudios.com>
*
*/
// TODO(jwall): unit tests for this class.
// TODO(jwall): should this activity implement some sendTo intents?
// TODO(jwall): Audio card sides?
public class NewCardCreatorActivity extends Activity {
private CardDatabase db;
public static final int REQUEST_SIDE1_IMAGE_RESULT = 1;
public static final int REQUEST_SIDE1_TEXT_RESULT = 2;
public static final int REQUEST_SIDE2_IMAGE_RESULT = 3;
public static final int REQUEST_SIDE2_TEXT_RESULT = 4;
public static final String CARD_INTENT_KEY = "card_for_update";
private Button side1ImageBtn;
private Button side1TextBtn;
private Button side2ImageBtn;
private Button side2TextBtn;
private EditText titleTextBox;
private Card card;
private String fileNamePrefix;
private String side1Text;
private String side2Text;
private Uri imageUriSide2;
private Uri imageUriSide1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_card_dialog);
db = new CardDatabase(this);
final Activity mainContext = this;
Intent intention = getIntent();
titleTextBox =
(EditText) findViewById(R.id.NewCardTitleEditable);
side1ImageBtn =
(Button) findViewById(R.id.NewCardSide1ImageBtn);
side1TextBtn =
(Button) mainContext.findViewById(R.id.NewCardSide1TextBtn);
side2ImageBtn =
(Button) mainContext.findViewById(R.id.NewCardSide2ImageBtn);
side2TextBtn =
(Button) mainContext.findViewById(R.id.NewCardSide2TextBtn);
Resources res = getResources();
side1Text = res.getString(R.string.Side1Text);
side2Text = res.getString(R.string.Side2Text);
if (intention.hasExtra(CARD_INTENT_KEY)) {
// we are editing a card
Long id = intention.getExtras().getLong(CARD_INTENT_KEY);
L.d("NewCardCreatorActivity onCreate", "Retrieving Card with id %d", id);
card = db.getCard(intention.getExtras().getLong(CARD_INTENT_KEY));
fileNamePrefix = String.format("card_%d_", card.getId());
} else {
// new card
card = new Card(
res.getString(R.string.NewCardDialogTitleDefault), side1Text, side2Text);
fileNamePrefix = String.format("card_%d_", db.getNextCardId());
}
titleTextBox.setText(card.getTitle());
imageUriSide1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileNamePrefix + "side1.png"));
OnClickListener side1ImageBtnListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUriSide1);
L.i("onClick side1ImageBtnListener", "image uri: %s", imageUriSide1.toString());
mainContext.startActivityForResult(intent,
REQUEST_SIDE1_IMAGE_RESULT);
}
};
side1ImageBtn.setOnClickListener(side1ImageBtnListener);
OnClickListener side1TextBtnListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mainContext, TextCardEditActivity.class);
intent.putExtra(TextCardEditActivity.EXTRA_KEY, card.side1);
intent.setType("text/plain");
L.d("NewCardCreatorAtvivtyService side1TextBtnListener",
"Launching the Text editing service.");
mainContext.startActivityForResult(
intent, REQUEST_SIDE1_TEXT_RESULT);
}
};
side1TextBtn.setOnClickListener(side1TextBtnListener);
imageUriSide2 = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileNamePrefix + "side2.png"));
OnClickListener side2ImageBtnListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUriSide2);
L.i("onClick side2ImageBtnListener", "image uri: %s", imageUriSide2.toString());
mainContext.startActivityForResult(intent,
REQUEST_SIDE2_IMAGE_RESULT);
}
};
side2ImageBtn.setOnClickListener(side2ImageBtnListener);
OnClickListener side2TextBtnListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mainContext, TextCardEditActivity.class);
intent.putExtra(TextCardEditActivity.EXTRA_KEY, card.side2);
intent.setType("text/plain");
L.d("NewCardCreatorAtvivtyService side2TextBtnListener",
"Launching the Text editing service.");
mainContext.startActivityForResult(
intent, REQUEST_SIDE2_TEXT_RESULT);
}
};
side2TextBtn.setOnClickListener(side2TextBtnListener);
}
public CardDatabase getDb() { return db; }
public void onActivityResult(int requestCode, int resultCode, Intent data) {
L.d("NewCardCreatorActivity onActivityResult",
"Recieved result from an activity resultCode: %d, requestCode %d",
resultCode, requestCode);
switch(requestCode) {
// TODO(jwall): the following is now testable so go write some :-)
case REQUEST_SIDE1_IMAGE_RESULT:
card.setSide1Type(Card.IMAGE_TYPE);
card.side1 = imageUriSide1.toString();
L.d("NewCardCreatorActivity onActivityResult",
"Recieved image result for side 1 image: %s", card.side1);
break;
case REQUEST_SIDE2_IMAGE_RESULT:
card.setSide2Type(Card.IMAGE_TYPE);
card.side2 = imageUriSide2.toString();
L.d("NewCardCreatorActivity onActivityResult",
"Recieved image result for side 2 %s", card.side2);
break;
case REQUEST_SIDE1_TEXT_RESULT:
card.setSide1Type(Card.TEXT_TYPE);
if (data != null && data.hasExtra(TextCardEditActivity.EXTRA_KEY)) {
card.side1 = data.getExtras().getString(TextCardEditActivity.EXTRA_KEY);
}
L.d("NewCardCreatorActivity onActivityResult",
"Recieved text result for side 1 %s", card.side1);
break;
case REQUEST_SIDE2_TEXT_RESULT:
card.setSide2Type(Card.TEXT_TYPE);
if (data != null && data.hasExtra(TextCardEditActivity.EXTRA_KEY)) {
card.side2 = data.getExtras().getString(TextCardEditActivity.EXTRA_KEY);
}
L.d("NewCardCreatorActivity onActivityResult",
"Recieved text result for side 2 %s", card.side2);
break;
}
}
@Override
public void onPause() {
super.onPause();
card.setTitle(titleTextBox.getText().toString());
Long id = db.upsertCard(card);
card.setId(id);
db.close();
}
}
|
package de.pinyto.passwordgenerator;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private boolean isGenerated = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBar seekBarLength = (SeekBar) findViewById(R.id.seekBarLength);
seekBarLength.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView textViewLengthDisplay =
(TextView) findViewById(R.id.textViewLengthDisplay);
textViewLengthDisplay.setText(Integer.toString(progress + 4));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Button generateButton = (Button) findViewById(R.id.generatorButton);
generateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText editTextDomain =
(EditText) findViewById(R.id.editTextDomain);
EditText editTextMasterPassword =
(EditText) findViewById(R.id.editTextMasterPassword);
PasswordGenerator generator = new PasswordGenerator();
generator.initialize(
editTextDomain.getText().toString(),
editTextMasterPassword.getText().toString());
generator.hash(1);
CheckBox checkBoxSpecialCharacters =
(CheckBox) findViewById(R.id.checkBoxSpecialCharacter);
CheckBox checkBoxLetters =
(CheckBox) findViewById(R.id.checkBoxLetters);
CheckBox checkBoxNumbers =
(CheckBox) findViewById(R.id.checkBoxNumbers);
SeekBar seekBarLength =
(SeekBar) findViewById(R.id.seekBarLength);
String password = generator.getPassword(
checkBoxSpecialCharacters.isChecked(),
checkBoxLetters.isChecked(),
checkBoxNumbers.isChecked(),
seekBarLength.getProgress() + 4);
TextView textViewPassword = (TextView) findViewById(R.id.textViewPassword);
textViewPassword.setText(password);
isGenerated = true;
invalidateOptionsMenu();
}
});
TextWatcher changeEditTextListener = new TextWatcher(){
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
public void afterTextChanged(Editable editable) {
isGenerated = false;
invalidateOptionsMenu();
TextView textViewPassword = (TextView) findViewById(R.id.textViewPassword);
textViewPassword.setText("");
}
};
EditText editTextDomain =
(EditText) findViewById(R.id.editTextDomain);
editTextDomain.addTextChangedListener(changeEditTextListener);
EditText editTextMasterPassword =
(EditText) findViewById(R.id.editTextMasterPassword);
editTextMasterPassword.addTextChangedListener(changeEditTextListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main_actions, menu);
MenuItem copyItem = menu.findItem(R.id.action_copy);
copyItem.setVisible(isGenerated);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_copy) {
TextView textViewPassword = (TextView) findViewById(R.id.textViewPassword);
ClipData clipDataPassword = ClipData.newPlainText(
"password",
textViewPassword.getText()
);
ClipboardManager clipboard =
(ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(clipDataPassword);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.onlinephotosubmission.csv_importer;
import java.util.Arrays;
class CardHolder {
private static String[] header;
private static int supportingDocsRequiredIndex = -1;
private static int cardholderGroupIndex = -1;
private static int managerEmailIndex = -1;
private static final int EMAIL_INDEX = 0;
private static final int ID_INDEX = 1;
private static final String SUPPORTING_DOCS_REQD_HEADER = "SupportingDocumentsRequired";
private static final String EMAIL_GROUP_HEADER = "EmailGroup";
private static final String CARDHOLDER_GROUP_HEADER = "CardholderGroup";
private static final String MANAGER_EMAIL_HEADER = "ManagerEmail";
private String email;
private String id;
private String supportingDocsRequired;
private String cardholderGroupName;
private String managerEmail;
private String inputString;
private String delimiter;
String[] fieldValues;
CardHolder() {
}
CardHolder(String delimiter, String inputString) {
this.inputString = inputString;
this.delimiter = delimiter;
this.parseInputString();
}
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
String getEmail() {
return email;
}
void setEmail(String inputEmail) {
email = inputEmail;
}
public String getId() {
return id;
}
void setId(String inputID) {
id = inputID;
}
public static String[] getHeader() {
return header;
}
public static void setHeader(String[] header) {
Arrays.parallelSetAll(header, (i) -> header[ i ].replace("\"", "").trim());
supportingDocsRequiredIndex = Arrays.asList(header).indexOf(SUPPORTING_DOCS_REQD_HEADER);
cardholderGroupIndex = (Arrays.asList(header).contains(CARDHOLDER_GROUP_HEADER) ? Arrays.asList(header).indexOf(CARDHOLDER_GROUP_HEADER) : Arrays.asList(header).indexOf(EMAIL_GROUP_HEADER));
managerEmailIndex = Arrays.asList(header).indexOf(MANAGER_EMAIL_HEADER);
CardHolder.header = header;
}
public static String csvHeader() {
return String.join(", ", header);
}
public void parseInputString() {
fieldValues = inputString.split(delimiter);
Arrays.parallelSetAll(fieldValues, (i) -> fieldValues[ i ].trim());
fieldValues = stripQuotes(fieldValues);
email = fieldValues[ EMAIL_INDEX ];
id = fieldValues[ ID_INDEX ];
if (supportingDocsRequiredIndex >= 0) supportingDocsRequired = fieldValues[ supportingDocsRequiredIndex ];
if (cardholderGroupIndex >= 0) cardholderGroupName = fieldValues[cardholderGroupIndex];
if (managerEmailIndex >= 0) managerEmail = fieldValues[ managerEmailIndex ];
}
public String toJSON() {
return toJSON(false);
}
public String toJSON(boolean forUpdate) {
StringBuilder json = new StringBuilder("{ \"email\":\"" + email + "\",");
json.append(forUpdate || !hasCustomFields() ? "" : "\"customFields\":");
if (hasCustomFields())
json.append(getCustomFieldsAsJSON(forUpdate) + ", ");
json.append("\"identifier\":\"" + id + "\"" + getSupportingDocsRequiredJSON() + getCardholderGroupJSON() + getManagerEmailJSON() + " }");
return json.toString();
}
private boolean hasCustomFields() {
return hasCardholderGroup() ? header.length > 3 : header.length > 2;
}
private boolean hasCardholderGroup() {
return cardholderGroupIndex > 0;
}
private String getSupportingDocsRequiredJSON() {
if (supportingDocsRequiredIndex < 0) return "";
else return ", \"additionalPhotoRequired\":" + supportingDocsRequired;
}
private String getCardholderGroupJSON() {
if (cardholderGroupIndex < 0) return "";
else return ", \"cardHolderGroupName\":\"" + cardholderGroupName + "\"";
}
private String getManagerEmailJSON() {
if (managerEmailIndex < 0) return "";
else return ", \"managerEmail\":\"" + managerEmail + "\"";
}
private String getCustomFieldsAsJSON(boolean forUpdate) {
StringBuilder customFieldsAsJSON = new StringBuilder(forUpdate ? "" : "{");
for (int i = 2; i < header.length; i++) {
if (i == supportingDocsRequiredIndex || i == cardholderGroupIndex) continue;
customFieldsAsJSON.append("\"" + header[ i ] + "\":\"" + fieldValues[ i ].replaceAll("\"", "") + "\",");
}
customFieldsAsJSON.deleteCharAt(customFieldsAsJSON.length() - 1);
customFieldsAsJSON.append(forUpdate ? "" : "}");
return customFieldsAsJSON.toString();
}
@Override
public String toString() {
return String.join(", ", fieldValues);
}
public boolean validate() {
return (email.isEmpty() || id.isEmpty()) ? false : true;
}
private String[] stripQuotes(String[] stringArray) {
for (int i = 0; i < stringArray.length; i++) {
stringArray[ i ] = stripQuotes(stringArray[ i ]);
}
return stringArray;
}
private String stripQuotes(String s) {
if (s.matches("^\".+\"$"))
return s.substring(1, s.length() - 1);
else
return s;
}
}
|
package de.refugeehackathon.transit;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
@Bind(R.id.drawer_layout)
DrawerLayout drawerLayout;
@Bind(R.id.toolbar)
Toolbar toolbar;
@Bind(R.id.drawer_navigation)
NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
navigateTo(R.id.navigation_map);
}
private void navigateTo(@IdRes int navId) {
getSupportFragmentManager().beginTransaction().replace(R.id.contentContainer, getFragmentForNavId(navId)).commit();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
final ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
super.onPostCreate(savedInstanceState);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
navigateTo(item.getItemId());
return false;
}
private Fragment getFragmentForNavId(@IdRes int id) {
switch (id) {
case R.id.navigation_about:
return new AboutFragment();
case R.id.navigation_faq:
return new FAQFragment();
default:
case R.id.navigation_map:
return new MapFragment();
}
}
}
|
package com.ra4king.circuitsimulator.gui;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.ra4king.circuitsimulator.gui.Properties.PropertyListValidator;
import com.ra4king.circuitsimulator.gui.file.FileFormat;
import com.ra4king.circuitsimulator.gui.file.FileFormat.CircuitInfo;
import com.ra4king.circuitsimulator.gui.file.FileFormat.ComponentInfo;
import com.ra4king.circuitsimulator.gui.file.FileFormat.WireInfo;
import com.ra4king.circuitsimulator.simulator.Simulator;
import com.ra4king.circuitsimulator.simulator.components.Clock;
import com.ra4king.circuitsimulator.simulator.utils.Pair;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TabPane.TabClosingPolicy;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.KeyCharacterCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
/**
* @author Roi Atalla
*/
public class CircuitSimulator extends Application {
public static void main(String[] args) {
new Thread(FileFormat::init).start();
launch(args);
}
private Simulator simulator;
private ComponentManager componentManager;
private TabPane buttonTabPane;
private ToggleGroup buttonsToggleGroup;
private ComboBox<Integer> bitSizeSelect, secondaryOptionSelect;
private GridPane propertiesTable;
private Tab circuitButtonsTab;
private TabPane canvasTabPane;
private HashMap<Tab, CircuitManager> circuitManagers;
private String componentMode;
private File saveFile;
private int currentClockHz = 1;
@Override
public void init() {
simulator = new Simulator();
circuitManagers = new HashMap<>();
Clock.addChangeListener(value -> {
try {
getCurrentCircuit().getCircuitBoard().runSim();
} catch(Exception exc) {
}
getCurrentCircuit().repaint();
});
}
private CircuitManager getCurrentCircuit() {
return circuitManagers.get(canvasTabPane.getSelectionModel().getSelectedItem());
}
public ComponentManager getComponentManager() {
return componentManager;
}
public void clearSelection() {
if(buttonsToggleGroup.getSelectedToggle() != null) {
buttonsToggleGroup.getSelectedToggle().setSelected(false);
}
componentMode = null;
}
public void setProperties(Properties properties) {
propertiesTable.getChildren().clear();
if(properties != null) {
properties.forEach(property -> {
int size = propertiesTable.getChildren().size();
Label name = new Label(property.name);
GridPane.setHgrow(name, Priority.ALWAYS);
name.setMaxWidth(Double.MAX_VALUE);
name.setMinHeight(30);
name.setBackground(new Background(new BackgroundFill((size / 2) % 2 == 0 ? Color.LIGHTGRAY
: Color.WHITE, null, null)));
Node value;
if(property.validator instanceof PropertyListValidator) {
ComboBox<String> valueList = new ComboBox<>();
for(String entry : ((PropertyListValidator)property.validator).validValues) {
valueList.getItems().add(entry);
}
valueList.setValue(property.value);
valueList.getSelectionModel()
.selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if(oldValue == null || !newValue.equals(oldValue)) {
Properties newProperties = new Properties(properties);
newProperties.setValue(property, newValue);
modifiedSelection(newProperties);
}
});
value = valueList;
} else {
TextField valueField = new TextField(property.value);
valueField.setOnAction(event -> {
String newValue = valueField.getText();
if(!newValue.equals(property.value)) {
Properties newProperties = new Properties(properties);
newProperties.setValue(property, newValue);
modifiedSelection(newProperties);
}
});
value = valueField;
}
Pane valuePane = new Pane(value);
valuePane.setBackground(
new Background(new BackgroundFill((size / 2) % 2 == 0 ? Color.LIGHTGRAY
: Color.WHITE, null, null)));
GridPane.setHgrow(valuePane, Priority.ALWAYS);
propertiesTable.addRow(size, name, valuePane);
});
}
}
private void modifiedSelection() {
modifiedSelection(new Properties());
}
private void modifiedSelection(Properties properties) {
CircuitManager current = getCurrentCircuit();
if(current != null) {
Tab tab = buttonTabPane.getSelectionModel().getSelectedItem();
String group = tab == null ? null : tab.getText();
setProperties(
current.modifiedSelection(componentManager.getComponentCreator(group, componentMode),
properties));
current.repaint();
}
}
private ToggleButton setupButton(ToggleGroup group, String componentName) {
ToggleButton button = new ToggleButton(componentName);
group.getToggles().add(button);
button.setMinHeight(30);
button.setMaxWidth(Double.MAX_VALUE);
button.addEventHandler(ActionEvent.ACTION, (e) -> {
if(componentMode != componentName) {
componentMode = componentName;
} else {
componentMode = null;
}
modifiedSelection();
});
GridPane.setHgrow(button, Priority.ALWAYS);
return button;
}
private void refreshCircuitsTab() {
if(circuitButtonsTab == null) {
circuitButtonsTab = new Tab("Circuits");
circuitButtonsTab.setClosable(false);
circuitButtonsTab.setContent(new GridPane());
buttonTabPane.getTabs().add(circuitButtonsTab);
} else {
circuitButtonsTab.setContent(new GridPane());
}
for(Pair<String, String> component : componentManager.getComponentNames()) {
if(component.first.equals("Circuits")) {
GridPane buttons = (GridPane)circuitButtonsTab.getContent();
ToggleButton toggleButton = setupButton(buttonsToggleGroup, component.second);
buttons.addRow(buttons.getChildren().size(), toggleButton);
}
}
}
private CircuitManager createTab(String name) {
Canvas canvas = new Canvas(800, 600) {
{
widthProperty().addListener(evt -> {
CircuitManager manager = getCurrentCircuit();
if(manager != null) {
manager.repaint();
}
});
heightProperty().addListener(evt -> {
CircuitManager manager = getCurrentCircuit();
if(manager != null) {
manager.repaint();
}
});
}
@Override
public boolean isResizable() {
return true;
}
@Override
public double prefWidth(double width) {
return getWidth();
}
@Override
public double prefHeight(double height) {
return getHeight();
}
};
canvas.widthProperty().bind(canvasTabPane.widthProperty());
canvas.heightProperty().bind(canvasTabPane.heightProperty());
canvas.addEventHandler(MouseEvent.ANY, e -> canvas.requestFocus());
canvas.addEventHandler(MouseEvent.MOUSE_MOVED, this::mouseMoved);
canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, this::mouseDragged);
canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, this::mouseClicked);
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, this::mousePressed);
canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, this::mouseReleased);
canvas.addEventHandler(MouseEvent.MOUSE_ENTERED, this::mouseEntered);
canvas.addEventHandler(MouseEvent.MOUSE_EXITED, this::mouseExited);
canvas.addEventHandler(KeyEvent.KEY_PRESSED, this::keyPressed);
canvas.addEventHandler(KeyEvent.KEY_TYPED, this::keyTyped);
canvas.addEventHandler(KeyEvent.KEY_RELEASED, this::keyReleased);
CircuitManager circuitManager = new CircuitManager(this, canvas, simulator);
for(int count = 0; ; count++) {
try {
String n = name;
if(count > 0) {
n += count;
}
componentManager.addCircuit(n, circuitManager);
name = n;
break;
} catch(Exception exc) {
}
}
Tab canvasTab = new Tab(name, canvas);
MenuItem rename = new MenuItem("Rename");
rename.setOnAction(event -> {
String lastTyped = canvasTab.getText();
while(true) {
try {
TextInputDialog dialog = new TextInputDialog(lastTyped);
dialog.setTitle("Rename circuit");
dialog.setHeaderText("Rename circuit");
dialog.setContentText("Enter new name:");
Optional<String> value = dialog.showAndWait();
if(value.isPresent() && !(lastTyped = value.get().trim()).isEmpty()
&& !lastTyped.equals(canvasTab.getText())) {
componentManager.renameCircuit(canvasTab.getText(), lastTyped);
canvasTab.setText(value.get());
refreshCircuitsTab();
}
break;
} catch(Exception exc) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Duplicate name");
alert.setHeaderText("Duplicate name");
alert.setContentText("Name already exists, please choose a new name.");
alert.showAndWait();
}
}
});
canvasTab.setContextMenu(new ContextMenu(rename));
canvasTab.setOnCloseRequest(event -> {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Delete this circuit?");
alert.setHeaderText("Delete this circuit?");
alert.setContentText("Are you sure you want to delete this circuit?");
Optional<ButtonType> result = alert.showAndWait();
if(!result.isPresent() || result.get() != ButtonType.OK) {
event.consume();
} else {
CircuitManager manager = circuitManagers.remove(canvasTab);
manager.getCircuitBoard().clear();
componentManager.removeCircuit(canvasTab.getText());
if(canvasTabPane.getTabs().size() == 1) {
createTab("New circuit");
} else {
refreshCircuitsTab();
}
}
});
circuitManagers.put(canvasTab, circuitManager);
canvasTabPane.getTabs().addAll(canvasTab);
refreshCircuitsTab();
return circuitManager;
}
@Override
public void start(Stage stage) {
componentManager = new ComponentManager();
buttonTabPane = new TabPane();
buttonTabPane.setMinWidth(100);
propertiesTable = new GridPane();
propertiesTable.setMaxWidth(Double.MAX_VALUE);
bitSizeSelect = new ComboBox<>();
for(int i = 1; i <= 32; i++) {
bitSizeSelect.getItems().add(i);
}
bitSizeSelect.setMaxWidth(Double.MAX_VALUE);
bitSizeSelect.setValue(1);
bitSizeSelect.getSelectionModel()
.selectedItemProperty()
.addListener((observable, oldValue, newValue) -> modifiedSelection());
secondaryOptionSelect = new ComboBox<>();
for(int i = 1; i <= 8; i++) {
secondaryOptionSelect.getItems().add(i);
}
secondaryOptionSelect.setMaxWidth(Double.MAX_VALUE);
secondaryOptionSelect.setValue(1);
secondaryOptionSelect.getSelectionModel()
.selectedItemProperty()
.addListener((observable, oldValue, newValue) -> modifiedSelection());
canvasTabPane = new TabPane();
canvasTabPane.setPrefWidth(800);
canvasTabPane.setPrefHeight(600);
canvasTabPane.setMaxWidth(Double.MAX_VALUE);
canvasTabPane.setMaxHeight(Double.MAX_VALUE);
canvasTabPane.setTabClosingPolicy(TabClosingPolicy.ALL_TABS);
canvasTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
CircuitManager oldManager = circuitManagers.get(oldValue);
CircuitManager newManager = circuitManagers.get(newValue);
if(oldManager != null && newManager != null) {
newManager.setLastMousePosition(oldManager.getLastMousePosition());
}
modifiedSelection();
});
buttonsToggleGroup = new ToggleGroup();
Map<String, Tab> buttonTabs = new HashMap<>();
for(Pair<String, String> component : componentManager.getComponentNames()) {
Tab tab;
if(buttonTabs.containsKey(component.first)) {
tab = buttonTabs.get(component.first);
} else {
tab = new Tab(component.first);
tab.setClosable(false);
tab.setContent(new GridPane());
buttonTabPane.getTabs().add(tab);
buttonTabs.put(component.first, tab);
}
GridPane buttons = (GridPane)tab.getContent();
ToggleButton toggleButton = setupButton(buttonsToggleGroup, component.second);
buttons.addRow(buttons.getChildren().size(), toggleButton);
}
createTab("New circuit");
// Label bitSizeLabel = new Label("Bit size:");
// Label secondaryLabel = new Label("Secondary:");
// GridPane.setHalignment(bitSizeLabel, HPos.CENTER);
// GridPane.setHalignment(secondaryLabel, HPos.CENTER);
// buttons.addRow(count++, bitSizeLabel, secondaryLabel);
// buttons.addRow(count, bitSizeSelect, secondaryOptionSelect);
MenuBar menuBar = new MenuBar();
Menu fileMenu = new Menu("File");
MenuItem load = new MenuItem("Load");
load.setAccelerator(new KeyCharacterCombination("O", KeyCombination.CONTROL_DOWN));
load.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose sim file");
fileChooser.getExtensionFilters().add(new ExtensionFilter("Circuit Sim file", "*.sim"));
File selectedFile = fileChooser.showOpenDialog(stage);
if(selectedFile != null) {
saveFile = selectedFile;
try {
List<CircuitInfo> circuits = FileFormat.load(selectedFile);
circuitManagers.values().forEach(manager -> manager.getCircuitBoard().clear());
circuitManagers.clear();
canvasTabPane.getTabs().clear();
for(CircuitInfo circuit : circuits) {
CircuitManager manager = createTab(circuit.name);
for(ComponentInfo component : circuit.components) {
try {
@SuppressWarnings("unchecked")
Class<? extends ComponentPeer<?>> clazz =
(Class<? extends ComponentPeer<?>>)Class.forName(component.className);
manager.getCircuitBoard().createComponent(ComponentManager.forClass(clazz),
component.properties, component.x,
component.y);
} catch(Exception exc) {
exc.printStackTrace();
}
}
for(WireInfo wire : circuit.wires) {
try {
manager.getCircuitBoard().addWire(wire.x, wire.y, wire.length, wire.isHorizontal);
} catch(Exception exc) {
exc.printStackTrace();
}
}
}
} catch(Exception exc) {
exc.printStackTrace();
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error loading circuits");
alert.setHeaderText("Error loading circuits");
alert.setContentText("Error when loading circuits file: " + exc.getMessage()
+ "\nPlease send the stack trace to a developer.");
alert.show();
}
}
});
MenuItem save = new MenuItem("Save");
save.setAccelerator(new KeyCharacterCombination("S", KeyCombination.CONTROL_DOWN));
save.setOnAction(event -> {
if(saveFile == null) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose sim file");
fileChooser.getExtensionFilters().add(new ExtensionFilter("Circuit Sim file", "*.sim"));
saveFile = fileChooser.showSaveDialog(stage);
}
if(saveFile != null) {
List<CircuitInfo> circuits = new ArrayList<>();
canvasTabPane.getTabs().forEach(tab -> {
CircuitManager manager = circuitManagers.get(tab);
String name = tab.getText();
Set<ComponentInfo> components =
manager.getCircuitBoard()
.getComponents().stream()
.map(component ->
new ComponentInfo(component.getClass().getName(),
component.getX(), component.getY(),
component.getProperties())).collect(
Collectors.toSet());
Set<WireInfo> wires = manager.getCircuitBoard()
.getLinks().stream()
.flatMap(linkWires -> linkWires.getWires().stream())
.map(wire -> new WireInfo(wire.getX(), wire.getY(),
wire.getLength(), wire.isHorizontal()))
.collect(Collectors.toSet());
circuits.add(new CircuitInfo(name, components, wires));
});
try {
FileFormat.save(saveFile, circuits);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Circuits saved");
alert.setHeaderText("Circuits saved");
alert.setContentText("Circuits have successfully been saved.");
alert.show();
} catch(Exception exc) {
exc.printStackTrace();
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error saving circuit");
alert.setHeaderText("Error saving circuit.");
alert.setContentText("Error when saving the circuits: " + exc.getMessage());
alert.show();
}
}
});
MenuItem saveAs = new MenuItem("Save as");
saveAs.setAccelerator(new KeyCharacterCombination("S", KeyCombination.CONTROL_DOWN, KeyCombination.ALT_DOWN));
saveAs.setOnAction(event -> {
File oldSave = saveFile;
saveFile = null;
save.fire();
if(saveFile == null) {
saveFile = oldSave;
}
});
fileMenu.getItems().addAll(load, save, saveAs);
Menu circuitsMenu = new Menu("Circuits");
MenuItem newCircuit = new MenuItem("New circuit");
newCircuit.setOnAction(event -> createTab("New circuit"));
circuitsMenu.getItems().add(newCircuit);
Menu clockMenu = new Menu("Clock");
MenuItem startClock = new MenuItem("Start clock");
startClock.setAccelerator(new KeyCharacterCombination("K", KeyCombination.CONTROL_DOWN));
startClock.setOnAction(event -> {
if(startClock.getText().startsWith("Start")) {
Clock.startClock(currentClockHz);
startClock.setText("Stop clock");
} else {
Clock.stopClock();
startClock.setText("Start clock");
}
});
MenuItem tickClock = new MenuItem("Tick clock");
tickClock.setAccelerator(new KeyCharacterCombination("T", KeyCombination.CONTROL_DOWN));
tickClock.setOnAction(event -> Clock.tick());
Menu frequenciesMenu = new Menu("Frequency");
ToggleGroup freqToggleGroup = new ToggleGroup();
for(int i = 0; i <= 10; i++) {
RadioMenuItem freq = new RadioMenuItem((1 << i) + " Hz");
freq.setToggleGroup(freqToggleGroup);
freq.setSelected(i == 0);
final int j = i;
freq.setOnAction(event -> {
currentClockHz = 1 << j;
Clock.startClock(currentClockHz);
});
frequenciesMenu.getItems().add(freq);
}
clockMenu.getItems().addAll(startClock, tickClock, frequenciesMenu);
menuBar.getMenus().addAll(fileMenu, circuitsMenu, clockMenu);
VBox vBox = new VBox(buttonTabPane, propertiesTable);
VBox.setVgrow(buttonTabPane, Priority.ALWAYS);
VBox.setVgrow(propertiesTable, Priority.ALWAYS);
HBox hBox = new HBox(vBox, canvasTabPane);
HBox.setHgrow(canvasTabPane, Priority.ALWAYS);
VBox.setVgrow(hBox, Priority.ALWAYS);
Scene scene = new Scene(new VBox(menuBar, hBox));
stage.setScene(scene);
stage.setTitle("Circuit Simulator");
stage.sizeToScene();
stage.show();
stage.centerOnScreen();
}
public void keyPressed(KeyEvent e) {
switch(e.getCode()) {
case ESCAPE:
clearSelection();
modifiedSelection();
break;
}
getCurrentCircuit().keyPressed(e);
}
public void keyReleased(KeyEvent e) {
getCurrentCircuit().keyReleased(e);
}
public void keyTyped(KeyEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
getCurrentCircuit().mousePressed(e);
}
public void mouseReleased(MouseEvent e) {
getCurrentCircuit().mouseReleased(e);
}
public void mouseMoved(MouseEvent e) {
getCurrentCircuit().mouseMoved(e);
}
public void mouseDragged(MouseEvent e) {
getCurrentCircuit().mouseDragged(e);
}
public void mouseEntered(MouseEvent e) {
getCurrentCircuit().mouseEntered(e);
}
public void mouseExited(MouseEvent e) {
getCurrentCircuit().mouseExited(e);
}
}
|
package com.redhat.ceylon.compiler.typechecker.model;
import static com.redhat.ceylon.compiler.typechecker.model.Module.LANGUAGE_MODULE_NAME;
import static com.redhat.ceylon.compiler.typechecker.model.Util.addToIntersection;
import static com.redhat.ceylon.compiler.typechecker.model.Util.intersectionType;
import static com.redhat.ceylon.compiler.typechecker.model.Util.isNameMatching;
import static com.redhat.ceylon.compiler.typechecker.model.Util.isOverloadedVersion;
import static com.redhat.ceylon.compiler.typechecker.model.Util.producedType;
import static com.redhat.ceylon.compiler.typechecker.model.Util.unionType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import com.redhat.ceylon.compiler.typechecker.context.ProducedTypeCache;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Identifier;
public class Unit {
private Package pkg;
private List<Import> imports = new ArrayList<Import>();
private List<Declaration> declarations = new ArrayList<Declaration>();
private String filename;
private List<ImportList> importLists = new ArrayList<ImportList>();
private Set<Identifier> unresolvedReferences = new HashSet<Identifier>();
private Set<Declaration> duplicateDeclarations = new HashSet<Declaration>();
private final Set<String> dependentsOf = new HashSet<String>();
private String fullPath;
private String relativePath;
public List<Import> getImports() {
return imports;
}
public List<ImportList> getImportLists() {
return importLists;
}
/**
* @return the dependentsOf
*/
public Set<String> getDependentsOf() {
return dependentsOf;
}
public Set<Identifier> getUnresolvedReferences() {
return unresolvedReferences;
}
public Set<Declaration> getDuplicateDeclarations() {
return duplicateDeclarations;
}
public Package getPackage() {
return pkg;
}
public void setPackage(Package p) {
pkg = p;
}
public List<Declaration> getDeclarations() {
synchronized (declarations) {
return new ArrayList<Declaration>(declarations);
}
}
public void addDeclaration(Declaration declaration) {
synchronized (declarations) {
declarations.add(declaration);
}
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getFullPath() {
return fullPath;
}
public void setFullPath(String fullPath) {
this.fullPath = fullPath;
}
public String getRelativePath() {
return relativePath;
}
public void setRelativePath(String relativePath) {
this.relativePath = relativePath;
}
@Override
public String toString() {
return "Unit[" + filename + "]";
}
public Import getImport(String name) {
for (Import i: getImports()) {
if (!i.isAmbiguous() &&
i.getTypeDeclaration()==null &&
i.getAlias().equals(name)) {
return i;
}
}
return null;
}
public String getAliasedName(Declaration dec) {
for (Import i: getImports()) {
if (!i.isAmbiguous() &&
i.getDeclaration().equals(getAbstraction(dec))) {
return i.getAlias();
}
}
return dec.getName();
}
public static Declaration getAbstraction(Declaration dec){
if (isOverloadedVersion(dec)) {
return dec.getContainer()
.getDirectMember(dec.getName(), null, false);
}
else {
return dec;
}
}
/**
* Search the imports of a compilation unit
* for the named toplevel declaration.
*/
public Declaration getImportedDeclaration(String name,
List<ProducedType> signature, boolean ellipsis) {
for (Import i: getImports()) {
if (!i.isAmbiguous() &&
i.getAlias().equals(name)) {
//in case of an overloaded member, this will
//be the "abstraction", so search for the
//correct overloaded version
Declaration d = i.getDeclaration();
if (d.isToplevel() || d.isStaticallyImportable()) {
return d.getContainer()
.getMember(d.getName(),
signature, ellipsis);
}
}
}
return null;
}
/**
* Search the imports of a compilation unit
* for the named member declaration.
*/
public Declaration getImportedDeclaration(TypeDeclaration td, String name,
List<ProducedType> signature, boolean ellipsis) {
for (Import i: getImports()) {
TypeDeclaration itd = i.getTypeDeclaration();
if (itd!=null && itd.equals(td) &&
!i.isAmbiguous() &&
i.getAlias().equals(name)) {
//in case of an overloaded member, this will
//be the "abstraction", so search for the
//correct overloaded version
Declaration d = i.getDeclaration();
return d.getContainer()
.getMember(d.getName(),
signature, ellipsis);
}
}
return null;
}
public Map<String, DeclarationWithProximity>
getMatchingImportedDeclarations(String startingWith, int proximity) {
Map<String, DeclarationWithProximity> result =
new TreeMap<String, DeclarationWithProximity>();
for (Import i: new ArrayList<Import>(getImports())) {
if (i.getAlias()!=null &&
!i.isAmbiguous() &&
isNameMatching(startingWith, i)) {
Declaration d = i.getDeclaration();
if (d.isToplevel() || d.isStaticallyImportable()) {
result.put(i.getAlias(),
new DeclarationWithProximity(i,
proximity));
}
}
}
return result;
}
public Map<String, DeclarationWithProximity>
getMatchingImportedDeclarations(TypeDeclaration td,
String startingWith, int proximity) {
Map<String, DeclarationWithProximity> result =
new TreeMap<String, DeclarationWithProximity>();
for (Import i: new ArrayList<Import>(getImports())) {
TypeDeclaration itd = i.getTypeDeclaration();
if (i.getAlias()!=null &&
!i.isAmbiguous() &&
itd!=null && itd.equals(td) &&
isNameMatching(startingWith, i)) {
result.put(i.getAlias(),
new DeclarationWithProximity(i,
proximity));
}
}
return result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Unit) {
Unit that = (Unit) obj;
return that.getPackage().equals(getPackage())
&& that.getFullPath().equals(getFullPath());
}
else {
return false;
}
}
@Override
public int hashCode() {
return getFullPath().hashCode();
}
private Module languageModule;
private Package languagePackage;
/**
* Search for a declaration in the language module.
*/
public Declaration getLanguageModuleDeclaration(String name) {
//all elements in ceylon.language are auto-imported
//traverse all default module packages provided they
//have not been traversed yet
Module languageModule = getLanguageModule();
if (languageModule!=null && languageModule.isAvailable()) {
if ("Nothing".equals(name)) {
return getNothingDeclaration();
}
if (languagePackage==null) {
languagePackage =
languageModule.getPackage(LANGUAGE_MODULE_NAME);
}
if (languagePackage != null) {
Declaration d =
languagePackage.getMember(name, null, false);
if (d != null && d.isShared()) {
return d;
}
}
}
return null;
}
private Module getLanguageModule() {
if (languageModule==null) {
languageModule = getPackage().getModule().getLanguageModule();
}
return languageModule;
}
/**
* Search for a declaration in {@code ceylon.language.model}
*/
public Declaration getLanguageModuleModelDeclaration(String name) {
Module languageModule = getPackage().getModule().getLanguageModule();
if ( languageModule != null && languageModule.isAvailable() ) {
Package languageScope =
languageModule.getPackage("ceylon.language.meta.model");
if (languageScope != null) {
Declaration d = languageScope.getMember(name, null, false);
if (d != null && d.isShared()) {
return d;
}
}
}
return null;
}
/**
* Search for a declaration in {@code ceylon.language.model.declaration}
*/
public Declaration getLanguageModuleDeclarationDeclaration(String name) {
Module languageModule = getPackage().getModule().getLanguageModule();
if ( languageModule != null && languageModule.isAvailable() ) {
Package languageScope =
languageModule.getPackage("ceylon.language.meta.declaration");
if (languageScope != null) {
Declaration d = languageScope.getMember(name, null, false);
if (d != null && d.isShared()) {
return d;
}
}
}
return null;
}
public Interface getCorrespondenceDeclaration() {
return (Interface) getLanguageModuleDeclaration("Correspondence");
}
public Class getAnythingDeclaration() {
return (Class) getLanguageModuleDeclaration("Anything");
}
public Class getNullDeclaration() {
return (Class) getLanguageModuleDeclaration("Null");
}
public Value getNullValueDeclaration() {
return (Value) getLanguageModuleDeclaration("null");
}
public Interface getEmptyDeclaration() {
return (Interface) getLanguageModuleDeclaration("Empty");
}
public Interface getSequenceDeclaration() {
return (Interface) getLanguageModuleDeclaration("Sequence");
}
public Class getObjectDeclaration() {
return (Class) getLanguageModuleDeclaration("Object");
}
public Class getBasicDeclaration() {
return (Class) getLanguageModuleDeclaration("Basic");
}
public Interface getIdentifiableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Identifiable");
}
public Class getThrowableDeclaration() {
return (Class) getLanguageModuleDeclaration("Throwable");
}
public Class getErrorDeclaration() {
return (Class) getLanguageModuleDeclaration("Error");
}
public Class getExceptionDeclaration() {
return (Class) getLanguageModuleDeclaration("Exception");
}
public Interface getCategoryDeclaration() {
return (Interface) getLanguageModuleDeclaration("Category");
}
public Interface getIterableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Iterable");
}
public Interface getSequentialDeclaration() {
return (Interface) getLanguageModuleDeclaration("Sequential");
}
public Interface getListDeclaration() {
return (Interface) getLanguageModuleDeclaration("List");
}
public Interface getIteratorDeclaration() {
return (Interface) getLanguageModuleDeclaration("Iterator");
}
public Interface getCallableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Callable");
}
public Interface getScalableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Scalable");
}
public Interface getSummableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Summable");
}
public Interface getNumericDeclaration() {
return (Interface) getLanguageModuleDeclaration("Numeric");
}
public Interface getIntegralDeclaration() {
return (Interface) getLanguageModuleDeclaration("Integral");
}
public Interface getInvertableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Invertible");
}
public Interface getExponentiableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Exponentiable");
}
public Interface getSetDeclaration() {
return (Interface) getLanguageModuleDeclaration("Set");
}
public TypeDeclaration getComparisonDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("Comparison");
}
public TypeDeclaration getBooleanDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("Boolean");
}
public Value getTrueValueDeclaration() {
return (Value) getLanguageModuleDeclaration("true");
}
public Value getFalseValueDeclaration() {
return (Value) getLanguageModuleDeclaration("false");
}
public TypeDeclaration getStringDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("String");
}
public TypeDeclaration getFloatDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("Float");
}
public TypeDeclaration getIntegerDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("Integer");
}
public TypeDeclaration getCharacterDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("Character");
}
public TypeDeclaration getByteDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("Byte");
}
public Interface getComparableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Comparable");
}
public Interface getUsableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Usable");
}
public Interface getDestroyableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Destroyable");
}
public Interface getObtainableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Obtainable");
}
public Interface getOrdinalDeclaration() {
return (Interface) getLanguageModuleDeclaration("Ordinal");
}
public Interface getEnumerableDeclaration() {
return (Interface) getLanguageModuleDeclaration("Enumerable");
}
public Class getRangeDeclaration() {
return (Class) getLanguageModuleDeclaration("Range");
}
public Class getSpanDeclaration() {
return (Class) getLanguageModuleDeclaration("Span");
}
public Class getMeasureDeclaration() {
return (Class) getLanguageModuleDeclaration("Measure");
}
public Class getTupleDeclaration() {
return (Class) getLanguageModuleDeclaration("Tuple");
}
public TypeDeclaration getArrayDeclaration() {
return (Class) getLanguageModuleDeclaration("Array");
}
public Interface getRangedDeclaration() {
return (Interface) getLanguageModuleDeclaration("Ranged");
}
public Class getEntryDeclaration() {
return (Class) getLanguageModuleDeclaration("Entry");
}
ProducedType getCallableType(ProducedReference ref, ProducedType rt) {
ProducedType result = denotableType(rt);
Declaration declaration = ref.getOverloadedVersion();
if (declaration instanceof Functional) {
List<ParameterList> pls =
((Functional) declaration).getParameterLists();
for (int i=pls.size()-1; i>=0; i
boolean hasSequenced = false;
boolean atLeastOne = false;
int firstDefaulted = -1;
List<Parameter> ps = pls.get(i).getParameters();
List<ProducedType> args =
new ArrayList<ProducedType>(ps.size());
for (int j=0; j<ps.size(); j++) {
Parameter p = ps.get(j);
if (p.getModel()==null) {
args.add(new UnknownType(this).getType());
}
else {
ProducedTypedReference np = ref.getTypedParameter(p);
ProducedType npt = np.getType();
if (npt==null) {
args.add(new UnknownType(this).getType());
}
else {
if (p.isDefaulted() &&
firstDefaulted==-1) {
firstDefaulted = j;
}
if (np.getDeclaration() instanceof Functional) {
args.add(getCallableType(np, npt));
}
else if (p.isSequenced()) {
args.add(getIteratedType(npt));
hasSequenced = true;
atLeastOne = p.isAtLeastOne();
}
else {
args.add(npt);
}
}
}
}
ProducedType paramListType =
getTupleType(args,
hasSequenced, atLeastOne,
firstDefaulted);
result = producedType(getCallableDeclaration(),
result, paramListType);
}
}
return result;
}
public ProducedType getTupleType(List<ProducedType> elemTypes,
boolean variadic, boolean atLeastOne, int firstDefaulted) {
ProducedType result = getType(getEmptyDeclaration());
ProducedType union = getType(getNothingDeclaration());
int last = elemTypes.size()-1;
for (int i=last; i>=0; i
ProducedType elemType = elemTypes.get(i);
union = unionType(union, elemType, this);
if (variadic && i==last) {
result = atLeastOne ?
getSequenceType(elemType) :
getSequentialType(elemType);
}
else {
result = producedType(getTupleDeclaration(),
union, elemType, result);
if (firstDefaulted>=0 && i>=firstDefaulted) {
result = unionType(result,
getType(getEmptyDeclaration()), this);
}
}
}
return result;
}
public ProducedType getEmptyType(ProducedType pt) {
return pt==null ? null :
unionType(pt, getType(getEmptyDeclaration()), this);
/*else if (isEmptyType(pt)) {
//Null|Null|T == Null|T
return pt;
}
else if (pt.getDeclaration() instanceof NothingType) {
//Null|0 == Null
return getEmptyDeclaration().getType();
}
else {
UnionType ut = new UnionType();
List<ProducedType> types = new ArrayList<ProducedType>();
addToUnion(types,getEmptyDeclaration().getType());
addToUnion(types,pt);
ut.setCaseTypes(types);
return ut.getType();
}*/
}
public ProducedType getPossiblyNoneType(ProducedType pt) {
return pt==null ? null :
unionType(pt, producedType(getSequentialDeclaration(),
getType(getAnythingDeclaration())), this);
}
public ProducedType getOptionalType(ProducedType pt) {
return pt==null ? null :
unionType(pt, getType(getNullDeclaration()), this);
/*else if (isOptionalType(pt)) {
//Null|Null|T == Null|T
return pt;
}
else if (pt.getDeclaration() instanceof NothingType) {
//Null|0 == Null
return getNullDeclaration().getType();
}
else {
UnionType ut = new UnionType();
List<ProducedType> types = new ArrayList<ProducedType>();
addToUnion(types,getNullDeclaration().getType());
addToUnion(types,pt);
ut.setCaseTypes(types);
return ut.getType();
}*/
}
public ProducedType getSequenceType(ProducedType et) {
return producedType(getSequenceDeclaration(), et);
}
public ProducedType getSequentialType(ProducedType et) {
return producedType(getSequentialDeclaration(), et);
}
public ProducedType getIterableType(ProducedType et) {
return producedType(getIterableDeclaration(), et,
getType(getNullDeclaration()));
}
public ProducedType getNonemptyIterableType(ProducedType et) {
return producedType(getIterableDeclaration(), et,
getNothingDeclaration().getType());
}
public ProducedType getSetType(ProducedType et) {
return producedType(getSetDeclaration(), et);
}
/**
* Returns a ProducedType corresponding to {@code Iterator<T>}
* @param et The ProducedType corresponding to {@code T}
* @return The ProducedType corresponding to {@code Iterator<T>}
*/
public ProducedType getIteratorType(ProducedType et) {
return Util.producedType(getIteratorDeclaration(), et);
}
/**
* Returns a ProducedType corresponding to {@code Span<T>}
* @param rt The ProducedType corresponding to {@code T}
* @return The ProducedType corresponding to {@code Span<T>}
*/
public ProducedType getSpanType(ProducedType rt) {
return Util.producedType(getRangeDeclaration(), rt);
}
/**
* Returns a ProducedType corresponding to {@code SizedRange<T>|[]}
* @param rt The ProducedType corresponding to {@code T}
* @return The ProducedType corresponding to {@code SizedRange<T>|[]}
*/
public ProducedType getMeasureType(ProducedType rt) {
return unionType(Util.producedType(getRangeDeclaration(), rt),
getType(getEmptyDeclaration()), this);
}
public ProducedType getEntryType(ProducedType kt, ProducedType vt) {
return producedType(getEntryDeclaration(), kt, vt);
}
public ProducedType getKeyType(ProducedType type) {
ProducedType st = type.getSupertype(getEntryDeclaration());
if (st!=null && st.getTypeArguments().size()==2) {
return st.getTypeArgumentList().get(0);
}
else {
return null;
}
}
public ProducedType getValueType(ProducedType type) {
ProducedType st = type.getSupertype(getEntryDeclaration());
if (st!=null && st.getTypeArguments().size()==2) {
return st.getTypeArgumentList().get(1);
}
else {
return null;
}
}
public ProducedType getIteratedType(ProducedType type) {
ProducedType st = type.getSupertype(getIterableDeclaration());
if (st!=null && st.getTypeArguments().size()>0) {
return st.getTypeArgumentList().get(0);
}
else {
return null;
}
}
public ProducedType getFirstType(ProducedType type) {
ProducedType st = type.getSupertype(getIterableDeclaration());
if (st!=null && st.getTypeArguments().size()>1) {
return st.getTypeArgumentList().get(1);
}
else {
return null;
}
}
public boolean isNonemptyIterableType(ProducedType type) {
ProducedType ft = getFirstType(type);
return ft!=null && ft.isNothing();
}
public ProducedType getSetElementType(ProducedType type) {
ProducedType st = type.getSupertype(getSetDeclaration());
if (st!=null && st.getTypeArguments().size()==1) {
return st.getTypeArgumentList().get(0);
}
else {
return null;
}
}
public ProducedType getSequentialElementType(ProducedType type) {
ProducedType st = type.getSupertype(getSequentialDeclaration());
if (st!=null && st.getTypeArguments().size()==1) {
return st.getTypeArgumentList().get(0);
}
else {
return null;
}
}
public ProducedType getDefiniteType(ProducedType pt) {
return intersectionType(getType(getObjectDeclaration()),
pt, pt.getDeclaration().getUnit());
/*if (pt.getDeclaration().equals(getAnythingDeclaration())) {
return getObjectDeclaration().getType();
}
else {
return pt.minus(getNullDeclaration());
}*/
}
public ProducedType getNonemptyType(ProducedType pt) {
return intersectionType(producedType(getSequenceDeclaration(),
getSequentialElementType(pt)), pt,
pt.getDeclaration().getUnit());
/*if (pt.getDeclaration().equals(getAnythingDeclaration())) {
return getObjectDeclaration().getType();
}
else {
return pt.minus(getNullDeclaration());
}*/
}
public ProducedType getNonemptyDefiniteType(ProducedType pt) {
return getNonemptyType(getDefiniteType(pt));
}
public boolean isEntryType(ProducedType pt) {
return pt.getDeclaration().inherits(getEntryDeclaration());
}
public boolean isIterableType(ProducedType pt) {
return pt.getDeclaration().inherits(getIterableDeclaration());
}
public boolean isUsableType(ProducedType pt) {
return pt.getDeclaration().inherits(getUsableDeclaration());
}
public boolean isSequentialType(ProducedType pt) {
return pt.getDeclaration().inherits(getSequentialDeclaration());
}
public boolean isSequenceType(ProducedType pt) {
return pt.getDeclaration().inherits(getSequenceDeclaration());
}
public boolean isEmptyType(ProducedType pt) {
return pt.getDeclaration().inherits(getEmptyDeclaration());
}
public boolean isOptionalType(ProducedType pt) {
//must have non-empty intersection with Null
//and non-empty intersection with Value
return !intersectionType(getType(getNullDeclaration()), pt, this)
.isNothing() &&
!intersectionType(getType(getObjectDeclaration()), pt, this)
.isNothing();
}
public boolean isPossiblyEmptyType(ProducedType pt) {
//must be a subtype of Sequential<Anything>
return isSequentialType(getDefiniteType(pt)) &&
//must have non-empty intersection with Empty
//and non-empty intersection with Sequence<Nothing>
!intersectionType(getType(getEmptyDeclaration()), pt, this)
.isNothing() &&
!intersectionType(getSequentialType(getNothingDeclaration().getType()), pt, this)
.isNothing();
}
public boolean isCallableType(ProducedType pt) {
return pt!=null && pt.getDeclaration().inherits(getCallableDeclaration());
}
public NothingType getNothingDeclaration() {
return new NothingType(this);
}
public ProducedType denotableType(ProducedType pt) {
if (pt!=null) {
TypeDeclaration d = pt.getDeclaration();
if (d instanceof Functional) {
if (((Functional) d).isOverloaded()) {
pt = pt.getSupertype(d.getExtendedTypeDeclaration());
}
}
if (d instanceof Constructor) {
return pt.getSupertype(d.getExtendedTypeDeclaration());
}
if (d!=null && d.isAnonymous() ) {
ClassOrInterface etd = d.getExtendedTypeDeclaration();
List<TypeDeclaration> stds =
d.getSatisfiedTypeDeclarations();
List<ProducedType> list =
new ArrayList<ProducedType>(stds.size()+1);
addToIntersection(list, pt.getSupertype(etd), this);
for (TypeDeclaration td: stds) {
addToIntersection(list, pt.getSupertype(td), this);
}
IntersectionType it = new IntersectionType(this);
it.setSatisfiedTypes(list);
return it.getType();
}
else {
return pt;
}
}
else {
return null;
}
}
public ProducedType nonemptyArgs(ProducedType args) {
return getType(getEmptyDeclaration()).isSubtypeOf(args) ?
getNonemptyType(args) : args;
}
public List<ProducedType> getTupleElementTypes(ProducedType args) {
if (args!=null) {
List<ProducedType> simpleResult =
getSimpleTupleElementTypes(args, 0);
if (simpleResult!=null){
return simpleResult;
}
ProducedType tst = nonemptyArgs(args)
.getSupertype(getTupleDeclaration());
if (tst!=null) {
List<ProducedType> tal = tst.getTypeArgumentList();
if (tal.size()>=3) {
List<ProducedType> result =
getTupleElementTypes(tal.get(2));
ProducedType arg = tal.get(1);
if (arg==null) {
arg = new UnknownType(this).getType();
}
result.add(0, arg);
return result;
}
}
else if (isEmptyType(args)) {
return new LinkedList<ProducedType>();
}
else if (isSequentialType(args)) {
if (!(args.getDeclaration() instanceof TypeParameter)) {
LinkedList<ProducedType> sequenced =
new LinkedList<ProducedType>();
sequenced.add(args);
return sequenced;
}
}
}
LinkedList<ProducedType> unknown =
new LinkedList<ProducedType>();
unknown.add(new UnknownType(this).getType());
return unknown;
}
private List<ProducedType> getSimpleTupleElementTypes(ProducedType args, int count) {
// can be a defaulted tuple of Empty|Tuple
TypeDeclaration declaration = args.getDeclaration();
if (declaration instanceof UnionType) {
List<ProducedType> caseTypes = declaration.getCaseTypes();
if (caseTypes == null || caseTypes.size() != 2) {
return null;
}
ProducedType caseA = caseTypes.get(0);
TypeDeclaration caseADecl = caseA.getDeclaration();
ProducedType caseB = caseTypes.get(1);
TypeDeclaration caseBDecl = caseB.getDeclaration();
if (caseADecl instanceof ClassOrInterface == false
|| caseBDecl instanceof ClassOrInterface == false) {
return null;
}
String caseAName = caseADecl.getQualifiedNameString();
String caseBName = caseBDecl.getQualifiedNameString();
if (caseAName.equals("ceylon.language::Empty")
&& caseBName.equals("ceylon.language::Tuple")) {
return getSimpleTupleElementTypes(caseB, count);
}
if (caseBName.equals("ceylon.language::Empty")
&& caseAName.equals("ceylon.language::Tuple")) {
return getSimpleTupleElementTypes(caseA, count);
}
return null;
}
// can be Tuple, Empty, Sequence or Sequential
if (declaration instanceof ClassOrInterface == false) {
return null;
}
String name = declaration.getQualifiedNameString();
if (name.equals("ceylon.language::Tuple")){
ProducedType first = args.getTypeArgumentList().get(1);
ProducedType rest = args.getTypeArgumentList().get(2);
List<ProducedType> ret =
getSimpleTupleElementTypes(rest, count+1);
if (ret == null)
return null;
ret.set(count, first);
return ret;
}
if (name.equals("ceylon.language::Empty")){
ArrayList<ProducedType> ret =
new ArrayList<ProducedType>(count);
for (int i=0;i<count;i++) {
ret.add(null);
}
return ret;
}
if (name.equals("ceylon.language::Sequential")
|| name.equals("ceylon.language::Sequence")) {
ArrayList<ProducedType> ret =
new ArrayList<ProducedType>(count+1);
for (int i=0;i<count;i++) {
ret.add(null);
}
ret.add(args);
return ret;
}
return null;
}
public boolean isTupleLengthUnbounded(ProducedType args) {
if (args!=null) {
Boolean simpleTupleLengthUnbounded =
isSimpleTupleLengthUnbounded(args);
if (simpleTupleLengthUnbounded != null) {
return simpleTupleLengthUnbounded.booleanValue();
}
ProducedType tst = nonemptyArgs(args)
.getSupertype(getTupleDeclaration());
if (tst!=null) {
List<ProducedType> tal = tst.getTypeArgumentList();
if (tal.size()>=3) {
return isTupleLengthUnbounded(tal.get(2));
}
}
else if (isEmptyType(args)) {
return false;
}
else if (isSequentialType(args)) {
return !(args.getDeclaration() instanceof TypeParameter);
}
}
return false;
}
private Boolean isSimpleTupleLengthUnbounded(ProducedType args) {
// can be a defaulted tuple of Empty|Tuple
TypeDeclaration declaration = args.getDeclaration();
if (declaration instanceof UnionType){
List<ProducedType> caseTypes = declaration.getCaseTypes();
if (caseTypes == null || caseTypes.size() != 2) {
return null;
}
ProducedType caseA = caseTypes.get(0);
TypeDeclaration caseADecl = caseA.getDeclaration();
ProducedType caseB = caseTypes.get(1);
TypeDeclaration caseBDecl = caseB.getDeclaration();
if (caseADecl instanceof ClassOrInterface == false
|| caseBDecl instanceof ClassOrInterface == false) {
return null;
}
String caseAName = caseADecl.getQualifiedNameString();
String caseBName = caseBDecl.getQualifiedNameString();
if (caseAName.equals("ceylon.language::Empty")
&& caseBName.equals("ceylon.language::Tuple")) {
return isSimpleTupleLengthUnbounded(caseB);
}
if (caseBName.equals("ceylon.language::Empty")
&& caseAName.equals("ceylon.language::Tuple")) {
return isSimpleTupleLengthUnbounded(caseA);
}
return null;
}
// can be Tuple, Empty, Sequence or Sequential
if (declaration instanceof ClassOrInterface == false) {
return null;
}
String name = declaration.getQualifiedNameString();
if (name.equals("ceylon.language::Tuple")) {
ProducedType rest = args.getTypeArgumentList().get(2);
return isSimpleTupleLengthUnbounded(rest);
}
if (name.equals("ceylon.language::Empty")) {
return false;
}
if (name.equals("ceylon.language::Sequential")
|| name.equals("ceylon.language::Sequence")) {
return true;
}
return null;
}
public boolean isTupleVariantAtLeastOne(ProducedType args) {
if (args!=null) {
Boolean simpleTupleVariantAtLeastOne =
isSimpleTupleVariantAtLeastOne(args);
if (simpleTupleVariantAtLeastOne != null) {
return simpleTupleVariantAtLeastOne.booleanValue();
}
ProducedType tst = nonemptyArgs(args)
.getSupertype(getTupleDeclaration());
if (tst!=null) {
List<ProducedType> tal = tst.getTypeArgumentList();
if (tal.size()>=3) {
return isTupleVariantAtLeastOne(tal.get(2));
}
}
else if (isEmptyType(args)) {
return false;
}
else if (isSequenceType(args)) {
return true;
}
else if (isSequentialType(args)) {
return false;
}
}
return false;
}
private Boolean isSimpleTupleVariantAtLeastOne(ProducedType args) {
// can be a defaulted tuple of Empty|Tuple
TypeDeclaration declaration = args.getDeclaration();
if (declaration instanceof UnionType) {
List<ProducedType> caseTypes = declaration.getCaseTypes();
if (caseTypes == null || caseTypes.size() != 2) {
return null;
}
ProducedType caseA = caseTypes.get(0);
TypeDeclaration caseADecl = caseA.getDeclaration();
ProducedType caseB = caseTypes.get(1);
TypeDeclaration caseBDecl = caseB.getDeclaration();
if (caseADecl instanceof ClassOrInterface == false
|| caseBDecl instanceof ClassOrInterface == false)
return null;
String caseAName = caseADecl.getQualifiedNameString();
String caseBName = caseBDecl.getQualifiedNameString();
if (caseAName.equals("ceylon.language::Empty")
&& caseBName.equals("ceylon.language::Tuple")) {
return isSimpleTupleVariantAtLeastOne(caseB);
}
if (caseBName.equals("ceylon.language::Empty")
&& caseAName.equals("ceylon.language::Tuple")) {
return isSimpleTupleVariantAtLeastOne(caseA);
}
return null;
}
// can be Tuple, Empty, Sequence or Sequential
if (declaration instanceof ClassOrInterface == false) {
return null;
}
String name = declaration.getQualifiedNameString();
if (name.equals("ceylon.language::Tuple")) {
ProducedType rest = args.getTypeArgumentList().get(2);
return isSimpleTupleVariantAtLeastOne(rest);
}
if (name.equals("ceylon.language::Empty")) {
return false;
}
if (name.equals("ceylon.language::Sequential")) {
return false;
}
if (name.equals("ceylon.language::Sequence")) {
return true;
}
return null;
}
public int getTupleMinimumLength(ProducedType args) {
if (args!=null) {
int simpleMinimumLength =
getSimpleTupleMinimumLength(args);
if (simpleMinimumLength != -1) {
return simpleMinimumLength;
}
if (getType(getEmptyDeclaration()).isSubtypeOf(args)) {
return 0;
}
ProducedType tst = nonemptyArgs(args)
.getSupertype(getTupleDeclaration());
if (tst!=null) {
List<ProducedType> tal = tst.getTypeArgumentList();
if (tal.size()>=3) {
return getTupleMinimumLength(tal.get(2))+1;
}
}
else if (isEmptyType(args)) {
return 0;
}
else if (isSequenceType(args)) {
return 1;
}
else if (isSequentialType(args)) {
return 0;
}
}
return 0;
}
private int getSimpleTupleMinimumLength(ProducedType args) {
// can be a defaulted tuple of Empty|Tuple
TypeDeclaration declaration = args.getDeclaration();
if (declaration instanceof UnionType){
List<ProducedType> caseTypes = declaration.getCaseTypes();
if (caseTypes == null || caseTypes.size() != 2) {
return -1;
}
ProducedType caseA = caseTypes.get(0);
TypeDeclaration caseADecl = caseA.getDeclaration();
ProducedType caseB = caseTypes.get(1);
TypeDeclaration caseBDecl = caseB.getDeclaration();
if (caseADecl instanceof ClassOrInterface == false
|| caseBDecl instanceof ClassOrInterface == false)
return -1;
String caseAName = caseADecl.getQualifiedNameString();
String caseBName = caseBDecl.getQualifiedNameString();
if (caseAName.equals("ceylon.language::Empty")
&& caseBName.equals("ceylon.language::Tuple")) {
return 0;
}
if (caseBName.equals("ceylon.language::Empty")
&& caseAName.equals("ceylon.language::Tuple")) {
return 0;
}
return -1;
}
// can be Tuple, Empty, Sequence or Sequential
if (declaration instanceof ClassOrInterface == false) {
return -1;
}
String name = declaration.getQualifiedNameString();
if (name.equals("ceylon.language::Tuple")) {
ProducedType rest = args.getTypeArgumentList().get(2);
int ret = getSimpleTupleMinimumLength(rest);
if(ret == -1)
return -1;
return ret + 1;
}
if (name.equals("ceylon.language::Empty")) {
return 0;
}
if (name.equals("ceylon.language::Sequential")) {
return 0;
}
if (name.equals("ceylon.language::Sequence")) {
return 1;
}
return -1;
}
public List<ProducedType> getCallableArgumentTypes(ProducedType t) {
ProducedType tuple = getCallableTuple(t);
if (tuple == null) {
return Collections.emptyList();
}
else {
return getTupleElementTypes(tuple);
}
}
public ProducedType getCallableTuple(ProducedType t) {
if (t==null) return null;
ProducedType ct = t.getSupertype(getCallableDeclaration());
if (ct!=null) {
List<ProducedType> typeArgs = ct.getTypeArgumentList();
if (typeArgs.size()>=2) {
return typeArgs.get(1);
}
}
return null;
}
public ProducedType getCallableReturnType(ProducedType t) {
if (t==null) return null;
ProducedType ct = t.getSupertype(getCallableDeclaration());
if (ct!=null) {
List<ProducedType> typeArgs = ct.getTypeArgumentList();
if (typeArgs.size()>=1) {
return typeArgs.get(0);
}
}
return null;
}
public boolean isIterableParameterType(ProducedType t) {
return t.getDeclaration() instanceof Interface &&
t.getDeclaration().equals(getIterableDeclaration());
}
public TypeDeclaration getLanguageModuleModelTypeDeclaration(String name) {
return (TypeDeclaration) getLanguageModuleModelDeclaration(name);
}
public TypeDeclaration getLanguageModuleDeclarationTypeDeclaration(String name) {
return (TypeDeclaration) getLanguageModuleDeclarationDeclaration(name);
}
private final Map<String,String> modifiers = new HashMap<String,String>();
private void put(String modifier) {
modifiers.put(modifier, modifier);
}
{
put("shared");
put("default");
put("formal");
put("native");
put("actual");
put("abstract");
put("final");
put("sealed");
put("variable");
put("late");
put("deprecated");
put("annotation");
put("optional");
}
public Map<String, String> getModifiers() {
return modifiers;
}
public ProducedType getValueMetatype(ProducedTypedReference pr) {
boolean variable = pr.getDeclaration().isVariable();
ProducedType getType = denotableType(pr.getType());
ProducedType setType = variable ?
denotableType(pr.getType()) :
new NothingType(this).getType();
if (pr.getQualifyingType() != null) {
return producedType(getLanguageModuleModelTypeDeclaration("Attribute"),
pr.getQualifyingType(), getType, setType);
}
else {
return producedType(getLanguageModuleModelTypeDeclaration("Value"),
getType, setType);
}
}
public ProducedType getFunctionMetatype(ProducedTypedReference pr) {
Functional f = (Functional) pr.getDeclaration();
if (f.getParameterLists().isEmpty()) {
return null;
}
ParameterList fpl = f.getParameterLists().get(0);
ProducedType parameterTuple =
getParameterTypesAsTupleType(fpl.getParameters(), pr);
ProducedType returnType = getCallableReturnType(pr.getFullType());
if (returnType == null) {
return null;
}
else {
if (pr.getQualifyingType() != null) {
return producedType(getLanguageModuleModelTypeDeclaration("Method"),
pr.getQualifyingType(), returnType, parameterTuple);
}
else {
return producedType(getLanguageModuleModelTypeDeclaration("Function"),
returnType, parameterTuple);
}
}
}
public ProducedType getClassMetatype(ProducedType literalType) {
Class c = (Class) literalType.getDeclaration();
ParameterList parameterList = c.getParameterList();
ProducedType parameterTuple;
if (c.isClassOrInterfaceMember()||c.isToplevel()) {
parameterTuple = getParameterTypesAsTupleType(parameterList != null ?
parameterList.getParameters() :
Collections.<Parameter>emptyList(),
literalType);
}
else {
parameterTuple = new NothingType(this).getType();
}
if (literalType.getDeclaration().isMember()) {
return producedType(getLanguageModuleModelTypeDeclaration("MemberClass"),
literalType.getQualifyingType(), literalType, parameterTuple);
}
else {
return producedType(getLanguageModuleModelTypeDeclaration("Class"),
literalType, parameterTuple);
}
}
public ProducedType getInterfaceMetatype(ProducedType literalType) {
if (literalType.getDeclaration().isMember()) {
return producedType(getLanguageModuleModelTypeDeclaration("MemberInterface"),
literalType.getQualifyingType(), literalType);
}
else {
return producedType(getLanguageModuleModelTypeDeclaration("Interface"), literalType);
}
}
public ProducedType getTypeMetaType(ProducedType literalType) {
TypeDeclaration declaration = literalType.getDeclaration();
if (declaration instanceof UnionType) {
return producedType(getLanguageModuleModelTypeDeclaration("UnionType"), literalType);
}
else if (declaration instanceof IntersectionType) {
return producedType(getLanguageModuleModelTypeDeclaration("IntersectionType"), literalType);
}
else {
return producedType(getLanguageModuleModelTypeDeclaration("Type"), literalType);
}
}
public ProducedType getParameterTypesAsTupleType(List<Parameter> params,
ProducedReference pr) {
List<ProducedType> paramTypes = new ArrayList<ProducedType>(params.size());
int max = params.size()-1;
int firstDefaulted = -1;
boolean sequenced = false;
boolean atLeastOne = false;
for (int i=0; i<=max; i++) {
Parameter p = params.get(i);
ProducedType ft;
if (p.getModel() == null) {
ft = new UnknownType(this).getType();
}
else {
ft = pr.getTypedParameter(p).getFullType();
if (firstDefaulted<0 && p.isDefaulted()) {
firstDefaulted = i;
}
if (i==max && p.isSequenced()) {
sequenced = true;
atLeastOne = p.isAtLeastOne();
if (ft!=null) {
ft = getIteratedType(ft);
}
}
}
paramTypes.add(ft);
}
return getTupleType(paramTypes, sequenced, atLeastOne,
firstDefaulted);
}
public ProducedType getType(TypeDeclaration td) {
return td==null ? new UnknownType(this).getType() : td.getType();
}
public ProducedType getPackageDeclarationType() {
return getType(getLanguageModuleDeclarationTypeDeclaration("Package"));
}
public ProducedType getModuleDeclarationType() {
return getType(getLanguageModuleDeclarationTypeDeclaration("Module"));
}
public ProducedType getImportDeclarationType() {
return getType(getLanguageModuleDeclarationTypeDeclaration("Import"));
}
public ProducedType getClassDeclarationType() {
return getType(getLanguageModuleDeclarationTypeDeclaration("ClassDeclaration"));
}
public ProducedType getInterfaceDeclarationType() {
return getType(getLanguageModuleDeclarationTypeDeclaration("InterfaceDeclaration"));
}
public ProducedType getAliasDeclarationType() {
return getType(getLanguageModuleDeclarationTypeDeclaration("AliasDeclaration"));
}
public ProducedType getTypeParameterDeclarationType() {
return getType(getLanguageModuleDeclarationTypeDeclaration("TypeParameter"));
}
public ProducedType getFunctionDeclarationType() {
return getType(getLanguageModuleDeclarationTypeDeclaration("FunctionDeclaration"));
}
public ProducedType getValueDeclarationType(TypedDeclaration value) {
return getType(getLanguageModuleDeclarationTypeDeclaration("ValueDeclaration"));
}
public TypeDeclaration getAnnotationDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("Annotation");
}
public TypeDeclaration getConstrainedAnnotationDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("ConstrainedAnnotation");
}
public TypeDeclaration getSequencedAnnotationDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("SequencedAnnotation");
}
public TypeDeclaration getOptionalAnnotationDeclaration() {
return (TypeDeclaration) getLanguageModuleDeclaration("OptionalAnnotation");
}
public TypeDeclaration getDeclarationDeclaration() {
return getLanguageModuleDeclarationTypeDeclaration("Declaration");
}
public ProducedTypeCache getCache() {
Module module = getPackage().getModule();
return module != null ? module.getCache() : null;
}
}
|
package com.redhat.ceylon.compiler.typechecker.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Util {
/**
* Is the second scope contained by the first scope?
*/
public static boolean contains(Scope outer, Scope inner) {
while (inner!=null) {
if (inner.equals(outer)) {
return true;
}
inner = inner.getContainer();
}
return false;
}
/**
* Get the class or interface that "this" and "super"
* refer to.
*/
public static ClassOrInterface getContainingClassOrInterface(Scope scope) {
while (!(scope instanceof Package)) {
if (scope instanceof ClassOrInterface) {
return (ClassOrInterface) scope;
}
scope = scope.getContainer();
}
return null;
}
/**
* Get the class or interface that "outer" refers to.
*/
public static ProducedType getOuterClassOrInterface(Scope scope) {
Boolean foundInner = false;
while (!(scope instanceof Package)) {
if (scope instanceof ClassOrInterface) {
if (foundInner) {
return ((ClassOrInterface) scope).getType();
}
else {
foundInner = true;
}
}
scope = scope.getContainer();
}
return null;
}
/**
* Convenience method to bind a single type argument
* to a toplevel type declaration.
*/
public static ProducedType producedType(TypeDeclaration declaration, ProducedType typeArgument) {
return declaration.getProducedType(null, Collections.singletonList(typeArgument));
}
/**
* Convenience method to bind a list of type arguments
* to a toplevel type declaration.
*/
public static ProducedType producedType(TypeDeclaration declaration, ProducedType... typeArguments) {
return declaration.getProducedType(null, Arrays.asList(typeArguments));
}
static boolean isResolvable(Declaration declaration) {
return declaration.getName()!=null &&
!(declaration instanceof Setter) && //return getters, not setters
!(declaration instanceof Class &&
Character.isLowerCase(declaration.getName().charAt(0))); //don't return the type associated with an object dec
}
static boolean isParameter(Declaration d) {
return d instanceof Parameter
|| d instanceof TypeParameter;
}
static boolean notOverloaded(Declaration d) {
return !(d instanceof Functional) ||
!((Functional) d).isOverloaded() ||
((Functional) d).isAbstraction();
}
static boolean hasMatchingSignature(List<ProducedType> signature, Declaration d) {
if (d instanceof Class && ((Class) d).isAbstract()) {
return false;
}
if (d instanceof Functional) {
Functional f = (Functional) d;
if (f.isAbstraction()) {
return false;
}
else {
List<ParameterList> pls = f.getParameterLists();
if (pls!=null && !pls.isEmpty()) {
List<Parameter> params = pls.get(0).getParameters();
if (signature.size()!=params.size()) {
return false;
}
else {
for (int i=0; i<params.size(); i++) {
//ignore optionality for resolving overloads, since
//all all Java method params are treated as optional
ProducedType paramType = d.getUnit().getDefiniteType(params.get(i).getType());
ProducedType sigType = d.getUnit().getDefiniteType(signature.get(i));
TypeDeclaration paramTypeDec = paramType.getDeclaration();
TypeDeclaration sigTypeDec = sigType.getDeclaration();
if (sigTypeDec==null || paramTypeDec==null) return false;
if (sigTypeDec instanceof UnknownType || paramTypeDec instanceof UnknownType) return false;
if (!erase(sigTypeDec).inherits(erase(paramTypeDec)) &&
underlyingTypesUnequal(paramType, sigType)) {
return false;
}
}
return true;
}
}
else {
return false;
}
}
}
else {
return false;
}
}
private static boolean underlyingTypesUnequal(ProducedType paramType,
ProducedType sigType) {
return sigType.getUnderlyingType()==null ||
paramType.getUnderlyingType()==null ||
!sigType.getUnderlyingType().equals(paramType.getUnderlyingType());
}
static boolean betterMatch(Declaration d, Declaration r) {
if (d instanceof Functional && r instanceof Functional) {
List<ParameterList> dpls = ((Functional) d).getParameterLists();
List<ParameterList> rpls = ((Functional) r).getParameterLists();
if (dpls!=null&&!dpls.isEmpty() && rpls!=null&&!rpls.isEmpty()) {
List<Parameter> dpl = dpls.get(0).getParameters();
List<Parameter> rpl = rpls.get(0).getParameters();
if (dpl.size()==rpl.size()) {
for (int i=0; i<dpl.size(); i++) {
ProducedType paramType = d.getUnit().getDefiniteType(dpl.get(i).getType());
TypeDeclaration paramTypeDec = paramType.getDeclaration();
ProducedType otherType = d.getUnit().getDefiniteType(rpl.get(i).getType());
TypeDeclaration otherTypeDec = otherType.getDeclaration();
if (otherTypeDec==null || paramTypeDec==null) return false;
if (otherTypeDec instanceof UnknownType || paramTypeDec instanceof UnknownType) return false;
if (!erase(paramTypeDec).inherits(erase(otherTypeDec)) &&
underlyingTypesUnequal(paramType, otherType)) {
return false;
}
}
return true;
}
}
}
return false;
}
static boolean isNamed(String name, Declaration d) {
String dname = d.getName();
return dname!=null && dname.equals(name);
}
private static TypeDeclaration erase(TypeDeclaration paramType) {
if (paramType instanceof TypeParameter) {
if ( paramType.getSatisfiedTypes().isEmpty() ) {
return paramType.getExtendedTypeDeclaration();
}
else {
//TODO: is this actually correct? What is Java's
// rule here?
return paramType.getSatisfiedTypeDeclarations().get(0);
}
}
else if (paramType instanceof UnionType ||
paramType instanceof IntersectionType) {
//TODO: this is pretty sucky, cos in theory a
// union or intersection might be assignable
// to the parameter type with a typecast
return paramType.getUnit().getObjectDeclaration();
}
else {
return paramType;
}
}
static boolean isNameMatching(String startingWith, Declaration d) {
return d.getName()!=null &&
d.getName().toLowerCase().startsWith(startingWith.toLowerCase());
}
/**
* Collect together type arguments given a list of
* type arguments to a declaration and the receiving
* type.
*
* @return a map of type parameter to type argument
*
* @param declaration a declaration
* @param receivingType the receiving produced type
* of which the declaration is a member
* @param typeArguments explicit or inferred type
* arguments of the declaration
*/
static Map<TypeParameter,ProducedType> arguments(Declaration declaration,
ProducedType receivingType, List<ProducedType> typeArguments) {
Map<TypeParameter, ProducedType> map = getArgumentsOfOuterType(receivingType);
//now turn the type argument tuple into a
//map from type parameter to argument
if (declaration instanceof Generic) {
Generic g = (Generic) declaration;
for (int i=0; i<g.getTypeParameters().size(); i++) {
if (typeArguments.size()>i) {
map.put(g.getTypeParameters().get(i), typeArguments.get(i));
}
}
}
return map;
}
public static Map<TypeParameter, ProducedType> getArgumentsOfOuterType(
ProducedType receivingType) {
Map<TypeParameter, ProducedType> map = new HashMap<TypeParameter, ProducedType>();
//make sure we collect all type arguments
//from the whole qualified type!
ProducedType dt = receivingType;
while (dt!=null) {
map.putAll(dt.getTypeArguments());
dt = dt.getQualifyingType();
}
return map;
}
static <T> List<T> list(List<T> list, T element) {
List<T> result = new ArrayList<T>();
result.addAll(list);
result.add(element);
return result;
}
/**
* Helper method for eliminating duplicate types from
* lists of types that form a union type, taking into
* account that a subtype is a "duplicate" of its
* supertype.
*/
public static void addToUnion(List<ProducedType> list, ProducedType pt) {
if (pt==null) {
return;
}
ProducedType selfType = pt.getDeclaration().getSelfType();
if (selfType!=null) {
pt = selfType.substitute(pt.getTypeArguments()); //canonicalize type with self type to the self type
}
if (pt.getDeclaration() instanceof UnionType) {
for (ProducedType t: pt.getDeclaration().getCaseTypes() ) {
addToUnion( list, t.substitute(pt.getTypeArguments()) );
}
}
else {
Boolean included = pt.isWellDefined();
if (included) {
for (Iterator<ProducedType> iter = list.iterator(); iter.hasNext();) {
ProducedType t = iter.next();
if (pt.isSubtypeOf(t)) {
included = false;
break;
}
//TODO: I think in some very rare occasions
// this can cause stack overflows!
else if (pt.isSupertypeOf(t)) {
iter.remove();
}
}
}
if (included) {
list.add(pt);
}
}
}
/**
* Helper method for eliminating duplicate types from
* lists of types that form an intersection type, taking
* into account that a supertype is a "duplicate" of its
* subtype.
*/
public static void addToIntersection(List<ProducedType> list, ProducedType pt, Unit unit) {
if (pt==null) {
return;
}
ProducedType selfType = pt.getDeclaration().getSelfType();
if (selfType!=null) {
pt = selfType.substitute(pt.getTypeArguments()); //canonicalize type with self type to the self type
}
if (pt.getDeclaration() instanceof IntersectionType) {
for (ProducedType t: pt.getDeclaration().getSatisfiedTypes() ) {
addToIntersection(list, t.substitute(pt.getTypeArguments()), unit);
}
}
else {
//implement the rule that Foo&Bar==Bottom if
//there exists some Baz of Foo | Bar
//i.e. the intersection of disjoint types is
//empty
for (ProducedType supertype: pt.getSupertypes()) {
List<TypeDeclaration> ctds = supertype.getDeclaration().getCaseTypeDeclarations();
if (ctds!=null) {
TypeDeclaration ctd=null;
for (TypeDeclaration ct: ctds) {
if (pt.getSupertype(ct)!=null) {
ctd = ct;
break;
}
}
if (ctd!=null) {
for (TypeDeclaration ct: ctds) {
if (ct!=ctd) {
for (ProducedType t: list) {
if (t.getSupertype(ct)!=null) {
list.clear();
list.add( new BottomType(unit).getType() );
return;
}
}
}
}
}
}
}
Boolean included = pt.isWellDefined();
if (included) {
for (Iterator<ProducedType> iter = list.iterator(); iter.hasNext();) {
ProducedType t = iter.next();
if (pt.isSupertypeOf(t)) {
included = false;
break;
}
//TODO: I think in some very rare occasions
// this can cause stack overflows!
else if (pt.isSubtypeOf(t)) {
iter.remove();
}
else if ( pt.getDeclaration().equals(t.getDeclaration()) ) {
//canonicalize T<InX,OutX>&T<InY,OutY> to T<InX|InY,OutX&OutY>
TypeDeclaration td = pt.getDeclaration();
List<ProducedType> args = new ArrayList<ProducedType>();
for (int i=0; i<td.getTypeParameters().size(); i++) {
TypeParameter tp = td.getTypeParameters().get(i);
ProducedType pta = pt.getTypeArguments().get(tp);
ProducedType ta = t.getTypeArguments().get(tp);
if (tp.isContravariant()) {
args.add(unionType(pta, ta, unit));
}
else if (tp.isCovariant()) {
args.add(intersectionType(pta, ta, unit));
}
else {
TypeDeclaration ptad = pta.getDeclaration();
TypeDeclaration tad = ta.getDeclaration();
if ( !(ptad instanceof TypeParameter) &&
!(tad instanceof TypeParameter) &&
!ptad.equals(tad) ) {
//if the two type arguments have provably
//different types, then the meet of the
//two intersected invariant types is empty
//TODO: this is too weak, we should really
// recursively search for type parameter
// arguments and if we don't find any
// we can reduce to Bottom
list.clear();
args.add( new BottomType(unit).getType() );
return;
}
else {
//TODO: this is not correct: the intersection
// of two different instantiations of an
// invariant type is actually Bottom
// unless the type arguments are equivalent
// or are type parameters that might
// represent equivalent types at runtime.
// Therefore, a method T x(T y) of Inv<T>
// should have the signature:
// Foo&Bar x(Foo|Bar y)
// on the intersection Inv<Foo>&Inv<Bar>.
// But this code gives it the more
// restrictive signature:
// Foo&Bar x(Foo&Bar y)
args.add(intersectionType(pta, ta, unit));
}
}
}
iter.remove();
//TODO: broken handling of member types!
list.add( td.getProducedType(pt.getQualifyingType(), args) );
return;
}
else {
//Unit unit = pt.getDeclaration().getUnit();
TypeDeclaration nd = unit.getNothingDeclaration();
if (pt.getDeclaration() instanceof Class &&
t.getDeclaration() instanceof Class ||
pt.getDeclaration() instanceof Interface &&
t.getDeclaration().equals(nd) ||
//t.getDeclaration().getQualifiedNameString().equals("ceylon.language.Nothing") ||
t.getDeclaration() instanceof Interface &&
pt.getDeclaration().equals(nd)) {
//pt.getDeclaration().getQualifiedNameString().equals("ceylon.language.Nothing")) {
//the meet of two classes unrelated by inheritance, or
//of Nothing with an interface type is empty
list.clear();
list.add( unit.getBottomDeclaration().getType() );
return;
}
}
}
}
if (included) {
list.add(pt);
}
}
}
public static String formatPath(List<String> path) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<path.size(); i++) {
sb.append(path.get(i));
if (i<path.size()-1) sb.append('.');
}
return sb.toString();
}
static boolean addToSupertypes(List<ProducedType> list, ProducedType st) {
for (ProducedType et: list) {
if (st.getDeclaration().equals(et.getDeclaration()) && //return both a type and its self type
st.isExactly(et)) {
return false;
}
}
list.add(st);
return true;
}
public static ProducedType unionType(ProducedType lhst, ProducedType rhst, Unit unit) {
List<ProducedType> list = new ArrayList<ProducedType>();
addToUnion(list, rhst);
addToUnion(list, lhst);
UnionType ut = new UnionType(unit);
ut.setCaseTypes(list);
return ut.getType();
}
public static ProducedType intersectionType(ProducedType lhst, ProducedType rhst, Unit unit) {
List<ProducedType> list = new ArrayList<ProducedType>();
addToIntersection(list, rhst, unit);
addToIntersection(list, lhst, unit);
IntersectionType it = new IntersectionType(unit);
it.setSatisfiedTypes(list);
return it.canonicalize().getType();
}
public static boolean isElementOfUnion(UnionType ut, TypeDeclaration td) {
for (TypeDeclaration ct: ut.getCaseTypeDeclarations()) {
if (ct.equals(td)) return true;
}
return false;
}
public static boolean isElementOfIntersection(IntersectionType ut, TypeDeclaration td) {
for (TypeDeclaration ct: ut.getSatisfiedTypeDeclarations()) {
if (ct.equals(td)) return true;
}
return false;
}
public static Declaration lookupMember(List<Declaration> members, String name,
List<ProducedType> signature, boolean includeParameters) {
List<Declaration> results = new ArrayList<Declaration>();
Declaration inexactMatch = null;
for (Declaration d: members) {
if (isResolvable(d) && isNamed(name, d) &&
(includeParameters || !isParameter(d))) {
if (signature==null) {
//no argument types: either a type
//declaration, an attribute, or a method
//reference - don't return overloaded
//forms of the declaration (instead
//return the "abstraction" of them)
if (notOverloaded(d)) {
//by returning the first thing we
//find, we implement the rule that
//parameters hide attributes with
//the same name in the body of a
//class (a bit of a hack solution)
return d;
}
}
else {
if (notOverloaded(d)) {
//we have found either a non-overloaded
//declaration, or the "abstraction"
//which of all the overloaded forms
//of the declaration
inexactMatch = d;
}
if (hasMatchingSignature(signature, d)) {
//we have found an exactly matching
//overloaded declaration
boolean add=true;
for (Iterator<Declaration> i = results.iterator(); i.hasNext();) {
Declaration o = i.next();
if (betterMatch(d, o)) {
i.remove();
}
else if (betterMatch(o, d)) { //TODO: note assymmetry here resulting in nondeterminate behavior!
add=false;
}
}
if (add) results.add(d);
}
}
}
}
switch (results.size()) {
case 0:
//no exact match, so return the non-overloaded
//declaration or the "abstraction" of the
//overloaded declaration
return inexactMatch;
case 1:
//exactly one exact match, so return it
return results.get(0);
default:
//more than one matching overloaded declaration,
//so return the "abstraction" of the overloaded
//declaration
return inexactMatch;
}
}
}
|
package com.smartnsoft.droid4me.download;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.view.View;
public class BitmapDownloader
extends BasisBitmapDownloader
{
private static int preThreadCount;
// private final static class ImagePriorityBlockingQueue
// extends PriorityBlockingQueue<Runnable>
// @Override
// public boolean offer(Runnable runnable)
// // final int activePoolSize = BitmapDownloader.PRE_THREAD_POOL.getActiveCount();
// // if (activePoolSize >= BitmapDownloader.PRE_THREAD_POOL.getCorePoolSize() && activePoolSize <
// // BitmapDownloader.PRE_THREAD_POOL.getMaximumPoolSize())
// // return false;
// // return super.offer(runnable);
// return false;
// public void add(Runnable runnable, boolean forceAddition)
// super.offer(runnable);
// private final static BitmapDownloader.ImagePriorityBlockingQueue PRE_BLOCKING_QUEUE = new BitmapDownloader.ImagePriorityBlockingQueue();
private final static ThreadPoolExecutor PRE_THREAD_POOL = new ThreadPoolExecutor(2, 3, 5l, TimeUnit.SECONDS, new PriorityBlockingQueue<Runnable>(), new ThreadFactory()
{
public Thread newThread(Runnable runnable)
{
final Thread thread = new Thread(runnable);
thread.setName("droid4me-" + (BitmapDownloader.preThreadCount < BitmapDownloader.PRE_THREAD_POOL.getCorePoolSize() ? "core-" : "") + "pre #" + BitmapDownloader.preThreadCount++);
return thread;
}
}, /*
* new RejectedExecutionHandler() { public void rejectedExecution(Runnable command, ThreadPoolExecutor executor) {
* BitmapDownloader.PRE_BLOCKING_QUEUE.add(command, true); } }
*/new ThreadPoolExecutor.AbortPolicy());
private static int downloadThreadCount;
@SuppressWarnings("serial")
private final static ThreadPoolExecutor DOWNLOAD_THREAD_POOL = new ThreadPoolExecutor(2, 4, 5l, TimeUnit.SECONDS, new PriorityBlockingQueue<Runnable>()
{
// @Override
// public boolean offer(Runnable runnable)
// final int activePoolSize = BitmapDownloader.DOWNLOAD_THREAD_POOL.getActiveCount();
// if (activePoolSize >= BitmapDownloader.DOWNLOAD_THREAD_POOL.getCorePoolSize() && activePoolSize <
// BitmapDownloader.DOWNLOAD_THREAD_POOL.getMaximumPoolSize())
// return false;
// return super.offer(runnable);
}, new ThreadFactory()
{
public Thread newThread(Runnable runnable)
{
final Thread thread = new Thread(runnable);
thread.setName("droid4me-" + (BitmapDownloader.downloadThreadCount < BitmapDownloader.DOWNLOAD_THREAD_POOL.getCorePoolSize() ? "core-" : "") + "download #" + BitmapDownloader.downloadThreadCount++);
return thread;
}
}, new ThreadPoolExecutor.AbortPolicy());
private static int commandsCount;
private abstract class BasisCommand
implements Runnable, Comparable<BitmapDownloader.BasisCommand>
{
private final int order = BitmapDownloader.commandsCount++;
protected final int id;
protected final View view;
protected final String bitmapUid;
protected final Object imageSpecs;
protected final Handler handler;
protected final BasisBitmapDownloader.Instructions instructions;
protected BasisBitmapDownloader.UsedBitmap usedBitmap;
private boolean executeEnd;
public BasisCommand(int id, View view, String bitmapUid, Object imageSpecs, Handler handler, BasisBitmapDownloader.Instructions instructions)
{
this(id, view, bitmapUid, imageSpecs, handler, instructions, false);
}
public BasisCommand(int id, View view, String bitmapUid, Object imageSpecs, Handler handler, BasisBitmapDownloader.Instructions instructions,
boolean executeEnd)
{
this.id = id;
this.view = view;
this.bitmapUid = bitmapUid;
this.imageSpecs = imageSpecs;
this.handler = handler;
this.instructions = instructions;
this.executeEnd = executeEnd;
}
protected abstract void executeStart(boolean isFromGuiThread);
protected abstract void executeEnd();
/**
* Introduced in order to reduce the allocation of a {@link Runnable}, and for an optimization purpose.
*
* <p>
* The {@link BitmapDownloader.PreCommand#view} is ensured not to be null when this method is invoked.
* </p>
*/
public final void run()
{
try
{
if (executeEnd == false)
{
executeEnd = true;
executeStart(false);
}
else
{
executeEnd();
}
}
catch (Throwable throwable)
{
if (log.isErrorEnabled())
{
log.error("An unhandled exception has been raised during the processing of a command", throwable);
}
}
}
public int compareTo(BitmapDownloader.BasisCommand other)
{
return other.order - order;
}
}
// TODO: define a pool of Command objects, so as to minimize GC, if possible
private class PreCommand
extends BitmapDownloader.BasisCommand
{
/**
* <ol>
* <li><code>0</code>: the bitmap is taken from the local resources, and the command is over;</li>
* <li><code>1</code>: the bitmap was already in the memory cache, and the command is over;</li>
* <li><code>2</code>: the bitmap needs to be downloaded, and a download-command will be triggered.</li>
* </ol>
*/
private int state;
public PreCommand(int id, View view, String bitmapUid, Object imageSpecs, Handler handler, BasisBitmapDownloader.Instructions instructions)
{
super(id, view, bitmapUid, imageSpecs, handler, instructions);
}
public PreCommand(int id, View view, String bitmapUid, Object imageSpecs, Handler handler, BasisBitmapDownloader.Instructions instructions,
boolean executeEnd)
{
super(id, view, bitmapUid, imageSpecs, handler, instructions, executeEnd);
}
@Override
protected void executeStart(boolean isFromGuiThread)
{
// if (log.isDebugEnabled())
// log.debug("Starting to handle the drawable for the bitmap with identifier '" + bitmapUid + "'");
// The command is removed from the priority stack
if (view != null)
{
prioritiesPreStack.remove(view);
}
// We set a local bitmap if available
if (setLocalBitmapIfPossible(isFromGuiThread) == true)
{
return;
}
// We compute the bitmap URL and proceed
final String url = instructions.computeUrl(bitmapUid, imageSpecs);
// We use a bitmap from the cache if possible
if (setBitmapFromCacheIfPossible(url, isFromGuiThread) == true)
{
return;
}
// We set a temporary bitmap, if available
setTemporaryBitmapIfPossible(isFromGuiThread);
// TODO: handle the special case of the null imageUid is more clever and optimized way
// if (url == null)
// // We do not want to go any further, since the URL is null
// return;
downloadBitmap(url);
}
@Override
protected void executeEnd()
{
// if (log.isDebugEnabled())
// log.debug("Running the action in state '" + state + "'");
// We only continue the process (and the temporary or local bitmap view binding) provided there is not already another command bound to be
// processed
// for the same view
Integer commandId = prioritiesStack.get(view);
if (state != 2 && (commandId == null || commandId != id))
{
if (log.isDebugEnabled())
{
log.debug("The bitmap corresponding to the id '" + bitmapUid + "' will not be bound to its view, because this bitmap has asked for another bitmap URL in the meantime");
}
return;
}
try
{
switch (state)
{
case 0:
instructions.onBindLocalBitmap(view, bitmapUid, imageSpecs);
instructions.onBitmapBound(true, view, bitmapUid, imageSpecs);
// if (log.isDebugEnabled())
// log.debug("Set the local drawable for the bitmap with id '" + bitmapUid + "'");
break;
case 1:
if (instructions.onBindBitmap(false, view, usedBitmap.getBitmap(), bitmapUid, imageSpecs) == false)
{
// The binding is performed only if the instructions did not bind it
// THINK: what can we do?
// view.setImageBitmap(usedBitmap.getBitmap());
}
usedBitmap.forgetBitmap();
usedBitmap.rememberBinding(view);
instructions.onBitmapBound(true, view, bitmapUid, imageSpecs);
// if (log.isDebugEnabled())
// log.debug("Set the cached bitmap for the bitmap with id '" + bitmapUid + "'");
break;
case 2:
instructions.onBindTemporaryBitmap(view, bitmapUid, imageSpecs);
// if (log.isDebugEnabled())
// log.debug("Set the temporary drawable for the bitmap with id '" + bitmapUid + "'");
break;
}
// We clear the priorities stack if the work is over for that command (i.e. no DownloadBitmapCommand is required)
commandId = prioritiesStack.get(view);
if (state != 2 && commandId == id)
{
prioritiesStack.remove(view);
}
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn("Process exceeding available memory", exception);
}
cleanUpCache();
}
}
private boolean setLocalBitmapIfPossible(boolean isFromGuiThread)
{
if (instructions.hasLocalBitmap(bitmapUid, imageSpecs) == true)
{
if (view != null)
{
// We need to do that in the GUI thread!
state = 0;
if (isFromGuiThread == false)
{
if (handler.post(this) == false)
{
if (log.isWarnEnabled())
{
log.warn("Failed to apply that local resource for the bitmap with id '" + bitmapUid + "' from the GUI thread");
}
}
}
else
{
run();
}
return true;
}
}
return false;
}
private void setTemporaryBitmapIfPossible(boolean isFromGuiThread)
{
if (instructions.hasTemporaryBitmap(bitmapUid, imageSpecs) == true)
{
if (view != null)
{
// We need to do that in the GUI thread!
state = 2;
if (isFromGuiThread == false)
{
if (handler.post(this) == false)
{
if (log.isWarnEnabled())
{
log.warn("Failed to apply that temporary local resource for the bitmap with id '" + bitmapUid + "' from the GUI thread");
}
}
}
else
{
run();
}
}
}
}
private boolean setBitmapFromCacheIfPossible(String url, boolean isFromGuiThread)
{
// There is a special case when the bitmap URL is null
if (url == null)
{
// We do not want to attempt retrieving a cached bitmap corresponding to a null URL
return false;
}
// We check that the bitmap is no already in the cache
final BasisBitmapDownloader.UsedBitmap otherUsedBitmap = getUsedBitmapFromCache(url);
if (otherUsedBitmap != null)
{
usedBitmap = otherUsedBitmap;
usedBitmap.rememberAccessed();
instructions.onBitmapReady(true, view, usedBitmap.getBitmap(), bitmapUid, imageSpecs);
if (view != null)
{
// if (log.isDebugEnabled())
// log.debug("Re-using the cached bitmap for the URL '" + url + "'");
// It is possible that no bitmap exists for that URL
// We need to do that in the GUI thread!
state = 1;
if (isFromGuiThread == false)
{
if (handler.post(this) == false)
{
if (log.isWarnEnabled())
{
log.warn("Failed to apply that cached bitmap for the URL '" + url + "' from the GUI thread");
}
}
}
else
{
run();
}
}
else
{
// if (log.isDebugEnabled())
// log.debug("The bitmap corresponding to the URL '" + url + "' is null: no need to apply its cached bitmap");
}
return true;
}
return false;
}
private void downloadBitmap(final String url)
{
// We want to remove any pending download command for the view
if (view != null)
{
// But we test whether the download is still required
final Integer commandId = prioritiesStack.get(view);
if (commandId == null || commandId != id)
{
return;
}
// We remove a previously stacked command for the same view
final BitmapDownloader.PreCommand alreadyStackedCommand = prioritiesDownloadStack.get(view);
if (alreadyStackedCommand != null)
{
if (log.isDebugEnabled())
{
log.debug("Removed an already stacked download command corresponding to the view with id '" + view.getId() + "'");
}
if (BitmapDownloader.DOWNLOAD_THREAD_POOL.remove(alreadyStackedCommand) == false)
{
if (log.isErrorEnabled())
{
log.error("Could not find the download command relative to the view with id '" + bitmapUid + "' when attempting to remove it!");
}
}
}
}
// We need to download the bitmap or take it from a local persistence place
// Hence, we stack the bitmap download command
final BitmapDownloader.DownloadBitmapCommand downloadCommand = computeDownloadBitmapCommand(id, view, url, bitmapUid, imageSpecs, handler, instructions);
if (view != null)
{
prioritiesDownloadStack.put(view, downloadCommand);
}
BitmapDownloader.DOWNLOAD_THREAD_POOL.execute(downloadCommand);
}
}
// TODO: when a second download for the same bitmap UID occurs, do not run it
protected class DownloadBitmapCommand
extends BitmapDownloader.PreCommand
implements BasisBitmapDownloader.InputStreamDownloadInstructor
{
protected final String url;
private boolean downloaded;
private boolean inputStreamAsynchronous;
public DownloadBitmapCommand(int id, View view, String url, String bitmapUid, Object imageSpecs, Handler handler,
BasisBitmapDownloader.Instructions instructions)
{
super(id, view, bitmapUid, imageSpecs, handler, instructions);
this.url = url;
}
@Override
protected void executeStart(boolean isFromGuiThread)
{
// The command is removed from the priority stack
if (view != null)
{
prioritiesDownloadStack.remove(view);
}
// We need to check whether the same URL has not been downloaded in the meantime
final BasisBitmapDownloader.UsedBitmap otherUsedBitmap = getUsedBitmapFromCache(url);
if (otherUsedBitmap == null)
{
// If the bitmap is not already in memory, we load it in memory
final Bitmap bitmap = retrieveBitmap();
if (bitmap == null)
{
// This happens either when the bitmap URL is null, or when the bitmap retrieval failed
if (inputStreamAsynchronous == false)
{
if (url != null && url.length() >= 1)
{
if (log.isWarnEnabled())
{
log.warn("The bitmap relative to the URL '" + url + "' is null");
}
}
}
// We let intentionally the 'usedBitmap' null
}
else
{
usedBitmap = putInCache(url, bitmap);
}
}
else
{
// Otherwise, we reuse it
usedBitmap = otherUsedBitmap;
usedBitmap.rememberAccessed();
}
instructions.onBitmapReady(true, view, usedBitmap == null ? null : usedBitmap.getBitmap(), bitmapUid, imageSpecs);
bindBitmap();
}
/**
* The {@link BitmapDownloader.PreCommand#view} is ensured not to be null when this method is invoked.
*/
@Override
protected void executeEnd()
{
// We only bind the bitmap to the view provided there is not already another command bound to be processed
Integer commandId = prioritiesStack.get(view);
if (commandId == null || commandId != id)
{
// if (log.isDebugEnabled())
// log.debug("The bitmap corresponding to the URL '" + url +
// "' will not be bound to its view, because this view has asked for another bitmap URL in the meantime");
return;
}
try
{
if (usedBitmap != null)
{
if (instructions.onBindBitmap(downloaded, view, usedBitmap.getBitmap(), bitmapUid, imageSpecs) == false)
{
// The binding is performed only if the instructions did not bind it
// THINK: what can we do?
// view.setImageBitmap(usedBitmap.getBitmap());
}
usedBitmap.forgetBitmap();
usedBitmap.rememberBinding(view);
}
instructions.onBitmapBound(usedBitmap != null, view, bitmapUid, imageSpecs);
// We clear the priorities stack if the work is over for that command (i.e. no DownloadBitmapCommand is required)
commandId = prioritiesStack.get(view);
if (commandId != null && commandId == id)
{
prioritiesStack.remove(view);
}
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn("Process exceeding available memory", exception);
}
cleanUpCache();
}
}
public final void setAsynchronous()
{
inputStreamAsynchronous = true;
}
public final void onDownloaded(InputStream inputStream)
{
try
{
inputStream = onInputStreamDownloaded(inputStream);
downloaded = true;
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn("Process exceeding available memory", exception);
}
cleanUpCache();
return;
}
// Indicates whether another command has been set for the view in the meantime
final boolean forgetTheBinding = view != null && asynchronousDownloadCommands.remove(view) == false;
final Bitmap bitmap = convertInputStream(inputStream);
if (forgetTheBinding == false && bitmap == null)
{
instructions.onBitmapReady(false, view, null, bitmapUid, imageSpecs);
return;
}
usedBitmap = putInCache(url, bitmap);
if (forgetTheBinding == false)
{
instructions.onBitmapReady(true, view, usedBitmap.getBitmap(), bitmapUid, imageSpecs);
bindBitmap();
}
}
/**
* @return <code>null</code>, in particular, when either if the URL is null or empty
* @throws IOException
* if an IO problem occurred while retrieving the bitmap stream
*/
private final InputStream fetchInputStream()
throws IOException
{
InputStream inputStream = null;
// We do not event attempt to request for the input stream if the bitmap URI is null or empty
if (url != null && url.length() >= 1)
{
try
{
inputStream = instructions.getInputStream(bitmapUid, imageSpecs, url, this);
}
catch (IOException exception)
{
if (log.isWarnEnabled())
{
log.warn("Could not get the provided input stream corresponding to the URL '" + url + "'", exception);
}
// In that case, we consider that the input stream custom download was a failure
throw exception;
}
}
else
{
return null;
}
if (inputStream != null)
{
// if (log.isDebugEnabled())
// log.debug("Using the provided input stream corresponding to the URL '" + url + "'");
return inputStream;
}
// We determine whether the input stream has turned asynchronous
if (inputStreamAsynchronous == true)
{
asynchronousDownloadCommands.add(view);
return null;
}
final long start = System.currentTimeMillis();
final URL aURL = new URL(url);
final URLConnection connection = aURL.openConnection();
instructions.onBeforeBitmapDownloaded(bitmapUid, imageSpecs, connection);
// if (log.isDebugEnabled())
// log.debug("Setting to the URL connection belonging to class '" + connection.getClass().getName() + "' a 'User-Agent' header property");
connection.connect();
final long stop = System.currentTimeMillis();
inputStream = connection.getInputStream();
if (log.isDebugEnabled())
{
log.debug("The thread '" + Thread.currentThread().getName() + "' downloaded in " + (stop - start) + " ms the bitmap relative to the URL '" + url + "'");
}
try
{
inputStream = onInputStreamDownloaded(inputStream);
downloaded = true;
return inputStream;
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn("Process exceeding available memory", exception);
}
cleanUpCache();
return null;
}
}
/**
* @return <code>null</code>, in particular, if the underlying bitmap URL is null or empty
*/
private final Bitmap retrieveBitmap()
{
final InputStream inputStream;
try
{
inputStream = fetchInputStream();
}
catch (IOException exception)
{
if (log.isWarnEnabled())
{
log.warn("Could not access to the bitmap URL '" + url + "'");
}
return null;
}
if (inputStream == null)
{
if (inputStreamAsynchronous == false)
{
if (url != null && url.length() >= 1)
{
if (log.isWarnEnabled())
{
log.warn("The input stream used to build the bitmap corresponding to the URL '" + url + "' is null");
}
}
}
return null;
}
try
{
return convertInputStream(inputStream);
}
finally
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException exception)
{
// Does not matter
}
}
}
}
protected InputStream onInputStreamDownloaded(InputStream inputStream)
{
return inputStream;
}
private final Bitmap convertInputStream(InputStream inputStream)
{
final Bitmap theBitmap;
try
{
// final long start = System.currentTimeMillis();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
options.inDither = false;
options.inDensity = 0;
theBitmap = BitmapFactory.decodeStream(inputStream, null, options);
// final long stop = System.currentTimeMillis();
// if (log.isDebugEnabled() && bitmap != null)
// log.debug("The thread '" + Thread.currentThread().getName() + "' decoded in " + (stop - start) + " ms the bitmap with density " +
// theBitmap.getDensity() + " relative to the URL '" + url + "'");
return theBitmap;
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn("Cannot decode the downloaded bitmap because it exceeds the allowed memory", exception);
}
cleanUpCache();
return null;
}
}
private final void bindBitmap()
{
// We need to bind the bitmap to the view in the GUI thread!
if (view != null)
{
if (handler.post(this) == false)
{
if (log.isWarnEnabled())
{
log.warn("Failed to apply the downloaded bitmap for the bitmap with id '" + bitmapUid + "' and URL '" + url + "' from the GUI thread");
}
}
}
}
}
public static int INSTANCES_COUNT = 1;
/**
* The fully qualified name of the {@link BitmapDownloader} instances implementation.
*/
public static String IMPLEMENTATION_FQN = BitmapDownloader.class.getName();
/**
* Indicates the upper limit of memory that each cache is allowed to reach.
*/
public static long[] MAX_MEMORY_IN_BYTES;
/**
* When the cache is being cleaned-up, indicates the lower limit of memory that each cache is allowed to reach.
*/
public static long[] LOW_LEVEL_MEMORY_WATER_MARK_IN_BYTES;
/**
* Indicates whether the instances should let the Java garbage collector handle bitmap soft references.
*/
public static boolean[] USE_REFERENCES;
public static boolean[] RECYCLE_BITMAP;
private static volatile BitmapDownloader[] instances;
/**
* Implements a "double-checked locking" pattern.
*/
public static BitmapDownloader getInstance()
{
return BitmapDownloader.getInstance(0);
}
// We accept the "out-of-order writes" case
@SuppressWarnings("unchecked")
public static BitmapDownloader getInstance(int position)
{
if (BitmapDownloader.instances == null)
{
synchronized (BitmapDownloader.class)
{
if (BitmapDownloader.instances == null)
{
try
{
final Class<? extends BitmapDownloader> implementationClass = (Class<? extends BitmapDownloader>) Class.forName(BitmapDownloader.IMPLEMENTATION_FQN);
final BitmapDownloader[] newInstances = (BitmapDownloader[]) Array.newInstance(implementationClass, BitmapDownloader.INSTANCES_COUNT);
final Constructor<? extends BitmapDownloader> constructor = implementationClass.getDeclaredConstructor(String.class, long.class, long.class,
boolean.class, boolean.class);
for (int index = 0; index < BitmapDownloader.INSTANCES_COUNT; index++)
{
newInstances[index] = constructor.newInstance("BitmapDownloader-" + index, BitmapDownloader.MAX_MEMORY_IN_BYTES[index],
BitmapDownloader.LOW_LEVEL_MEMORY_WATER_MARK_IN_BYTES[index], BitmapDownloader.USE_REFERENCES[index], BitmapDownloader.RECYCLE_BITMAP[index]);
}
// We only assign the instances class variable here, once all instances have actually been created
BitmapDownloader.instances = newInstances;
}
catch (Exception exception)
{
if (log.isFatalEnabled())
{
log.fatal("Cannot instantiate properly the BitmapDownloader instances", exception);
}
}
}
}
}
return BitmapDownloader.instances[position];
}
/**
* A map which handles the priorities of the {@link BitmapDownloader.PreCommand pre-commands}: when a new command for an {@link View} is asked for,
* if a {@link BitmapDownloader.PreCommand} is already stacked for the same view (i.e. present in {@link #preStack stacked}), the old one will be
* discarded.
*/
private final Map<View, BitmapDownloader.PreCommand> prioritiesPreStack;
/**
* A map which contains all the {@link BitmapDownloader.PreCommand commands} that are currently at the top of the priorities stack. When a new
* command for an {@link View} is asked for, if a {@link BitmapDownloader.PreCommand} is already stacked for the same view (i.e. present in
* {@link BitmapDownloader#preStack stacked}), the old one will be discarded.
*/
private final Map<View, Integer> prioritiesStack;
private final Map<View, BitmapDownloader.DownloadBitmapCommand> prioritiesDownloadStack;
private final Set<View> asynchronousDownloadCommands = new HashSet<View>();
/**
* The counter of all commands, which is incremented on every new command, so as to identify them.
*/
private int commandIdCount = -1;
protected BitmapDownloader(String name, long maxMemoryInBytes, long lowLevelMemoryWaterMarkInBytes, boolean useReferences, boolean recycleMap)
{
super(name, maxMemoryInBytes, lowLevelMemoryWaterMarkInBytes, useReferences, recycleMap);
prioritiesStack = new Hashtable<View, Integer>();
prioritiesPreStack = new Hashtable<View, BitmapDownloader.PreCommand>();
prioritiesDownloadStack = new Hashtable<View, BitmapDownloader.DownloadBitmapCommand>();
}
@Override
public final void get(View view, String bitmapUid, Object imageSpecs, Handler handler, BasisBitmapDownloader.Instructions instructions)
{
// if (log.isDebugEnabled())
// log.debug("Asking to handle the bitmap with id '" + bitmapUid + "'");
// try
if (view != null)
{
// We indicate to the potential asynchronous input stream downloads that a new request is now set for the bitmap
asynchronousDownloadCommands.remove(view);
// We remove a previously stacked command for the same view
final BitmapDownloader.PreCommand alreadyStackedCommand = prioritiesPreStack.get(view);
if (alreadyStackedCommand != null)
{
if (log.isDebugEnabled())
{
log.debug("Removed an already stacked command corresponding to the view with id '" + view.getId() + "'");
}
if (BitmapDownloader.PRE_THREAD_POOL.remove(alreadyStackedCommand) == false)
{
if (log.isErrorEnabled())
{
log.error("Could not find the pre-command relative to the view with id '" + bitmapUid + "' to remove it!");
}
}
}
}
final BitmapDownloader.PreCommand command = new BitmapDownloader.PreCommand(++commandIdCount, view, bitmapUid, imageSpecs, handler, instructions);
if (view != null)
{
prioritiesStack.put(view, command.id);
prioritiesPreStack.put(view, command);
}
BitmapDownloader.PRE_THREAD_POOL.execute(command);
}
@Override
public final void get(boolean isBlocking, View view, String bitmapUid, Object imageSpecs, Handler handler, BasisBitmapDownloader.Instructions instructions)
{
if (isBlocking == false)
{
get(view, bitmapUid, imageSpecs, handler, instructions);
}
else
{
final BitmapDownloader.PreCommand preCommand = new BitmapDownloader.PreCommand(++commandIdCount, view, bitmapUid, imageSpecs, handler, instructions, true);
if (view != null)
{
prioritiesStack.put(view, preCommand.id);
prioritiesPreStack.put(view, preCommand);
}
preCommand.executeStart(true);
}
}
public synchronized void empty()
{
if (log.isInfoEnabled())
{
log.info("Clearing the cache '" + name + "'");
}
BitmapDownloader.PRE_THREAD_POOL.getQueue().clear();
BitmapDownloader.DOWNLOAD_THREAD_POOL.getQueue().clear();
asynchronousDownloadCommands.clear();
prioritiesStack.clear();
prioritiesPreStack.clear();
prioritiesDownloadStack.clear();
cache.clear();
}
protected DownloadBitmapCommand computeDownloadBitmapCommand(int id, View view, String url, String bitmapUid, Object imageSpecs, Handler handler,
BasisBitmapDownloader.Instructions instructions)
{
return new BitmapDownloader.DownloadBitmapCommand(id, view, url, bitmapUid, imageSpecs, handler, instructions);
}
}
|
package com.thaiopensource.relaxng.parse.sax;
import com.thaiopensource.relaxng.parse.DataPatternBuilder;
import com.thaiopensource.relaxng.parse.Grammar;
import com.thaiopensource.relaxng.parse.GrammarSection;
import com.thaiopensource.relaxng.parse.IllegalSchemaException;
import com.thaiopensource.relaxng.parse.Include;
import com.thaiopensource.relaxng.parse.IncludedGrammar;
import com.thaiopensource.relaxng.parse.Location;
import com.thaiopensource.relaxng.parse.ParsedNameClass;
import com.thaiopensource.relaxng.parse.ParsedPattern;
import com.thaiopensource.relaxng.parse.SchemaBuilder;
import com.thaiopensource.relaxng.parse.Scope;
import com.thaiopensource.relaxng.parse.Annotations;
import com.thaiopensource.relaxng.parse.Context;
import com.thaiopensource.relaxng.parse.CommentList;
import com.thaiopensource.relaxng.parse.Div;
import com.thaiopensource.relaxng.parse.ElementAnnotationBuilder;
import com.thaiopensource.relaxng.parse.ParsedElementAnnotation;
import com.thaiopensource.relaxng.parse.ParsedPatternFuture;
import com.thaiopensource.util.Uri;
import com.thaiopensource.util.Localizer;
import com.thaiopensource.xml.util.Naming;
import com.thaiopensource.xml.util.WellKnownNamespaces;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Stack;
class SchemaParser implements ParsedPatternFuture {
private static final String relaxngURIPrefix =
WellKnownNamespaces.RELAX_NG.substring(0, WellKnownNamespaces.RELAX_NG.lastIndexOf('/') + 1);
static final String relaxng10URI = WellKnownNamespaces.RELAX_NG;
private static final Localizer localizer = new Localizer(SchemaParser.class);
private String relaxngURI;
private final XMLReader xr;
private final ErrorHandler eh;
private final SchemaBuilder schemaBuilder;
private ParsedPattern startPattern;
private Locator locator;
private final XmlBaseHandler xmlBaseHandler = new XmlBaseHandler();
private final ContextImpl context = new ContextImpl();
private boolean hadError = false;
private Hashtable patternTable;
private Hashtable nameClassTable;
static class PrefixMapping {
final String prefix;
final String uri;
final PrefixMapping next;
PrefixMapping(String prefix, String uri, PrefixMapping next) {
this.prefix = prefix;
this.uri = uri;
this.next = next;
}
}
static abstract class AbstractContext extends DtdContext implements Context {
PrefixMapping prefixMapping;
AbstractContext() {
prefixMapping = new PrefixMapping("xml", WellKnownNamespaces.XML, null);
}
AbstractContext(AbstractContext context) {
super(context);
prefixMapping = context.prefixMapping;
}
public String resolveNamespacePrefix(String prefix) {
for (PrefixMapping p = prefixMapping; p != null; p = p.next)
if (p.prefix.equals(prefix))
return p.uri;
return null;
}
public Enumeration prefixes() {
Vector v = new Vector();
for (PrefixMapping p = prefixMapping; p != null; p = p.next) {
if (!v.contains(p.prefix))
v.addElement(p.prefix);
}
return v.elements();
}
public Context copy() {
return new SavedContext(this);
}
}
static class SavedContext extends AbstractContext {
private final String baseUri;
SavedContext(AbstractContext context) {
super(context);
this.baseUri = context.getBaseUri();
}
public String getBaseUri() {
return baseUri;
}
}
class ContextImpl extends AbstractContext {
public String getBaseUri() {
return xmlBaseHandler.getBaseUri();
}
}
static interface CommentHandler {
void comment(String value);
}
abstract class Handler implements ContentHandler, CommentHandler {
CommentList comments;
CommentList getComments() {
CommentList tem = comments;
comments = null;
return tem;
}
public void comment(String value) {
if (comments == null)
comments = schemaBuilder.makeCommentList();
comments.addComment(value, makeLocation());
}
public void processingInstruction(String target, String date) { }
public void skippedEntity(String name) { }
public void ignorableWhitespace(char[] ch, int start, int len) { }
public void startDocument() { }
public void endDocument() { }
public void startPrefixMapping(String prefix, String uri) {
context.prefixMapping = new PrefixMapping(prefix, uri, context.prefixMapping);
}
public void endPrefixMapping(String prefix) {
context.prefixMapping = context.prefixMapping.next;
}
public void setDocumentLocator(Locator loc) {
locator = loc;
xmlBaseHandler.setLocator(loc);
}
}
abstract class State extends Handler {
State parent;
String nsInherit;
String ns;
String datatypeLibrary;
Scope scope;
Location startLocation;
Annotations annotations;
void set() {
xr.setContentHandler(this);
}
abstract State create();
abstract State createChildState(String localName) throws SAXException;
void setParent(State parent) {
this.parent = parent;
this.nsInherit = parent.getNs();
this.datatypeLibrary = parent.datatypeLibrary;
this.scope = parent.scope;
this.startLocation = makeLocation();
if (parent.comments != null) {
annotations = schemaBuilder.makeAnnotations(parent.comments, getContext());
parent.comments = null;
}
else if (parent instanceof RootState)
annotations = schemaBuilder.makeAnnotations(null, getContext());
}
String getNs() {
return ns == null ? nsInherit : ns;
}
boolean isRelaxNGElement(String uri) throws SAXException {
return uri.equals(relaxngURI);
}
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
xmlBaseHandler.startElement();
if (isRelaxNGElement(namespaceURI)) {
State state = createChildState(localName);
if (state == null) {
xr.setContentHandler(new Skipper(this));
return;
}
state.setParent(this);
state.set();
state.attributes(atts);
}
else {
checkForeignElement();
ForeignElementHandler feh = new ForeignElementHandler(this, getComments());
feh.startElement(namespaceURI, localName, qName, atts);
xr.setContentHandler(feh);
}
}
public void endElement(String namespaceURI,
String localName,
String qName) throws SAXException {
xmlBaseHandler.endElement();
parent.set();
end();
}
void setName(String name) throws SAXException {
error("illegal_name_attribute");
}
void setOtherAttribute(String name, String value) throws SAXException {
error("illegal_attribute_ignored", name);
}
void endAttributes() throws SAXException {
}
void checkForeignElement() throws SAXException {
}
void attributes(Attributes atts) throws SAXException {
int len = atts.getLength();
for (int i = 0; i < len; i++) {
String uri = atts.getURI(i);
if (uri.length() == 0) {
String name = atts.getLocalName(i);
if (name.equals("name"))
setName(atts.getValue(i).trim());
else if (name.equals("ns"))
ns = atts.getValue(i);
else if (name.equals("datatypeLibrary")) {
datatypeLibrary = atts.getValue(i);
checkUri(datatypeLibrary);
if (!datatypeLibrary.equals("")
&& !Uri.isAbsolute(datatypeLibrary))
error("relative_datatype_library");
if (Uri.hasFragmentId(datatypeLibrary))
error("fragment_identifier_datatype_library");
datatypeLibrary = Uri.escapeDisallowedChars(datatypeLibrary);
}
else
setOtherAttribute(name, atts.getValue(i));
}
else if (uri.equals(relaxngURI))
error("qualified_attribute", atts.getLocalName(i));
else if (uri.equals(WellKnownNamespaces.XML)
&& atts.getLocalName(i).equals("base"))
xmlBaseHandler.xmlBaseAttribute(atts.getValue(i));
else {
if (annotations == null)
annotations = schemaBuilder.makeAnnotations(null, getContext());
annotations.addAttribute(uri, atts.getLocalName(i), findPrefix(atts.getQName(i), uri),
atts.getValue(i), startLocation);
}
}
endAttributes();
}
abstract void end() throws SAXException;
void endChild(ParsedPattern pattern) {
// XXX cannot happen; throw exception
}
void endChild(ParsedNameClass nc) {
// XXX cannot happen; throw exception
}
public void startDocument() { }
public void endDocument() {
if (comments != null && startPattern != null) {
startPattern = schemaBuilder.commentAfter(startPattern, comments);
comments = null;
}
}
public void characters(char[] ch, int start, int len) throws SAXException {
for (int i = 0; i < len; i++) {
switch(ch[start + i]) {
case ' ':
case '\r':
case '\n':
case '\t':
break;
default:
error("illegal_characters_ignored");
break;
}
}
}
boolean isPatternNamespaceURI(String s) {
return s.equals(relaxngURI);
}
void endForeignChild(ParsedElementAnnotation ea) {
if (annotations == null)
annotations = schemaBuilder.makeAnnotations(null, getContext());
annotations.addElement(ea);
}
void mergeLeadingComments() {
if (comments != null) {
if (annotations == null)
annotations = schemaBuilder.makeAnnotations(comments, getContext());
else
annotations.addLeadingComment(comments);
comments = null;
}
}
}
class ForeignElementHandler extends Handler {
final State nextState;
ElementAnnotationBuilder builder;
final Stack builderStack = new Stack();
StringBuffer textBuf;
Location textLoc;
ForeignElementHandler(State nextState, CommentList comments) {
this.nextState = nextState;
this.comments = comments;
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) {
flushText();
if (builder != null)
builderStack.push(builder);
Location loc = makeLocation();
builder = schemaBuilder.makeElementAnnotationBuilder(namespaceURI,
localName,
findPrefix(qName, namespaceURI),
loc,
getComments(),
getContext());
int len = atts.getLength();
for (int i = 0; i < len; i++) {
String uri = atts.getURI(i);
builder.addAttribute(uri, atts.getLocalName(i), findPrefix(atts.getQName(i), uri),
atts.getValue(i), loc);
}
}
public void endElement(String namespaceURI, String localName,
String qName) {
flushText();
if (comments != null)
builder.addComment(getComments());
ParsedElementAnnotation ea = builder.makeElementAnnotation();
if (builderStack.empty()) {
nextState.endForeignChild(ea);
nextState.set();
}
else {
builder = (ElementAnnotationBuilder)builderStack.pop();
builder.addElement(ea);
}
}
public void characters(char ch[], int start, int length) {
if (textBuf == null)
textBuf = new StringBuffer();
textBuf.append(ch, start, length);
if (textLoc == null)
textLoc = makeLocation();
}
public void comment(String value) {
flushText();
super.comment(value);
}
void flushText() {
if (textBuf != null && textBuf.length() != 0) {
builder.addText(textBuf.toString(), textLoc, getComments());
textBuf.setLength(0);
}
textLoc = null;
}
}
class Skipper extends DefaultHandler implements CommentHandler {
int level = 1;
final State nextState;
Skipper(State nextState) {
this.nextState = nextState;
}
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
++level;
}
public void endElement(String namespaceURI,
String localName,
String qName) throws SAXException {
if (--level == 0)
nextState.set();
}
public void comment(String value) {
}
}
abstract class EmptyContentState extends State {
State createChildState(String localName) throws SAXException {
error("expected_empty", localName);
return null;
}
abstract ParsedPattern makePattern() throws SAXException;
void end() throws SAXException {
if (comments != null) {
if (annotations == null)
annotations = schemaBuilder.makeAnnotations(null, getContext());
annotations.addComment(comments);
comments = null;
}
parent.endChild(makePattern());
}
}
static private final int INIT_CHILD_ALLOC = 5;
abstract class PatternContainerState extends State {
ParsedPattern[] childPatterns;
int nChildPatterns = 0;
State createChildState(String localName) throws SAXException {
State state = (State)patternTable.get(localName);
if (state == null) {
error("expected_pattern", localName);
return null;
}
return state.create();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
if (nPatterns == 1 && anno == null)
return patterns[0];
return schemaBuilder.makeGroup(patterns, nPatterns, loc, anno);
}
void endChild(ParsedPattern pattern) {
if (childPatterns == null)
childPatterns = new ParsedPattern[INIT_CHILD_ALLOC];
else if (nChildPatterns >= childPatterns.length) {
ParsedPattern[] newChildPatterns = new ParsedPattern[childPatterns.length * 2];
System.arraycopy(childPatterns, 0, newChildPatterns, 0, childPatterns.length);
childPatterns = newChildPatterns;
}
childPatterns[nChildPatterns++] = pattern;
}
void endForeignChild(ParsedElementAnnotation ea) {
if (nChildPatterns == 0)
super.endForeignChild(ea);
else
childPatterns[nChildPatterns - 1] = schemaBuilder.annotateAfter(childPatterns[nChildPatterns - 1], ea);
}
void end() throws SAXException {
if (nChildPatterns == 0) {
error("missing_children");
endChild(schemaBuilder.makeErrorPattern());
}
if (comments != null) {
childPatterns[nChildPatterns - 1] = schemaBuilder.commentAfter(childPatterns[nChildPatterns - 1], comments);
comments = null;
}
sendPatternToParent(buildPattern(childPatterns, nChildPatterns, startLocation, annotations));
}
void sendPatternToParent(ParsedPattern p) {
parent.endChild(p);
}
}
class GroupState extends PatternContainerState {
State create() {
return new GroupState();
}
}
class ZeroOrMoreState extends PatternContainerState {
State create() {
return new ZeroOrMoreState();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return schemaBuilder.makeZeroOrMore(super.buildPattern(patterns, nPatterns, loc, null), loc, anno);
}
}
class OneOrMoreState extends PatternContainerState {
State create() {
return new OneOrMoreState();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return schemaBuilder.makeOneOrMore(super.buildPattern(patterns, nPatterns, loc, null), loc, anno);
}
}
class OptionalState extends PatternContainerState {
State create() {
return new OptionalState();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return schemaBuilder.makeOptional(super.buildPattern(patterns, nPatterns, loc, null), loc, anno);
}
}
class ListState extends PatternContainerState {
State create() {
return new ListState();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return schemaBuilder.makeList(super.buildPattern(patterns, nPatterns, loc, null), loc, anno);
}
}
class ChoiceState extends PatternContainerState {
State create() {
return new ChoiceState();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return schemaBuilder.makeChoice(patterns, nPatterns, loc, anno);
}
}
class InterleaveState extends PatternContainerState {
State create() {
return new InterleaveState();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) {
return schemaBuilder.makeInterleave(patterns, nPatterns, loc, anno);
}
}
class MixedState extends PatternContainerState {
State create() {
return new MixedState();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return schemaBuilder.makeMixed(super.buildPattern(patterns, nPatterns, loc, null), loc, anno);
}
}
static interface NameClassRef {
void setNameClass(ParsedNameClass nc);
}
class ElementState extends PatternContainerState implements NameClassRef {
ParsedNameClass nameClass;
boolean nameClassWasAttribute;
String name;
void setName(String name) {
this.name = name;
}
public void setNameClass(ParsedNameClass nc) {
nameClass = nc;
}
void endAttributes() throws SAXException {
if (name != null) {
nameClass = expandName(name, getNs(), null);
nameClassWasAttribute = true;
}
else
new NameClassChildState(this, this).set();
}
State create() {
return new ElementState();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return schemaBuilder.makeElement(nameClass, super.buildPattern(patterns, nPatterns, loc, null), loc, anno);
}
void endForeignChild(ParsedElementAnnotation ea) {
if (nameClassWasAttribute || nChildPatterns > 0 || nameClass == null)
super.endForeignChild(ea);
else
nameClass = schemaBuilder.annotateAfter(nameClass, ea);
}
}
class RootState extends PatternContainerState {
IncludedGrammar grammar;
RootState() {
}
RootState(IncludedGrammar grammar, Scope scope, String ns) {
this.grammar = grammar;
this.scope = scope;
this.nsInherit = ns;
this.datatypeLibrary = "";
}
State create() {
return new RootState();
}
State createChildState(String localName) throws SAXException {
if (grammar == null)
return super.createChildState(localName);
if (localName.equals("grammar"))
return new MergeGrammarState(grammar);
error("expected_grammar", localName);
return null;
}
void checkForeignElement() throws SAXException {
error("root_bad_namespace_uri", WellKnownNamespaces.RELAX_NG);
}
void endChild(ParsedPattern pattern) {
startPattern = pattern;
}
boolean isRelaxNGElement(String uri) throws SAXException {
if (!uri.startsWith(relaxngURIPrefix))
return false;
if (!uri.equals(WellKnownNamespaces.RELAX_NG))
warning("wrong_uri_version",
WellKnownNamespaces.RELAX_NG.substring(relaxngURIPrefix.length()),
uri.substring(relaxngURIPrefix.length()));
relaxngURI = uri;
return true;
}
}
class NotAllowedState extends EmptyContentState {
State create() {
return new NotAllowedState();
}
ParsedPattern makePattern() {
return schemaBuilder.makeNotAllowed(startLocation, annotations);
}
}
class EmptyState extends EmptyContentState {
State create() {
return new EmptyState();
}
ParsedPattern makePattern() {
return schemaBuilder.makeEmpty(startLocation, annotations);
}
}
class TextState extends EmptyContentState {
State create() {
return new TextState();
}
ParsedPattern makePattern() {
return schemaBuilder.makeText(startLocation, annotations);
}
}
class ValueState extends EmptyContentState {
final StringBuffer buf = new StringBuffer();
String type;
State create() {
return new ValueState();
}
void setOtherAttribute(String name, String value) throws SAXException {
if (name.equals("type"))
type = checkNCName(value.trim());
else
super.setOtherAttribute(name, value);
}
public void characters(char[] ch, int start, int len) {
buf.append(ch, start, len);
}
void checkForeignElement() throws SAXException {
error("value_contains_foreign_element");
}
ParsedPattern makePattern() throws SAXException {
if (type == null)
return makePattern("", "token");
else
return makePattern(datatypeLibrary, type);
}
void end() throws SAXException {
mergeLeadingComments();
super.end();
}
ParsedPattern makePattern(String datatypeLibrary, String type) {
return schemaBuilder.makeValue(datatypeLibrary,
type,
buf.toString(),
getContext(),
getNs(),
startLocation,
annotations);
}
}
class DataState extends State {
String type;
ParsedPattern except = null;
DataPatternBuilder dpb = null;
State create() {
return new DataState();
}
State createChildState(String localName) throws SAXException {
if (localName.equals("param")) {
if (except != null)
error("param_after_except");
return new ParamState(dpb);
}
if (localName.equals("except")) {
if (except != null)
error("multiple_except");
return new ChoiceState();
}
error("expected_param_except", localName);
return null;
}
void setOtherAttribute(String name, String value) throws SAXException {
if (name.equals("type"))
type = checkNCName(value.trim());
else
super.setOtherAttribute(name, value);
}
void endAttributes() throws SAXException {
if (type == null)
error("missing_type_attribute");
else
dpb = schemaBuilder.makeDataPatternBuilder(datatypeLibrary, type, startLocation);
}
void endForeignChild(ParsedElementAnnotation ea) {
dpb.annotation(ea);
}
void end() throws SAXException {
ParsedPattern p;
if (dpb != null) {
if (except != null)
p = dpb.makePattern(except, startLocation, annotations);
else
p = dpb.makePattern(startLocation, annotations);
}
else
p = schemaBuilder.makeErrorPattern();
// XXX need to capture comments
parent.endChild(p);
}
void endChild(ParsedPattern pattern) {
except = pattern;
}
}
class ParamState extends State {
private final StringBuffer buf = new StringBuffer();
private final DataPatternBuilder dpb;
private String name;
ParamState(DataPatternBuilder dpb) {
this.dpb = dpb;
}
State create() {
return new ParamState(null);
}
void setName(String name) throws SAXException {
this.name = checkNCName(name);
}
void endAttributes() throws SAXException {
if (name == null)
error("missing_name_attribute");
}
State createChildState(String localName) throws SAXException {
error("expected_empty", localName);
return null;
}
public void characters(char[] ch, int start, int len) {
buf.append(ch, start, len);
}
void checkForeignElement() throws SAXException {
error("param_contains_foreign_element");
}
void end() throws SAXException {
if (name == null)
return;
if (dpb == null)
return;
mergeLeadingComments();
dpb.addParam(name, buf.toString(), getContext(), getNs(), startLocation, annotations);
}
}
class AttributeState extends PatternContainerState implements NameClassRef {
ParsedNameClass nameClass;
boolean nameClassWasAttribute;
String name;
State create() {
return new AttributeState();
}
void setName(String name) {
this.name = name;
}
public void setNameClass(ParsedNameClass nc) {
nameClass = nc;
}
void endAttributes() throws SAXException {
if (name != null) {
String nsUse;
if (ns != null)
nsUse = ns;
else
nsUse = "";
nameClass = expandName(name, nsUse, null);
nameClassWasAttribute = true;
}
else
new NameClassChildState(this, this).set();
}
void endForeignChild(ParsedElementAnnotation ea) {
if (nameClassWasAttribute || nChildPatterns > 0 || nameClass == null)
super.endForeignChild(ea);
else
nameClass = schemaBuilder.annotateAfter(nameClass, ea);
}
void end() throws SAXException {
if (nChildPatterns == 0)
endChild(schemaBuilder.makeText(startLocation, null));
super.end();
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return schemaBuilder.makeAttribute(nameClass, super.buildPattern(patterns, nPatterns, loc, null), loc, anno);
}
State createChildState(String localName) throws SAXException {
State tem = super.createChildState(localName);
if (tem != null && nChildPatterns != 0)
error("attribute_multi_pattern");
return tem;
}
}
abstract class SinglePatternContainerState extends PatternContainerState {
State createChildState(String localName) throws SAXException {
if (nChildPatterns == 0)
return super.createChildState(localName);
error("too_many_children");
return null;
}
}
class GrammarSectionState extends State {
GrammarSection section;
GrammarSectionState() { }
GrammarSectionState(GrammarSection section) {
this.section = section;
}
State create() {
return new GrammarSectionState(null);
}
State createChildState(String localName) throws SAXException {
if (localName.equals("define"))
return new DefineState(section);
if (localName.equals("start"))
return new StartState(section);
if (localName.equals("include")) {
Include include = section.makeInclude();
if (include != null)
return new IncludeState(include);
}
if (localName.equals("div"))
return new DivState(section.makeDiv());
error("expected_define", localName);
// XXX better errors
return null;
}
void end() throws SAXException {
if (comments != null) {
section.topLevelComment(comments);
comments = null;
}
}
void endForeignChild(ParsedElementAnnotation ea) {
section.topLevelAnnotation(ea);
}
}
class DivState extends GrammarSectionState {
final Div div;
DivState(Div div) {
super(div);
this.div = div;
}
void end() throws SAXException {
super.end();
div.endDiv(startLocation, annotations);
}
}
class IncludeState extends GrammarSectionState {
String href;
final Include include;
IncludeState(Include include) {
super(include);
this.include = include;
}
void setOtherAttribute(String name, String value) throws SAXException {
if (name.equals("href")) {
href = value;
checkUri(href);
}
else
super.setOtherAttribute(name, value);
}
void endAttributes() throws SAXException {
if (href == null)
error("missing_href_attribute");
else
href = resolve(href);
}
void end() throws SAXException {
super.end();
if (href != null) {
try {
include.endInclude(href, getNs(), startLocation, annotations);
}
catch (IllegalSchemaException e) {
}
}
}
}
class MergeGrammarState extends GrammarSectionState {
final IncludedGrammar grammar;
MergeGrammarState(IncludedGrammar grammar) {
super(grammar);
this.grammar = grammar;
}
void end() throws SAXException {
super.end();
parent.endChild(grammar.endIncludedGrammar(startLocation, annotations));
}
}
class GrammarState extends GrammarSectionState {
Grammar grammar;
void setParent(State parent) {
super.setParent(parent);
grammar = schemaBuilder.makeGrammar(scope);
section = grammar;
scope = grammar;
}
State create() {
return new GrammarState();
}
void end() throws SAXException {
super.end();
parent.endChild(grammar.endGrammar(startLocation, annotations));
}
}
class RefState extends EmptyContentState {
String name;
State create() {
return new RefState();
}
void endAttributes() throws SAXException {
if (name == null)
error("missing_name_attribute");
}
void setName(String name) throws SAXException {
this.name = checkNCName(name);
}
ParsedPattern makePattern() {
if (name == null)
return schemaBuilder.makeErrorPattern();
return scope.makeRef(name, startLocation, annotations);
}
}
class ParentRefState extends RefState {
State create() {
return new ParentRefState();
}
ParsedPattern makePattern() {
if (name == null)
return schemaBuilder.makeErrorPattern();
return scope.makeParentRef(name, startLocation, annotations);
}
}
class ExternalRefState extends EmptyContentState {
String href;
ParsedPattern includedPattern;
State create() {
return new ExternalRefState();
}
void setOtherAttribute(String name, String value) throws SAXException {
if (name.equals("href")) {
href = value;
checkUri(href);
}
else
super.setOtherAttribute(name, value);
}
void endAttributes() throws SAXException {
if (href == null)
error("missing_href_attribute");
else
href = resolve(href);
}
ParsedPattern makePattern() {
if (href != null) {
try {
return schemaBuilder.makeExternalRef(href,
getNs(),
scope,
startLocation,
annotations);
}
catch (IllegalSchemaException e) { }
}
return schemaBuilder.makeErrorPattern();
}
}
abstract class DefinitionState extends PatternContainerState {
GrammarSection.Combine combine = null;
final GrammarSection section;
DefinitionState(GrammarSection section) {
this.section = section;
}
void setOtherAttribute(String name, String value) throws SAXException {
if (name.equals("combine")) {
value = value.trim();
if (value.equals("choice"))
combine = GrammarSection.COMBINE_CHOICE;
else if (value.equals("interleave"))
combine = GrammarSection.COMBINE_INTERLEAVE;
else
error("combine_attribute_bad_value", value);
}
else
super.setOtherAttribute(name, value);
}
ParsedPattern buildPattern(ParsedPattern[] patterns, int nPatterns, Location loc, Annotations anno) throws SAXException {
return super.buildPattern(patterns, nPatterns, loc, null);
}
}
class DefineState extends DefinitionState {
String name;
DefineState(GrammarSection section) {
super(section);
}
State create() {
return new DefineState(null);
}
void setName(String name) throws SAXException {
this.name = checkNCName(name);
}
void endAttributes() throws SAXException {
if (name == null)
error("missing_name_attribute");
}
void sendPatternToParent(ParsedPattern p) {
if (name != null)
section.define(name, combine, p, startLocation, annotations);
}
}
class StartState extends DefinitionState {
StartState(GrammarSection section) {
super(section);
}
State create() {
return new StartState(null);
}
void sendPatternToParent(ParsedPattern p) {
section.define(GrammarSection.START, combine, p, startLocation, annotations);
}
State createChildState(String localName) throws SAXException {
State tem = super.createChildState(localName);
if (tem != null && nChildPatterns != 0)
error("start_multi_pattern");
return tem;
}
}
abstract class NameClassContainerState extends State {
State createChildState(String localName) throws SAXException {
State state = (State)nameClassTable.get(localName);
if (state == null) {
error("expected_name_class", localName);
return null;
}
return state.create();
}
}
class NameClassChildState extends NameClassContainerState {
final State prevState;
final NameClassRef nameClassRef;
State create() {
return null;
}
NameClassChildState(State prevState, NameClassRef nameClassRef) {
this.prevState = prevState;
this.nameClassRef = nameClassRef;
setParent(prevState.parent);
this.ns = prevState.ns;
}
void endChild(ParsedNameClass nameClass) {
nameClassRef.setNameClass(nameClass);
prevState.set();
}
void endForeignChild(ParsedElementAnnotation ea) {
prevState.endForeignChild(ea);
}
void end() throws SAXException {
nameClassRef.setNameClass(schemaBuilder.makeErrorNameClass());
error("missing_name_class");
prevState.set();
prevState.end();
}
}
abstract class NameClassBaseState extends State {
abstract ParsedNameClass makeNameClass() throws SAXException;
void end() throws SAXException {
parent.endChild(makeNameClass());
}
}
class NameState extends NameClassBaseState {
final StringBuffer buf = new StringBuffer();
State createChildState(String localName) throws SAXException {
error("expected_name", localName);
return null;
}
State create() {
return new NameState();
}
public void characters(char[] ch, int start, int len) {
buf.append(ch, start, len);
}
void checkForeignElement() throws SAXException {
error("name_contains_foreign_element");
}
ParsedNameClass makeNameClass() throws SAXException {
mergeLeadingComments();
return expandName(buf.toString().trim(), getNs(), annotations);
}
}
private static final int PATTERN_CONTEXT = 0;
private static final int ANY_NAME_CONTEXT = 1;
private static final int NS_NAME_CONTEXT = 2;
class AnyNameState extends NameClassBaseState {
ParsedNameClass except = null;
State create() {
return new AnyNameState();
}
State createChildState(String localName) throws SAXException {
if (localName.equals("except")) {
if (except != null)
error("multiple_except");
return new NameClassChoiceState(getContext());
}
error("expected_except", localName);
return null;
}
int getContext() {
return ANY_NAME_CONTEXT;
}
ParsedNameClass makeNameClass() {
if (except == null)
return makeNameClassNoExcept();
else
return makeNameClassExcept(except);
}
ParsedNameClass makeNameClassNoExcept() {
return schemaBuilder.makeAnyName(startLocation, annotations);
}
ParsedNameClass makeNameClassExcept(ParsedNameClass except) {
return schemaBuilder.makeAnyName(except, startLocation, annotations);
}
void endChild(ParsedNameClass nameClass) {
except = nameClass;
}
}
class NsNameState extends AnyNameState {
State create() {
return new NsNameState();
}
ParsedNameClass makeNameClassNoExcept() {
return schemaBuilder.makeNsName(getNs(), null, null);
}
ParsedNameClass makeNameClassExcept(ParsedNameClass except) {
return schemaBuilder.makeNsName(getNs(), except, null, null);
}
int getContext() {
return NS_NAME_CONTEXT;
}
}
class NameClassChoiceState extends NameClassContainerState {
private ParsedNameClass[] nameClasses;
private int nNameClasses;
private int context;
NameClassChoiceState() {
this.context = PATTERN_CONTEXT;
}
NameClassChoiceState(int context) {
this.context = context;
}
void setParent(State parent) {
super.setParent(parent);
if (parent instanceof NameClassChoiceState)
this.context = ((NameClassChoiceState)parent).context;
}
State create() {
return new NameClassChoiceState();
}
State createChildState(String localName) throws SAXException {
if (localName.equals("anyName")) {
if (context >= ANY_NAME_CONTEXT) {
error(context == ANY_NAME_CONTEXT
? "any_name_except_contains_any_name"
: "ns_name_except_contains_any_name");
return null;
}
}
else if (localName.equals("nsName")) {
if (context == NS_NAME_CONTEXT) {
error("ns_name_except_contains_ns_name");
return null;
}
}
return super.createChildState(localName);
}
void endChild(ParsedNameClass nc) {
if (nameClasses == null)
nameClasses = new ParsedNameClass[INIT_CHILD_ALLOC];
else if (nNameClasses >= nameClasses.length) {
ParsedNameClass[] newNameClasses = new ParsedNameClass[nameClasses.length * 2];
System.arraycopy(nameClasses, 0, newNameClasses, 0, nameClasses.length);
nameClasses = newNameClasses;
}
nameClasses[nNameClasses++] = nc;
}
void endForeignChild(ParsedElementAnnotation ea) {
if (nNameClasses == 0)
super.endForeignChild(ea);
else
nameClasses[nNameClasses - 1] = schemaBuilder.annotateAfter(nameClasses[nNameClasses - 1], ea);
}
void end() throws SAXException {
if (nNameClasses == 0) {
error("missing_name_class");
parent.endChild(schemaBuilder.makeErrorNameClass());
return;
}
if (comments != null) {
nameClasses[nNameClasses - 1] = schemaBuilder.commentAfter(nameClasses[nNameClasses - 1], comments);
comments = null;
}
parent.endChild(schemaBuilder.makeChoice(nameClasses, nNameClasses, startLocation, annotations));
}
}
private void initPatternTable() {
patternTable = new Hashtable();
patternTable.put("zeroOrMore", new ZeroOrMoreState());
patternTable.put("oneOrMore", new OneOrMoreState());
patternTable.put("optional", new OptionalState());
patternTable.put("list", new ListState());
patternTable.put("choice", new ChoiceState());
patternTable.put("interleave", new InterleaveState());
patternTable.put("group", new GroupState());
patternTable.put("mixed", new MixedState());
patternTable.put("element", new ElementState());
patternTable.put("attribute", new AttributeState());
patternTable.put("empty", new EmptyState());
patternTable.put("text", new TextState());
patternTable.put("value", new ValueState());
patternTable.put("data", new DataState());
patternTable.put("notAllowed", new NotAllowedState());
patternTable.put("grammar", new GrammarState());
patternTable.put("ref", new RefState());
patternTable.put("parentRef", new ParentRefState());
patternTable.put("externalRef", new ExternalRefState());
}
private void initNameClassTable() {
nameClassTable = new Hashtable();
nameClassTable.put("name", new NameState());
nameClassTable.put("anyName", new AnyNameState());
nameClassTable.put("nsName", new NsNameState());
nameClassTable.put("choice", new NameClassChoiceState());
}
public ParsedPattern getParsedPattern() throws IllegalSchemaException {
if (hadError)
throw new IllegalSchemaException();
return startPattern;
}
private void error(String key) throws SAXException {
error(key, locator);
}
private void error(String key, String arg) throws SAXException {
error(key, arg, locator);
}
void error(String key, String arg1, String arg2) throws SAXException {
error(key, arg1, arg2, locator);
}
private void error(String key, Locator loc) throws SAXException {
error(new SAXParseException(localizer.message(key), loc));
}
private void error(String key, String arg, Locator loc) throws SAXException {
error(new SAXParseException(localizer.message(key, arg), loc));
}
private void error(String key, String arg1, String arg2, Locator loc)
throws SAXException {
error(new SAXParseException(localizer.message(key, arg1, arg2), loc));
}
private void error(SAXParseException e) throws SAXException {
hadError = true;
if (eh != null)
eh.error(e);
}
void warning(String key) throws SAXException {
warning(key, locator);
}
private void warning(String key, String arg) throws SAXException {
warning(key, arg, locator);
}
private void warning(String key, String arg1, String arg2) throws SAXException {
warning(key, arg1, arg2, locator);
}
private void warning(String key, Locator loc) throws SAXException {
warning(new SAXParseException(localizer.message(key), loc));
}
private void warning(String key, String arg, Locator loc) throws SAXException {
warning(new SAXParseException(localizer.message(key, arg), loc));
}
private void warning(String key, String arg1, String arg2, Locator loc)
throws SAXException {
warning(new SAXParseException(localizer.message(key, arg1, arg2), loc));
}
private void warning(SAXParseException e) throws SAXException {
if (eh != null)
eh.warning(e);
}
SchemaParser(XMLReader xr,
ErrorHandler eh,
SchemaBuilder schemaBuilder,
IncludedGrammar grammar,
Scope scope) throws SAXException {
this.xr = xr;
this.eh = eh;
this.schemaBuilder = schemaBuilder;
if (eh != null)
xr.setErrorHandler(eh);
xr.setDTDHandler(context);
if (schemaBuilder.usesComments()) {
try {
xr.setProperty("http://xml.org/sax/properties/lexical-handler", new LexicalHandlerImpl());
}
catch (SAXNotRecognizedException e) {
warning("no_comment_support", xr.getClass().getName());
}
catch (SAXNotSupportedException e) {
warning("no_comment_support", xr.getClass().getName());
}
}
initPatternTable();
initNameClassTable();
new RootState(grammar, scope, SchemaBuilder.INHERIT_NS).set();
}
private Context getContext() {
return context;
}
class LexicalHandlerImpl extends AbstractLexicalHandler {
private boolean inDtd = false;
public void startDTD(String s, String s1, String s2) throws SAXException {
inDtd = true;
}
public void endDTD() throws SAXException {
inDtd = false;
}
public void comment(char[] chars, int start, int length) throws SAXException {
if (!inDtd)
((CommentHandler)xr.getContentHandler()).comment(new String(chars, start, length));
}
}
private ParsedNameClass expandName(String name, String ns, Annotations anno) throws SAXException {
int ic = name.indexOf(':');
if (ic == -1)
return schemaBuilder.makeName(ns, checkNCName(name), null, null, anno);
String prefix = checkNCName(name.substring(0, ic));
String localName = checkNCName(name.substring(ic + 1));
for (PrefixMapping tem = context.prefixMapping; tem != null; tem = tem.next)
if (tem.prefix.equals(prefix))
return schemaBuilder.makeName(tem.uri, localName, prefix, null, anno);
error("undefined_prefix", prefix);
return schemaBuilder.makeName("", localName, null, null, anno);
}
private String findPrefix(String qName, String uri) {
String prefix = null;
if (qName == null || qName.equals("")) {
for (PrefixMapping p = context.prefixMapping; p != null; p = p.next)
if (p.uri.equals(uri)) {
prefix = p.prefix;
break;
}
}
else {
int off = qName.indexOf(':');
if (off > 0)
prefix = qName.substring(0, off);
}
return prefix;
}
private String checkNCName(String str) throws SAXException {
if (!Naming.isNcname(str))
error("invalid_ncname", str);
return str;
}
private String resolve(String systemId) throws SAXException {
if (Uri.hasFragmentId(systemId))
error("href_fragment_id");
systemId = Uri.escapeDisallowedChars(systemId);
return Uri.resolve(xmlBaseHandler.getBaseUri(), systemId);
}
private Location makeLocation() {
if (locator == null)
return null;
return schemaBuilder.makeLocation(locator.getSystemId(),
locator.getLineNumber(),
locator.getColumnNumber());
}
private void checkUri(String s) throws SAXException {
if (!Uri.isValid(s))
error("invalid_uri", s);
}
}
|
package com.vaadin.terminal.gwt.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import com.vaadin.Application;
/**
* This servlet connects a Vaadin Application to Web.
*
* @author IT Mill Ltd.
* @version
* @VERSION@
* @since 5.0
*/
@SuppressWarnings("serial")
public class ApplicationServlet extends AbstractApplicationServlet {
// Private fields
private Class<? extends Application> applicationClass;
/**
* Called by the servlet container to indicate to a servlet that the servlet
* is being placed into service.
*
* @param servletConfig
* the object containing the servlet's configuration and
* initialization parameters
* @throws javax.servlet.ServletException
* if an exception has occurred that interferes with the
* servlet's normal operation.
*/
@SuppressWarnings("unchecked")
@Override
public void init(javax.servlet.ServletConfig servletConfig)
throws javax.servlet.ServletException {
super.init(servletConfig);
// Loads the application class using the same class loader
// as the servlet itself
// Gets the application class name
final String applicationClassName = servletConfig
.getInitParameter("application");
if (applicationClassName == null) {
throw new ServletException(
"Application not specified in servlet parameters");
}
try {
applicationClass = (Class<? extends Application>) getClassLoader()
.loadClass(applicationClassName);
} catch (final ClassNotFoundException e) {
throw new ServletException("Failed to load application class: "
+ applicationClassName);
}
}
@Override
protected Application getNewApplication(HttpServletRequest request)
throws ServletException {
// Creates a new application instance
try {
final Application application = getApplicationClass().newInstance();
return application;
} catch (final IllegalAccessException e) {
throw new ServletException("getNewApplication failed", e);
} catch (final InstantiationException e) {
throw new ServletException("getNewApplication failed", e);
} catch (ClassNotFoundException e) {
throw new ServletException("getNewApplication failed", e);
}
}
@Override
protected Class<? extends Application> getApplicationClass()
throws ClassNotFoundException {
return applicationClass;
}
}
|
package org.commcare.applogic;
import org.commcare.core.properties.CommCareProperties;
import org.commcare.resources.model.InstallCancelledException;
import org.commcare.resources.model.Resource;
import org.commcare.resources.model.ResourceTable;
import org.commcare.resources.model.TableStateListener;
import org.commcare.resources.model.UnreliableSourceException;
import org.commcare.resources.model.UnresolvedResourceException;
import org.commcare.util.CommCareContext;
import org.commcare.util.CommCareInitializer;
import org.commcare.util.CommCarePlatform;
import org.commcare.resources.ResourceManager;
import org.commcare.util.InitializationListener;
import org.commcare.util.YesNoListener;
import org.commcare.view.CommCareStartupInteraction;
import org.javarosa.core.api.State;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.PropertyManager;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.TrivialTransitions;
import org.javarosa.j2me.view.J2MEDisplay;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import java.util.Vector;
/**
* @author ctsims
*
*/
public abstract class CommCareUpgradeState implements State, TrivialTransitions {
public static final String UPGRADE_TABLE_NAME = "UPGRADGE";
public static final String RECOVERY_TABLE_NAME = "RECOVERY";
boolean interactive = false;
int networkRetries = -1;
public CommCareUpgradeState(boolean interactive) {
this(interactive, getRetryAttempts());
}
private static int getRetryAttempts() {
String retryAttempts = PropertyManager._().getSingularProperty(CommCareProperties.INSTALL_RETRY_ATTEMPTS);
if(retryAttempts == null ) { return -1; }
try {
return Integer.parseInt(retryAttempts);
} catch(NumberFormatException e) {
Logger.log("upgrade", "Bad retry attempt config set: \"" + retryAttempts + "\"");
return -1;
}
}
public CommCareUpgradeState(boolean interactive, int networkRetries) {
this.interactive = interactive;
this.networkRetries = networkRetries;
}
public void start() {
final CommCareStartupInteraction interaction = new CommCareStartupInteraction("CommCare is checking for updates....");
J2MEDisplay.setView(interaction);
CommCareInitializer upgradeInitializer = new CommCareInitializer() {
ResourceTable upgrade = CommCareContext.CreateTemporaryResourceTable(UPGRADE_TABLE_NAME);
ResourceTable recovery = CommCareContext.CreateTemporaryResourceTable(RECOVERY_TABLE_NAME);
protected boolean runWrapper() throws UnfullfilledRequirementsException {
if(networkRetries != -1) {
upgrade.setNumberOfRetries(networkRetries);
}
ResourceTable global = CommCareContext.RetrieveGlobalResourceTable();
if(global.getTableReadiness() != ResourceTable.RESOURCE_TABLE_INSTALLED) {
//TODO: Recover/repair
}
boolean staged = false;
ResourceManager resourceManager =
new ResourceManager(CommCareContext._().getManager(),
global, upgrade, recovery);
while(!staged) {
try {
resourceManager.stageUpgradeTable(false);
interaction.updateProgess(20);
staged = true;
} catch (InstallCancelledException e) {
Logger.log("upgrade", "User cancellation unsupported on J2ME: " + e.getMessage());
return false;
} catch (UnresolvedResourceException e) {
Logger.log("upgrade", "Error locating upgrade profile: " + e.getMessage());
if(interactive) {
if(blockForResponse("Couldn't find the update profile, do you want to try again?")) {
//loop here
} else {
return false;
}
} else{
return false;
}
}
}
Resource updateProfile = upgrade.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
Resource currentProfile = global.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID);
if(!(updateProfile.getVersion() > currentProfile.getVersion())){
if(interactive) {
blockForResponse("CommCare is up to date!", false);
return false;
} else {
return true;
}
}
if(interactive) {
if(!blockForResponse("Upgrade is Available! Do you want to start the update?")) {
return true;
}
}
setMessage(Localization.get("update.header"));
TableStateListener upgradeListener = new TableStateListener() {
private int score = 0;
private int max = 0;
public final static int INSTALL_SCORE = 5;
public void simpleResourceAdded() {
interaction.updateProgess(20 + (int)Math.ceil(65 * (++score * 1.0 / max)));
}
public void compoundResourceAdded(final ResourceTable table) {
score = 0;
max = 0;
Vector<Resource> resources = ResourceManager.getResourceListFromProfile(table);
max = resources.size() * INSTALL_SCORE;
if(max <= INSTALL_SCORE*2) {
//We'll have at least two resources when we jump in, so dont' bother updating
//until we have more
return;
}
for(Resource r : resources) {
switch(r.getStatus()) {
case Resource.RESOURCE_STATUS_UPGRADE:
score += INSTALL_SCORE;
break;
case Resource.RESOURCE_STATUS_INSTALLED:
score += INSTALL_SCORE;
break;
default:
score += 1;
break;
}
}
interaction.updateProgess(20 + (int)Math.ceil(65 * (score * 1.0 / max)));
}
public void incrementProgress(int complete, int total) {
}
};
TableStateListener globalListener = new TableStateListener() {
public void simpleResourceAdded() {
}
public void compoundResourceAdded(final ResourceTable table) {
}
public void incrementProgress(int complete, int total) {
}
};
upgrade.setStateListener(upgradeListener);
global.setStateListener(globalListener);
//We're gonna optionally allow the user to continue the install from this resource table in
//interactive mode
boolean upgradeAttemptPending = true;
while(upgradeAttemptPending) {
//We're trying once, so don't try again unless requested
upgradeAttemptPending = false;
try {
resourceManager.prepareUpgradeResources();
resourceManager.upgrade();
} catch (InstallCancelledException e) {
Logger.log("upgrade", "User cancellation unsupported on J2ME: " + e.getMessage());
} catch(UnreliableSourceException e) {
//We simply can't retrieve all of the resources that we're looking for.
//If interactive, give them the option of trying again.
if(interactive) {
if(blockForResponse(Localization.get("update.fail.network.retry"), true)) {
//Give it another shot!
setMessage(Localization.get("update.retrying"));
//TODO: Crank up the effort on the retries?
upgradeAttemptPending = true;
continue;
}
} else {
//If it's not interactive, just notify the user of failure
blockForResponse(Localization.get("update.fail.network"), false);
}
logFailure();
CommCareUpgradeState.this.done();
return false;
} catch (UnresolvedResourceException e) {
//Generic problem with the upgrade. Inform and return.
this.fail(e);
return false;
}
}
interaction.updateProgess(95);
blockForResponse("CommCare Updated!", false);
return true;
}
private void logFailure() {
//Can't (or won't) keep trying.
String logMsg = "Upgrade attempt unsuccesful. Probably due to network. ";
//Count resources
Vector<Resource> resources = ResourceManager.getResourceListFromProfile(upgrade);
int downloaded = 0;
for(Resource r : resources ){
if(r.getStatus() == Resource.RESOURCE_STATUS_UPGRADE || r.getStatus() == Resource.RESOURCE_STATUS_INSTALLED) {
downloaded++;
}
}
logMsg += downloaded + " of " + resources.size() + " resources were succesfully fetched/installed";
Logger.log("upgrade", logMsg);
}
protected void setMessage(String message) {
interaction.setMessage(message,true);
}
protected void askForResponse(String message, YesNoListener listener, boolean yesNo) {
interaction.setMessage(message,false);
if(yesNo) {
interaction.AskYesNo(message, listener);
} else {
interaction.PromptResponse(message, listener);
}
}
protected void askForResponse(String message, YesNoListener yesNoListener, boolean yesNo, String left, String right) {
if(yesNo) {
interaction.AskYesNo(message,yesNoListener, left, right);
} else {
interaction.PromptResponse(message, yesNoListener);
}
}
protected void fail(Exception e) {
//Botched! For any number of reasons. However, let's be sure to roll back
//any changes, if they happened.
upgrade.clear();
String message;
//Note why it failed, since we don't know what this is
Logger.exception(e);
message = Localization.get("update.fail.generic");
blockForResponse(message, false);
CommCareUpgradeState.this.done();
}
};
upgradeInitializer.initialize(new InitializationListener() {
public void onSuccess() {
CommCareUpgradeState.this.done();
}
public void onFailure() {
CommCareUpgradeState.this.done();
}
});
}
public abstract void done();
}
|
package net.fortuna.ical4j.model.component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.DateRange;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.Validator;
import net.fortuna.ical4j.model.parameter.FbType;
import net.fortuna.ical4j.model.property.Contact;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.FreeBusy;
import net.fortuna.ical4j.model.property.Method;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Url;
import net.fortuna.ical4j.util.CompatibilityHints;
import net.fortuna.ical4j.util.PropertyValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class VFreeBusy extends CalendarComponent {
private static final long serialVersionUID = 1046534053331139832L;
private transient Log log = LogFactory.getLog(VFreeBusy.class);
private final Map methodValidators = new HashMap();
{
methodValidators.put(Method.PUBLISH, new PublishValidator());
methodValidators.put(Method.REPLY, new ReplyValidator());
methodValidators.put(Method.REQUEST, new RequestValidator());
}
/**
* Default constructor.
*/
public VFreeBusy() {
super(VFREEBUSY);
getProperties().add(new DtStamp());
}
/**
* Constructor.
* @param properties a list of properties
*/
public VFreeBusy(final PropertyList properties) {
super(VFREEBUSY, properties);
}
/**
* Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used
* for requesting busy time for a specified period.
* @param start the starting boundary for the VFreeBusy
* @param end the ending boundary for the VFreeBusy
*/
public VFreeBusy(final DateTime start, final DateTime end) {
this();
// 4.8.2.4 Date/Time Start:
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start, true));
// 4.8.2.2 Date/Time End
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end, true));
}
/**
* Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used
* for requesting free time for a specified duration in given period defined by the start date and end date.
* @param start the starting boundary for the VFreeBusy
* @param end the ending boundary for the VFreeBusy
* @param duration the length of the period being requested
*/
public VFreeBusy(final DateTime start, final DateTime end, final Dur duration) {
this();
// 4.8.2.4 Date/Time Start:
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start, true));
// 4.8.2.2 Date/Time End
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end, true));
getProperties().add(new Duration(duration));
}
/**
* Constructs a new VFreeBusy instance representing a reply to the specified VFREEBUSY request according to the
* specified list of components.
* If the request argument has its duration set, then the result
* represents a list of <em>free</em> times (that is, parameter FBTYPE
* is set to FbType.FREE).
* If the request argument does not have its duration set, then the result
* represents a list of <em>busy</em> times.
* @param request a VFREEBUSY request
* @param components a component list used to initialise busy time
* @throws ValidationException
*/
public VFreeBusy(final VFreeBusy request, final ComponentList components) {
this();
DtStart start = (DtStart) request.getProperty(Property.DTSTART);
DtEnd end = (DtEnd) request.getProperty(Property.DTEND);
Duration duration = (Duration) request.getProperty(Property.DURATION);
// 4.8.2.4 Date/Time Start:
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
getProperties().add(new DtStart(start.getDate(), true));
// 4.8.2.2 Date/Time End
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
getProperties().add(new DtEnd(end.getDate(), true));
if (duration != null) {
getProperties().add(new Duration(duration.getDuration()));
// Initialise with all free time of at least the specified duration..
DateTime freeStart = new DateTime(start.getDate());
DateTime freeEnd = new DateTime(end.getDate());
FreeBusy fb = new FreeTimeBuilder().start(freeStart)
.end(freeEnd)
.duration(duration.getDuration())
.components(components)
.build();
if (fb != null && !fb.getPeriods().isEmpty()) {
getProperties().add(fb);
}
}
else {
// initialise with all busy time for the specified period..
DateTime busyStart = new DateTime(start.getDate());
DateTime busyEnd = new DateTime(end.getDate());
FreeBusy fb = new BusyTimeBuilder().start(busyStart)
.end(busyEnd)
.components(components)
.build();
if (fb != null && !fb.getPeriods().isEmpty()) {
getProperties().add(fb);
}
}
}
/**
* Create a FREEBUSY property representing the busy time for the specified component list. If the component is not
* applicable to FREEBUSY time, or if the component is outside the bounds of the start and end dates, null is
* returned. If no valid busy periods are identified in the component an empty FREEBUSY property is returned (i.e.
* empty period list).
*/
private class BusyTimeBuilder {
private DateTime start;
private DateTime end;
private ComponentList components;
public BusyTimeBuilder start(DateTime start) {
this.start = start;
return this;
}
public BusyTimeBuilder end(DateTime end) {
this.end = end;
return this;
}
public BusyTimeBuilder components(ComponentList components) {
this.components = components;
return this;
}
public FreeBusy build() {
final PeriodList periods = getConsumedTime(components, start, end);
final DateRange range = new DateRange(start, end);
// periods must be in UTC time for freebusy..
periods.setUtc(true);
for (final Iterator i = periods.iterator(); i.hasNext();) {
final Period period = (Period) i.next();
// check if period outside bounds..
if (!range.intersects(period)) {
periods.remove(period);
}
}
return new FreeBusy(periods);
}
}
/**
* Create a FREEBUSY property representing the free time available of the specified duration for the given list of
* components. component. If the component is not applicable to FREEBUSY time, or if the component is outside the
* bounds of the start and end dates, null is returned. If no valid busy periods are identified in the component an
* empty FREEBUSY property is returned (i.e. empty period list).
*/
private class FreeTimeBuilder {
private DateTime start;
private DateTime end;
private Dur duration;
private ComponentList components;
public FreeTimeBuilder start(DateTime start) {
this.start = start;
return this;
}
public FreeTimeBuilder end(DateTime end) {
this.end = end;
return this;
}
private FreeTimeBuilder duration(Dur duration) {
this.duration = duration;
return this;
}
public FreeTimeBuilder components(ComponentList components) {
this.components = components;
return this;
}
public FreeBusy build() {
final FreeBusy fb = new FreeBusy();
fb.getParameters().add(FbType.FREE);
final PeriodList periods = getConsumedTime(components, start, end);
final DateRange range = new DateRange(start, end);
// Add final consumed time to avoid special-case end-of-list processing
periods.add(new Period(end, end));
// debugging..
if (log.isDebugEnabled()) {
log.debug("Busy periods: " + periods);
}
DateTime lastPeriodEnd = new DateTime(start);
// where no time is consumed set the last period end as the range start..
for (final Iterator i = periods.iterator(); i.hasNext();) {
final Period period = (Period) i.next();
// check if period outside bounds..
if (range.contains(period)) {
// calculate duration between this period start and last period end..
final Duration freeDuration = new Duration(lastPeriodEnd, period.getStart());
if (freeDuration.getDuration().compareTo(duration) >= 0) {
fb.getPeriods().add(new Period(lastPeriodEnd, freeDuration.getDuration()));
}
}
if (period.getEnd().after(lastPeriodEnd)) {
lastPeriodEnd = period.getEnd();
}
}
return fb;
}
}
/**
* Creates a list of periods representing the time consumed by the specified list of components.
* @param components
* @return
*/
private PeriodList getConsumedTime(final ComponentList components, final DateTime rangeStart,
final DateTime rangeEnd) {
PeriodList periods = new PeriodList();
// only events consume time..
for (Iterator i = components.getComponents(Component.VEVENT).iterator(); i.hasNext();) {
Component component = (Component) i.next();
periods.addAll(((VEvent) component).getConsumedTime(rangeStart, rangeEnd, false));
}
return periods.normalise();
}
/**
* {@inheritDoc}
*/
public final void validate(final boolean recurse) throws ValidationException {
if (!CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) {
// From "4.8.4.7 Unique Identifier":
// Conformance: The property MUST be specified in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.UID,
getProperties());
// From "4.8.7.2 Date/Time Stamp":
// Conformance: This property MUST be included in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.DTSTAMP,
getProperties());
}
PropertyValidator validator = PropertyValidator.getInstance();
/*
* ; the following are optional, ; but MUST NOT occur more than once contact / dtstart / dtend / duration /
* dtstamp / organizer / uid / url /
*/
validator.assertOneOrLess(Property.CONTACT, getProperties());
validator.assertOneOrLess(Property.DTSTART, getProperties());
validator.assertOneOrLess(Property.DTEND, getProperties());
validator.assertOneOrLess(Property.DURATION, getProperties());
validator.assertOneOrLess(Property.DTSTAMP, getProperties());
validator.assertOneOrLess(Property.ORGANIZER, getProperties());
validator.assertOneOrLess(Property.UID, getProperties());
validator.assertOneOrLess(Property.URL, getProperties());
/*
* ; the following are optional, ; and MAY occur more than once attendee / comment / freebusy / rstatus / x-prop
*/
/*
* The recurrence properties ("RRULE", "EXRULE", "RDATE", "EXDATE") are not permitted within a "VFREEBUSY"
* calendar component. Any recurring events are resolved into their individual busy time periods using the
* "FREEBUSY" property.
*/
validator.assertNone(Property.RRULE, getProperties());
validator.assertNone(Property.EXRULE, getProperties());
validator.assertNone(Property.RDATE, getProperties());
validator.assertNone(Property.EXDATE, getProperties());
// DtEnd value must be later in time that DtStart..
DtStart dtStart = (DtStart) getProperty(Property.DTSTART);
// 4.8.2.4 Date/Time Start:
// Within the "VFREEBUSY" calendar component, this property defines the
// start date and time for the free or busy time information. The time
// MUST be specified in UTC time.
if (dtStart != null && !dtStart.isUtc()) {
throw new ValidationException("DTSTART must be specified in UTC time");
}
DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND);
// 4.8.2.2 Date/Time End
// Within the "VFREEBUSY" calendar component, this property defines the
// end date and time for the free or busy time information. The time
// MUST be specified in the UTC time format. The value MUST be later in
// time than the value of the "DTSTART" property.
if (dtEnd != null && !dtEnd.isUtc()) {
throw new ValidationException("DTEND must be specified in UTC time");
}
if (dtStart != null && dtEnd != null
&& !dtStart.getDate().before(dtEnd.getDate())) {
throw new ValidationException("Property [" + Property.DTEND
+ "] must be later in time than [" + Property.DTSTART + "]");
}
if (recurse) {
validateProperties();
}
}
/**
* {@inheritDoc}
*/
protected Validator getValidator(Method method) {
return (Validator) methodValidators.get(method);
}
private class PublishValidator implements Validator {
public void validate() throws ValidationException {
PropertyValidator.getInstance().assertOneOrMore(Property.FREEBUSY, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL, getProperties());
PropertyValidator.getInstance().assertNone(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.REQUEST_STATUS, getProperties());
}
}
private class ReplyValidator implements Validator {
public void validate() throws ValidationException {
// FREEBUSY is 1+ in RFC2446 but 0+ in Calsify
PropertyValidator.getInstance().assertOne(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.SEQUENCE, getProperties());
}
}
private class RequestValidator implements Validator {
public void validate() throws ValidationException {
PropertyValidator.getInstance().assertOneOrMore(Property.ATTENDEE, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTEND, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties());
PropertyValidator.getInstance().assertOne(Property.DTSTART, getProperties());
PropertyValidator.getInstance().assertOne(Property.ORGANIZER, getProperties());
PropertyValidator.getInstance().assertOne(Property.UID, getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.COMMENT, getProperties());
PropertyValidator.getInstance().assertNone(Property.FREEBUSY, getProperties());
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
PropertyValidator.getInstance().assertNone(Property.REQUEST_STATUS, getProperties());
PropertyValidator.getInstance().assertNone(Property.URL, getProperties());
}
}
/**
* @return the CONTACT property or null if not specified
*/
public final Contact getContact() {
return (Contact) getProperty(Property.CONTACT);
}
/**
* @return the DTSTART propery or null if not specified
*/
public final DtStart getStartDate() {
return (DtStart) getProperty(Property.DTSTART);
}
/**
* @return the DTEND property or null if not specified
*/
public final DtEnd getEndDate() {
return (DtEnd) getProperty(Property.DTEND);
}
/**
* @return the DURATION property or null if not specified
*/
public final Duration getDuration() {
return (Duration) getProperty(Property.DURATION);
}
/**
* @return the DTSTAMP property or null if not specified
*/
public final DtStamp getDateStamp() {
return (DtStamp) getProperty(Property.DTSTAMP);
}
/**
* @return the ORGANIZER property or null if not specified
*/
public final Organizer getOrganizer() {
return (Organizer) getProperty(Property.ORGANIZER);
}
/**
* @return the URL property or null if not specified
*/
public final Url getUrl() {
return (Url) getProperty(Property.URL);
}
/**
* Returns the UID property of this component if available.
* @return a Uid instance, or null if no UID property exists
*/
public final Uid getUid() {
return (Uid) getProperty(Property.UID);
}
/**
* @param stream
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(final java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
log = LogFactory.getLog(VFreeBusy.class);
}
}
|
package org.jasig.portal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.apache.pluto.om.common.Preference;
import org.apache.pluto.om.common.PreferenceSet;
import org.jasig.portal.container.om.common.PreferenceSetImpl;
import org.jasig.portal.utils.CounterStoreFactory;
import org.jasig.portal.utils.ICounterStore;
/**
* An implementation of IPortletPreferencesStore which uses a RDBM data source to
* persist the data.
*
* @author Eric Dalquist <a href="mailto:edalquist@unicon.net">edalquist@unicon.net </a>
* @version $Revision$
*/
public class RDBMPortletPreferencesStore implements IPortletPreferencesStore {
private static final Log log = LogFactory.getLog(RDBMPortletPreferencesStore.class);
private static final String READ_ONLY_TRUE = "Y";
private static final String READ_ONLY_FALSE = "N";
private static final String UP_PORTLET_PREFERENCE_VALUE = "UP_PORTLET_PREFERENCE_VALUE";
private static final String PREFIX = "UP_PORTLET_PREF_PREFIX__";
/**
* @see org.jasig.portal.IPortletPreferencesStore#setDefinitionPreferences(int, org.apache.pluto.om.common.PreferenceSet)
*/
public void setDefinitionPreferences(final int chanId, final PreferenceSet prefs) throws Exception {
final Connection con = RDBMServices.getConnection();
final String selectPrefIds =
"SELECT PREF_ID " +
"FROM UP_PORTLET_DEFINITION_PREFS " +
"WHERE CHAN_ID=?";
final String deletePrefValues =
"DELETE FROM UP_PORTLET_PREF_VALUES " +
"WHERE PREF_ID=?";
final String deletePrefNames =
"DELETE FROM UP_PORTLET_DEFINITION_PREFS " +
"WHERE CHAN_ID=?";
final String insertPrefName =
"INSERT INTO UP_PORTLET_DEFINITION_PREFS " +
"(CHAN_ID, PORTLET_PREF_NAME, PORTLET_PREF_READONLY, PREF_ID) " +
"VALUES (?, ?, ?, ?)";
final String insertPrefValue =
"INSERT INTO UP_PORTLET_PREF_VALUES " +
"(PREF_ID, PORTLET_PREF_VALUE) " +
"VALUES (?, ?)";
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setDefinitionPreferences(chanId=" + chanId + ")");
try {
// Set autocommit false for the connection
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.setAutoCommit(con, false);
PreparedStatement selectPrefIdsPstmt = null;
PreparedStatement deletePrefValuesPstmt = null;
PreparedStatement deletePrefNamesPstmt = null;
PreparedStatement insertPrefNamePstmt = null;
PreparedStatement insertPrefValuePstmt = null;
try {
final LinkedList prefIds = new LinkedList();
selectPrefIdsPstmt = con.prepareStatement(selectPrefIds);
deletePrefValuesPstmt = con.prepareStatement(deletePrefValues);
deletePrefNamesPstmt = con.prepareStatement(deletePrefNames);
insertPrefNamePstmt = con.prepareStatement(insertPrefName);
insertPrefValuePstmt = con.prepareStatement(insertPrefValue);
//Get a list of all the preference names for this portlet
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setDefinitionPreferences(): " + selectPrefIds);
selectPrefIdsPstmt.setInt(1, chanId);
ResultSet rs = selectPrefIdsPstmt.executeQuery();
//Go through and remove all the values. Catalog the removed pref_id's so they can be re-used so
//the counter doesn't have to get hammered as much
try {
while (rs.next()) {
int prefId = rs.getInt("PREF_ID");
prefIds.add(new Integer(prefId));
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setDefinitionPreferences(PREF_ID=" + prefId + "): " + deletePrefValues);
deletePrefValuesPstmt.setInt(1, prefId);
deletePrefValuesPstmt.executeUpdate();
}
}
finally {
try { rs.close(); } catch (Exception e) { };
}
//Delete all the preference names for this portlet
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setDefinitionPreferences(): " + deletePrefNames);
deletePrefNamesPstmt.setInt(1, chanId);
deletePrefNamesPstmt.executeUpdate();
//Loop through the prefs, inserting each name then the values
for (Iterator prefItr = prefs.iterator(); prefItr.hasNext();) {
final Preference pref = (Preference)prefItr.next();
int prefId = -1;
insertPrefNamePstmt.setInt(1, chanId);
insertPrefNamePstmt.setString(2, pref.getName());
if (pref.isReadOnly()) {
insertPrefNamePstmt.setString(3, READ_ONLY_TRUE);
} else {
insertPrefNamePstmt.setString(3, READ_ONLY_FALSE);
}
//Use the list of removed ids to re-use IDs before generating new ones
if (prefIds.size() > 0) {
prefId = ((Integer)prefIds.removeLast()).intValue();
} else {
final ICounterStore counterStore = CounterStoreFactory.getCounterStoreImpl();
prefId = counterStore.getIncrementIntegerId(UP_PORTLET_PREFERENCE_VALUE);
}
insertPrefNamePstmt.setInt(4, prefId);
//Insert the name row
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setDefinitionPreferences(): " + insertPrefName);
insertPrefNamePstmt.executeUpdate();
//For each value a row will be inserted in the values table
for (final Iterator valueItr = pref.getValues(); valueItr.hasNext();) {
String value = (String)valueItr.next();
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setDefinitionPreferences(): " + insertPrefValue);
insertPrefValuePstmt.setInt(1, prefId);
insertPrefValuePstmt.setString(2, PREFIX + value);
insertPrefValuePstmt.executeUpdate();
}
}
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.commit(con);
}
catch (Exception e) {
// Roll back the transaction
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.rollback(con);
throw e;
}
finally {
try { selectPrefIdsPstmt.close(); } catch (Exception e) { }
try { deletePrefValuesPstmt.close(); } catch (Exception e) { }
try { deletePrefNamesPstmt.close(); } catch (Exception e) { }
try { insertPrefNamePstmt.close(); } catch (Exception e) { }
try { insertPrefValuePstmt.close(); } catch (Exception e) { }
}
}
finally {
RDBMServices.releaseConnection(con);
}
}
/**
* @see org.jasig.portal.IPortletPreferencesStore#getDefinitionPreferences(int)
*/
public PreferenceSet getDefinitionPreferences(final int chanId) throws Exception {
final PreferenceSetImpl prefs = new PreferenceSetImpl();
final Connection con = RDBMServices.getConnection();
final String selectPrefs =
"SELECT UPDP.PORTLET_PREF_NAME, UPDP.PORTLET_PREF_READONLY, UPPV.PORTLET_PREF_VALUE " +
"FROM UP_PORTLET_DEFINITION_PREFS UPDP, UP_PORTLET_PREF_VALUES UPPV " +
"WHERE UPDP.PREF_ID=UPPV.PREF_ID AND CHAN_ID=?";
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::getDefinitionPreferences(chanId=" + chanId + ")");
try {
PreparedStatement selectCurrentPrefsPstmt = null;
try {
selectCurrentPrefsPstmt = con.prepareStatement(selectPrefs);
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::getDefinitionPreferences(): " + selectPrefs);
selectCurrentPrefsPstmt.setInt(1, chanId);
final ResultSet rs = selectCurrentPrefsPstmt.executeQuery();
final Map prefsBuilder = new HashMap();
final Map readOnlyMap = new HashMap();
try {
while (rs.next()) {
final String prefName = rs.getString("PORTLET_PREF_NAME");
String prefValue = rs.getString("PORTLET_PREF_VALUE");
if (prefValue != null && prefValue.startsWith(PREFIX))
prefValue = prefValue.substring(PREFIX.length());
if (!readOnlyMap.containsKey(prefName)) {
if (READ_ONLY_TRUE.equals(rs.getString("PORTLET_PREF_READONLY"))) {
readOnlyMap.put(prefName, Boolean.TRUE);
}
else {
readOnlyMap.put(prefName, Boolean.FALSE);
}
}
List prefList = (List)prefsBuilder.get(prefName);
if (prefList == null)
{
prefList = new LinkedList();
prefsBuilder.put(prefName, prefList);
}
prefList.add(prefValue);
}
}
finally {
try { rs.close(); } catch (Exception e) { }
}
for (final Iterator prefKeyItr = prefsBuilder.keySet().iterator(); prefKeyItr.hasNext();) {
final String prefName = (String)prefKeyItr.next();
final List prefValues = (List)prefsBuilder.get(prefName);
final boolean readOnly = Boolean.TRUE.equals(readOnlyMap.get(prefName));
prefs.add(prefName, prefValues, readOnly);
}
}
finally {
try { selectCurrentPrefsPstmt.close(); } catch (Exception e) { }
}
}
finally {
RDBMServices.releaseConnection(con);
}
return prefs;
}
/**
* @see org.jasig.portal.IPortletPreferencesStore#setEntityPreferences(int, int, String, org.apache.pluto.om.common.PreferenceSet)
*/
public void setEntityPreferences(final int userId, final int layoutId, final String chanDescId, final PreferenceSet prefs) throws Exception {
final Connection con = RDBMServices.getConnection();
final String selectPrefIds =
"SELECT PREF_ID " +
"FROM UP_PORTLET_ENTITY_PREFS " +
"WHERE USER_ID=? AND LAYOUT_ID=? AND CHAN_DESC_ID=?";
final String deletePrefValues =
"DELETE FROM UP_PORTLET_PREF_VALUES " +
"WHERE PREF_ID=?";
final String deletePrefNames =
"DELETE FROM UP_PORTLET_ENTITY_PREFS " +
"WHERE USER_ID=? AND LAYOUT_ID=? AND CHAN_DESC_ID=?";
final String insertPrefName =
"INSERT INTO UP_PORTLET_ENTITY_PREFS " +
"(USER_ID, LAYOUT_ID, CHAN_DESC_ID, PORTLET_PREF_NAME, PREF_ID) " +
"VALUES (?, ?, ?, ?, ?)";
final String insertPrefValue =
"INSERT INTO UP_PORTLET_PREF_VALUES " +
"(PREF_ID, PORTLET_PREF_VALUE) " +
"VALUES (?, ?)";
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setEntityPreferences(userId=" + userId + ", layoutId=" + layoutId + ", chanDescId=" + chanDescId + ")");
try {
// Set autocommit false for the connection
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.setAutoCommit(con, false);
PreparedStatement selectPrefIdsPstmt = null;
PreparedStatement deletePrefValuesPstmt = null;
PreparedStatement deletePrefNamesPstmt = null;
PreparedStatement insertPrefNamePstmt = null;
PreparedStatement insertPrefValuePstmt = null;
try {
final LinkedList prefIds = new LinkedList();
selectPrefIdsPstmt = con.prepareStatement(selectPrefIds);
deletePrefValuesPstmt = con.prepareStatement(deletePrefValues);
deletePrefNamesPstmt = con.prepareStatement(deletePrefNames);
insertPrefNamePstmt = con.prepareStatement(insertPrefName);
insertPrefValuePstmt = con.prepareStatement(insertPrefValue);
//Get a list of all the preference names for this instance of this portlet
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setEntityPreferences(): " + selectPrefIds);
selectPrefIdsPstmt.setInt(1, userId);
selectPrefIdsPstmt.setInt(2, layoutId);
selectPrefIdsPstmt.setString(3, chanDescId);
ResultSet rs = selectPrefIdsPstmt.executeQuery();
//Go through and remove all the values. Catalog the removed pref_id's so they can be re-used so
//the counter doesn't have to get hammered as much
try {
while (rs.next()) {
int prefId = rs.getInt("PREF_ID");
prefIds.add(new Integer(prefId));
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setEntityPreferences(PREF_ID=" + prefId + "): " + deletePrefValues);
deletePrefValuesPstmt.setInt(1, prefId);
deletePrefValuesPstmt.executeUpdate();
}
}
finally {
try { rs.close(); } catch (Exception e) { };
}
//Delete all the preference names for this instance of this portlet
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setEntityPreferences(): " + deletePrefNames);
deletePrefNamesPstmt.setInt(1, userId);
deletePrefNamesPstmt.setInt(2, layoutId);
deletePrefNamesPstmt.setString(3, chanDescId);
deletePrefNamesPstmt.executeUpdate();
//Loop through the prefs, inserting each name then the values
for (Iterator prefItr = prefs.iterator(); prefItr.hasNext();) {
final Preference pref = (Preference)prefItr.next();
int prefId = -1;
insertPrefNamePstmt.setInt(1, userId);
insertPrefNamePstmt.setInt(2, layoutId);
insertPrefNamePstmt.setString(3, chanDescId);
insertPrefNamePstmt.setString(4, pref.getName());
//Use the list of removed ids to re-use IDs before generating new ones
if (prefIds.size() > 0) {
prefId = ((Integer)prefIds.removeLast()).intValue();
}
else {
final ICounterStore counterStore = CounterStoreFactory.getCounterStoreImpl();
try {
prefId = counterStore.getIncrementIntegerId(UP_PORTLET_PREFERENCE_VALUE);
}
catch (Exception e) {
counterStore.createCounter(UP_PORTLET_PREFERENCE_VALUE);
prefId = counterStore.getIncrementIntegerId(UP_PORTLET_PREFERENCE_VALUE);
}
}
insertPrefNamePstmt.setInt(5, prefId);
//Insert the name row
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setEntityPreferences(): " + insertPrefName);
insertPrefNamePstmt.executeUpdate();
//For each value a row will be inserted in the values table
for (final Iterator valueItr = pref.getValues(); valueItr.hasNext();) {
String value = (String)valueItr.next();
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::setEntityPreferences(): " + insertPrefValue);
insertPrefValuePstmt.setInt(1, prefId);
insertPrefValuePstmt.setString(2, PREFIX + value);
insertPrefValuePstmt.executeUpdate();
}
}
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.commit(con);
}
catch (Exception e) {
// Roll back the transaction
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.rollback(con);
throw e;
}
finally {
try { selectPrefIdsPstmt.close(); } catch (Exception e) { }
try { deletePrefValuesPstmt.close(); } catch (Exception e) { }
try { deletePrefNamesPstmt.close(); } catch (Exception e) { }
try { insertPrefNamePstmt.close(); } catch (Exception e) { }
try { insertPrefValuePstmt.close(); } catch (Exception e) { }
}
}
finally {
RDBMServices.releaseConnection(con);
}
}
/**
* @see org.jasig.portal.IPortletPreferencesStore#getEntityPreferences(int, int, java.lang.String)
*/
public PreferenceSet getEntityPreferences(final int userId, final int layoutId, final String chanDescId) throws Exception {
final PreferenceSetImpl prefs = new PreferenceSetImpl();
final Connection con = RDBMServices.getConnection();
final String selectPrefs =
"SELECT UPEP.PORTLET_PREF_NAME, UPPV.PORTLET_PREF_VALUE " +
"FROM UP_PORTLET_ENTITY_PREFS UPEP, UP_PORTLET_PREF_VALUES UPPV " +
"WHERE UPEP.PREF_ID=UPPV.PREF_ID AND UPEP.USER_ID=? AND UPEP.LAYOUT_ID=? AND UPEP.CHAN_DESC_ID=?";
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::getEntityPreferences(userId=" + userId + ", layoutId=" + layoutId + ", chanDescId=" + chanDescId + ")");
try {
PreparedStatement selectCurrentPrefsPstmt = null;
try {
selectCurrentPrefsPstmt = con.prepareStatement(selectPrefs);
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::getEntityPreferences(): " + selectPrefs);
selectCurrentPrefsPstmt.setInt(1, userId);
selectCurrentPrefsPstmt.setInt(2, layoutId);
selectCurrentPrefsPstmt.setString(3, chanDescId);
ResultSet rs = selectCurrentPrefsPstmt.executeQuery();
final Map prefsBuilder = new HashMap();
try {
while (rs.next()) {
final String prefName = rs.getString("PORTLET_PREF_NAME");
String prefValue = rs.getString("PORTLET_PREF_VALUE");
if (prefValue != null && prefValue.startsWith(PREFIX))
prefValue = prefValue.substring(PREFIX.length());
List prefList = (List)prefsBuilder.get(prefName);
if (prefList == null)
{
prefList = new LinkedList();
prefsBuilder.put(prefName, prefList);
}
prefList.add(prefValue);
}
}
finally {
try { rs.close(); } catch (Exception e) { }
}
for (final Iterator prefKeyItr = prefsBuilder.keySet().iterator(); prefKeyItr.hasNext();) {
final String prefName = (String)prefKeyItr.next();
final List prefValues = (List)prefsBuilder.get(prefName);
prefs.add(prefName, prefValues);
}
}
finally {
try { selectCurrentPrefsPstmt.close(); } catch (Exception e) { }
}
}
finally {
RDBMServices.releaseConnection(con);
}
return prefs;
}
/**
* @see org.jasig.portal.IPortletPreferencesStore#deletePortletPreferencesByUser(int)
*/
public void deletePortletPreferencesByUser(int userId) throws Exception {
final Connection con = RDBMServices.getConnection();
final String selectPrefIds =
"SELECT PREF_ID " +
"FROM UP_PORTLET_ENTITY_PREFS " +
"WHERE USER_ID=?";
final String deletePrefNames =
"DELETE FROM UP_PORTLET_ENTITY_PREFS " +
"WHERE USER_ID=?";
final String deletePrefValues =
"DELETE FROM UP_PORTLET_PREF_VALUES " +
"WHERE PREF_ID=?";
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::deletePortletPreferencesByUser(userId=" + userId + ")");
try {
// Set autocommit false for the connection
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.setAutoCommit(con, false);
PreparedStatement selectPrefIdsPstmt = null;
PreparedStatement deletePrefNamesPstmt = null;
PreparedStatement deletePrefValuesPstmt = null;
try {
selectPrefIdsPstmt = con.prepareStatement(selectPrefIds);
deletePrefNamesPstmt = con.prepareStatement(deletePrefNames);
deletePrefValuesPstmt = con.prepareStatement(deletePrefValues);
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::deletePortletPreferencesByUser(): " + selectPrefIds);
selectPrefIdsPstmt.setInt(1, userId);
ResultSet rs = selectPrefIdsPstmt.executeQuery();
try {
while (rs.next()) {
int prefId = rs.getInt("PREF_ID");
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::deletePortletPreferencesByUser(): " + deletePrefValues);
deletePrefValuesPstmt.setInt(1, prefId);
deletePrefValuesPstmt.executeUpdate();
}
}
finally {
try { rs.close(); } catch (Exception e) { }
}
deletePrefNamesPstmt.setInt(1, userId);
deletePrefNamesPstmt.executeUpdate();
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.commit(con);
}
catch (Exception e) {
// Roll back the transaction
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.rollback(con);
throw e;
}
finally {
try { selectPrefIdsPstmt.close(); } catch (Exception e) { }
try { deletePrefNamesPstmt.close(); } catch (Exception e) { }
try { deletePrefValuesPstmt.close(); } catch (Exception e) { }
}
}
finally {
RDBMServices.releaseConnection(con);
}
}
/**
* @see org.jasig.portal.IPortletPreferencesStore#deletePortletPreferencesByInstance(int, int, String)
*/
public void deletePortletPreferencesByInstance(final int userId, final int layoutId, final String chanDescId) throws Exception {
final Connection con = RDBMServices.getConnection();
final String selectPrefIds =
"SELECT PREF_ID " +
"FROM UP_PORTLET_ENTITY_PREFS " +
"WHERE USER_ID=? AND LAYOUT_ID=? AND CHAN_DESC_ID=?";
final String deletePrefNames =
"DELETE FROM UP_PORTLET_ENTITY_PREFS " +
"WHERE USER_ID=? AND LAYOUT_ID=? AND CHAN_DESC_ID=?";
final String deletePrefValues =
"DELETE FROM UP_PORTLET_PREF_VALUES " +
"WHERE PREF_ID=?";
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::deletePortletPreferencesByInstance(userId=" + userId + ", layoutId=" + layoutId + ", chanDescId=" + chanDescId + ")");
try {
// Set autocommit false for the connection
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.setAutoCommit(con, false);
PreparedStatement selectPrefIdsPstmt = null;
PreparedStatement deletePrefNamesPstmt = null;
PreparedStatement deletePrefValuesPstmt = null;
try {
selectPrefIdsPstmt = con.prepareStatement(selectPrefIds);
deletePrefNamesPstmt = con.prepareStatement(deletePrefNames);
deletePrefValuesPstmt = con.prepareStatement(deletePrefValues);
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::deletePortletPreferencesByInstance(): " + selectPrefIds);
selectPrefIdsPstmt.setInt(1, userId);
selectPrefIdsPstmt.setInt(2, layoutId);
selectPrefIdsPstmt.setString(3, chanDescId);
ResultSet rs = selectPrefIdsPstmt.executeQuery();
try {
while (rs.next()) {
int prefId = rs.getInt("PREF_ID");
if (log.isDebugEnabled())
log.debug("RDBMPortletPreferencesStore::deletePortletPreferencesByInstance(): " + deletePrefValues);
deletePrefValuesPstmt.setInt(1, prefId);
deletePrefValuesPstmt.executeUpdate();
}
}
finally {
try { rs.close(); } catch (Exception e) { }
}
deletePrefNamesPstmt.setInt(1, userId);
deletePrefNamesPstmt.setInt(2, layoutId);
deletePrefNamesPstmt.setString(3, chanDescId);
deletePrefNamesPstmt.executeUpdate();
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.commit(con);
}
catch (Exception e) {
// Roll back the transaction
if (RDBMServices.getDbMetaData().supportsTransactions())
RDBMServices.rollback(con);
throw e;
}
finally {
try { selectPrefIdsPstmt.close(); } catch (Exception e) { }
try { deletePrefNamesPstmt.close(); } catch (Exception e) { }
try { deletePrefValuesPstmt.close(); } catch (Exception e) { }
}
}
finally {
RDBMServices.releaseConnection(con);
}
}
}
|
package de.danoeh.antennapod.activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.VideoView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.viewpagerindicator.TabPageIndicator;
import de.danoeh.antennapod.PodcastApp;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.feed.FeedManager;
import de.danoeh.antennapod.feed.FeedMedia;
import de.danoeh.antennapod.fragment.CoverFragment;
import de.danoeh.antennapod.fragment.ItemDescriptionFragment;
import de.danoeh.antennapod.service.PlaybackService;
import de.danoeh.antennapod.service.PlayerStatus;
import de.danoeh.antennapod.util.Converter;
import de.danoeh.antennapod.util.FeedItemMenuHandler;
import de.danoeh.antennapod.util.MediaPlayerError;
import de.danoeh.antennapod.util.StorageUtils;
public class MediaplayerActivity extends SherlockFragmentActivity implements
SurfaceHolder.Callback {
private final String TAG = "MediaplayerActivity";
private static final int DEFAULT_SEEK_DELTA = 30000; // Seek-Delta to use
// when using FF or
// Rev Buttons
/** Current screen orientation. */
private int orientation;
/** True if video controls are currently visible. */
private boolean videoControlsShowing = true;
/** True if media information was loaded. */
private boolean mediaInfoLoaded = false;
private PlaybackService playbackService;
private MediaPositionObserver positionObserver;
private VideoControlsHider videoControlsToggler;
private FeedMedia media;
private PlayerStatus status;
private FeedManager manager;
// Widgets
private CoverFragment coverFragment;
private ItemDescriptionFragment descriptionFragment;
private ViewPager viewpager;
private TabPageIndicator tabs;
private MediaPlayerPagerAdapter pagerAdapter;
private VideoView videoview;
private TextView txtvStatus;
private TextView txtvPosition;
private TextView txtvLength;
private SeekBar sbPosition;
private ImageButton butPlay;
private ImageButton butRev;
private ImageButton butFF;
private LinearLayout videoOverlay;
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "Activity stopped");
try {
unregisterReceiver(statusUpdate);
} catch (IllegalArgumentException e) {
// ignore
}
try {
unregisterReceiver(notificationReceiver);
} catch (IllegalArgumentException e) {
// ignore
}
try {
unbindService(mConnection);
} catch (IllegalArgumentException e) {
// ignore
}
if (positionObserver != null) {
positionObserver.cancel(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.mediaplayer, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.support_item).setVisible(media != null && media.getItem().getPaymentLink() != null);
menu.findItem(R.id.share_link_item).setVisible(media != null && media.getItem().getLink() != null);
menu.findItem(R.id.visit_website_item).setVisible(media != null && media.getItem().getLink() != null);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
default:
return FeedItemMenuHandler.onMenuItemClicked(this, item, media.getItem());
}
return true;
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "Resuming Activity");
StorageUtils.checkStorageAvailability(this);
bindToService();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "Configuration changed");
orientation = newConfig.orientation;
if (positionObserver != null) {
positionObserver.cancel(true);
}
setupGUI();
handleStatus();
}
@Override
protected void onPause() {
super.onPause();
if (PlaybackService.isRunning && playbackService != null
&& playbackService.isPlayingVideo()) {
playbackService.stop();
}
if (videoControlsToggler != null) {
videoControlsToggler.cancel(true);
}
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Creating Activity");
StorageUtils.checkStorageAvailability(this);
orientation = getResources().getConfiguration().orientation;
manager = FeedManager.getInstance();
getWindow().setFormat(PixelFormat.TRANSPARENT);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bindToService();
}
private void bindToService() {
Intent serviceIntent = new Intent(this, PlaybackService.class);
boolean bound = false;
if (!PlaybackService.isRunning) {
Log.d(TAG, "Trying to restore last played media");
SharedPreferences prefs = getApplicationContext()
.getSharedPreferences(PodcastApp.PREF_NAME, 0);
long mediaId = prefs.getLong(PlaybackService.PREF_LAST_PLAYED_ID,
-1);
long feedId = prefs.getLong(
PlaybackService.PREF_LAST_PLAYED_FEED_ID, -1);
if (mediaId != -1 && feedId != -1) {
serviceIntent.putExtra(PlaybackService.EXTRA_FEED_ID, feedId);
serviceIntent.putExtra(PlaybackService.EXTRA_MEDIA_ID, mediaId);
serviceIntent.putExtra(
PlaybackService.EXTRA_START_WHEN_PREPARED, false);
serviceIntent.putExtra(PlaybackService.EXTRA_SHOULD_STREAM,
prefs.getBoolean(PlaybackService.PREF_LAST_IS_STREAM,
true));
startService(serviceIntent);
bound = bindService(serviceIntent, mConnection,
Context.BIND_AUTO_CREATE);
} else {
Log.d(TAG, "No last played media found");
status = PlayerStatus.STOPPED;
setupGUI();
handleStatus();
}
} else {
bound = bindService(serviceIntent, mConnection, 0);
}
Log.d(TAG, "Result for service binding: " + bound);
}
private void handleStatus() {
switch (status) {
case ERROR:
setStatusMsg(R.string.player_error_msg, View.VISIBLE);
break;
case PAUSED:
setStatusMsg(R.string.player_paused_msg, View.VISIBLE);
loadMediaInfo();
if (positionObserver != null) {
positionObserver.cancel(true);
positionObserver = null;
}
butPlay.setImageResource(R.drawable.av_play);
break;
case PLAYING:
setStatusMsg(R.string.player_playing_msg, View.INVISIBLE);
loadMediaInfo();
setupPositionObserver();
butPlay.setImageResource(R.drawable.av_pause);
break;
case PREPARING:
setStatusMsg(R.string.player_preparing_msg, View.VISIBLE);
loadMediaInfo();
break;
case STOPPED:
setStatusMsg(R.string.player_stopped_msg, View.VISIBLE);
break;
case PREPARED:
loadMediaInfo();
setStatusMsg(R.string.player_ready_msg, View.VISIBLE);
butPlay.setImageResource(R.drawable.av_play);
break;
case SEEKING:
setStatusMsg(R.string.player_seeking_msg, View.VISIBLE);
break;
case AWAITING_VIDEO_SURFACE:
Log.d(TAG, "Preparing video playback");
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
private void setStatusMsg(int resId, int visibility) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (visibility == View.VISIBLE) {
txtvStatus.setText(resId);
}
txtvStatus.setVisibility(visibility);
}
}
private void setupPositionObserver() {
if (positionObserver == null || positionObserver.isCancelled()) {
positionObserver = new MediaPositionObserver() {
@Override
protected void onProgressUpdate(Void... v) {
super.onProgressUpdate();
txtvPosition.setText(Converter
.getDurationStringLong(playbackService.getPlayer()
.getCurrentPosition()));
txtvLength.setText(Converter
.getDurationStringLong(playbackService.getPlayer()
.getDuration()));
updateProgressbarPosition();
}
};
positionObserver.execute(playbackService.getPlayer());
}
}
private void updateProgressbarPosition() {
Log.d(TAG, "Updating progressbar info");
MediaPlayer player = playbackService.getPlayer();
float progress = ((float) player.getCurrentPosition())
/ player.getDuration();
sbPosition.setProgress((int) (progress * sbPosition.getMax()));
}
private void loadMediaInfo() {
if (!mediaInfoLoaded) {
Log.d(TAG, "Loading media info");
if (media != null) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
getSupportActionBar().setSubtitle(
media.getItem().getTitle());
getSupportActionBar().setTitle(
media.getItem().getFeed().getTitle());
pagerAdapter.notifyDataSetChanged();
}
txtvPosition.setText(Converter.getDurationStringLong((media
.getPosition())));
if (!playbackService.isShouldStream()) {
txtvLength.setText(Converter.getDurationStringLong(media
.getDuration()));
float progress = ((float) media.getPosition())
/ media.getDuration();
sbPosition.setProgress((int) (progress * sbPosition
.getMax()));
}
}
mediaInfoLoaded = true;
}
}
private void setupGUI() {
setContentView(R.layout.mediaplayer_activity);
sbPosition = (SeekBar) findViewById(R.id.sbPosition);
txtvPosition = (TextView) findViewById(R.id.txtvPosition);
txtvLength = (TextView) findViewById(R.id.txtvLength);
butPlay = (ImageButton) findViewById(R.id.butPlay);
butRev = (ImageButton) findViewById(R.id.butRev);
butFF = (ImageButton) findViewById(R.id.butFF);
// SEEKBAR SETUP
sbPosition.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int duration;
float prog;
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
prog = progress / ((float) seekBar.getMax());
duration = playbackService.getPlayer().getDuration();
txtvPosition.setText(Converter
.getDurationStringLong((int) (prog * duration)));
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// interrupt position Observer, restart later
if (positionObserver != null) {
positionObserver.cancel(true);
positionObserver = null;
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
playbackService.seek((int) (prog * duration));
setupPositionObserver();
}
});
// BUTTON SETUP
butPlay.setOnClickListener(playbuttonListener);
butFF.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.seekDelta(DEFAULT_SEEK_DELTA);
}
}
});
butRev.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.seekDelta(-DEFAULT_SEEK_DELTA);
}
}
});
// PORTRAIT ORIENTATION SETUP
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
txtvStatus = (TextView) findViewById(R.id.txtvStatus);
viewpager = (ViewPager) findViewById(R.id.viewpager);
tabs = (TabPageIndicator) findViewById(R.id.tabs);
pagerAdapter = new MediaPlayerPagerAdapter(
getSupportFragmentManager(), 2, this);
viewpager.setAdapter(pagerAdapter);
tabs.setViewPager(viewpager);
} else {
videoOverlay = (LinearLayout) findViewById(R.id.overlay);
videoview = (VideoView) findViewById(R.id.videoview);
videoview.getHolder().addCallback(this);
videoview.setOnClickListener(playbuttonListener);
videoview.setOnTouchListener(onVideoviewTouched);
setupVideoControlsToggler();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
private OnClickListener playbuttonListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (status == PlayerStatus.PLAYING) {
playbackService.pause(true);
} else if (status == PlayerStatus.PAUSED
|| status == PlayerStatus.PREPARED) {
playbackService.play();
}
}
};
private View.OnTouchListener onVideoviewTouched = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (videoControlsToggler != null) {
videoControlsToggler.cancel(true);
}
toggleVideoControlsVisibility();
if (videoControlsShowing) {
setupVideoControlsToggler();
}
return true;
} else {
return false;
}
}
};
private void setupVideoControlsToggler() {
if (videoControlsToggler != null) {
videoControlsToggler.cancel(true);
}
videoControlsToggler = new VideoControlsHider();
videoControlsToggler.execute();
}
private void toggleVideoControlsVisibility() {
if (videoControlsShowing) {
getSupportActionBar().hide();
videoOverlay.setVisibility(View.GONE);
} else {
getSupportActionBar().show();
videoOverlay.setVisibility(View.VISIBLE);
}
videoControlsShowing = !videoControlsShowing;
}
private void handleError(int errorCode) {
final AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
errorDialog.setTitle(R.string.error_label);
errorDialog
.setMessage(MediaPlayerError.getErrorString(this, errorCode));
errorDialog.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
errorDialog.create().show();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
playbackService = ((PlaybackService.LocalBinder) service)
.getService();
int requestedOrientation;
status = playbackService.getStatus();
media = playbackService.getMedia();
invalidateOptionsMenu();
registerReceiver(statusUpdate, new IntentFilter(
PlaybackService.ACTION_PLAYER_STATUS_CHANGED));
registerReceiver(notificationReceiver, new IntentFilter(
PlaybackService.ACTION_PLAYER_NOTIFICATION));
if (playbackService.isPlayingVideo()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
// check if orientation is correct
if ((requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && orientation == Configuration.ORIENTATION_LANDSCAPE)
|| (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation == Configuration.ORIENTATION_PORTRAIT)) {
Log.d(TAG, "Orientation correct");
setupGUI();
handleStatus();
} else {
Log.d(TAG,
"Orientation incorrect, waiting for orientation change");
}
Log.d(TAG, "Connection to Service established");
}
@Override
public void onServiceDisconnected(ComponentName name) {
playbackService = null;
Log.d(TAG, "Disconnected from Service");
}
};
private BroadcastReceiver statusUpdate = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Received statusUpdate Intent.");
status = playbackService.getStatus();
handleStatus();
}
};
private BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int type = intent.getIntExtra(
PlaybackService.EXTRA_NOTIFICATION_TYPE, -1);
int code = intent.getIntExtra(
PlaybackService.EXTRA_NOTIFICATION_CODE, -1);
if (code != -1 && type != -1) {
switch (type) {
case PlaybackService.NOTIFICATION_TYPE_ERROR:
handleError(code);
break;
case PlaybackService.NOTIFICATION_TYPE_BUFFER_UPDATE:
if (sbPosition != null) {
float progress = ((float) code) / 100;
sbPosition.setSecondaryProgress((int) progress
* sbPosition.getMax());
}
break;
case PlaybackService.NOTIFICATION_TYPE_RELOAD:
try {
unbindService(mConnection);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
if (positionObserver != null) {
positionObserver.cancel(true);
positionObserver = null;
}
mediaInfoLoaded = false;
bindToService();
break;
}
} else {
Log.d(TAG, "Bad arguments. Won't handle intent");
}
}
};
/** Refreshes the current position of the media file that is playing. */
public class MediaPositionObserver extends
AsyncTask<MediaPlayer, Void, Void> {
private static final String TAG = "MediaPositionObserver";
private static final int WAITING_INTERVALL = 1000;
private MediaPlayer player;
@Override
protected void onCancelled() {
Log.d(TAG, "Task was cancelled");
}
@Override
protected Void doInBackground(MediaPlayer... p) {
Log.d(TAG, "Background Task started");
player = p[0];
try {
while (player.isPlaying() && !isCancelled()) {
try {
Thread.sleep(WAITING_INTERVALL);
} catch (InterruptedException e) {
Log.d(TAG,
"Thread was interrupted while waiting. Finishing now");
return null;
}
publishProgress();
}
} catch (IllegalStateException e) {
Log.d(TAG, "player is in illegal state, exiting now");
}
Log.d(TAG, "Background Task finished");
return null;
}
}
/** Hides the videocontrols after a certain period of time. */
public class VideoControlsHider extends AsyncTask<Void, Void, Void> {
@Override
protected void onCancelled() {
videoControlsToggler = null;
}
@Override
protected void onPostExecute(Void result) {
videoControlsToggler = null;
}
private static final int WAITING_INTERVALL = 5000;
private static final String TAG = "VideoControlsToggler";
@Override
protected void onProgressUpdate(Void... values) {
if (videoControlsShowing) {
Log.d(TAG, "Hiding video controls");
getSupportActionBar().hide();
videoOverlay.setVisibility(View.GONE);
videoControlsShowing = false;
}
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(WAITING_INTERVALL);
} catch (InterruptedException e) {
return null;
}
publishProgress();
return null;
}
}
private boolean holderCreated;
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
holder.setFixedSize(width, height);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
holderCreated = true;
Log.d(TAG, "Videoview holder created");
if (status == PlayerStatus.AWAITING_VIDEO_SURFACE) {
playbackService.setVideoSurface(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
holderCreated = false;
}
public static class MediaPlayerPagerAdapter extends FragmentPagerAdapter {
private int numItems;
private MediaplayerActivity activity;
private static final int POS_COVER = 0;
private static final int POS_DESCR = 1;
private static final int POS_CHAPTERS = 2;
public MediaPlayerPagerAdapter(FragmentManager fm, int numItems,
MediaplayerActivity activity) {
super(fm);
this.numItems = numItems;
this.activity = activity;
}
@Override
public Fragment getItem(int position) {
if (activity.media != null) {
switch (position) {
case POS_COVER:
activity.coverFragment = CoverFragment
.newInstance(activity.media.getItem());
return activity.coverFragment;
case POS_DESCR:
activity.descriptionFragment = ItemDescriptionFragment
.newInstance(activity.media.getItem(), true);
return activity.descriptionFragment;
default:
return CoverFragment.newInstance(null);
}
} else {
return CoverFragment.newInstance(null);
}
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case POS_COVER:
return activity.getString(R.string.cover_label);
case POS_DESCR:
return activity.getString(R.string.description_label);
default:
return super.getPageTitle(position);
}
}
@Override
public int getCount() {
return numItems;
}
@Override
public int getItemPosition(Object object) {
return POSITION_UNCHANGED;
}
}
}
|
package org.umlg.sqlg.test;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.tinkerpop.gremlin.AbstractGremlinTest;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.*;
import org.apache.tinkerpop.gremlin.structure.io.GraphReader;
import org.apache.tinkerpop.gremlin.structure.io.gryo.GryoIo;
import org.apache.tinkerpop.gremlin.structure.io.gryo.GryoReader;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.junit.*;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.umlg.sqlg.sql.dialect.SqlDialect;
import org.umlg.sqlg.structure.SqlgDataSource;
import org.umlg.sqlg.structure.SqlgGraph;
import org.umlg.sqlg.util.SqlgUtil;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.sql.*;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public abstract class BaseTest {
private static Logger logger = LoggerFactory.getLogger(BaseTest.class.getName());
protected SqlgGraph sqlgGraph;
protected GraphTraversalSource gt;
protected static Configuration configuration;
@Rule
public TestRule watcher = new TestWatcher() {
protected void starting(Description description) {
logger.info("Starting test: " + description.getClass() + "." + description.getMethodName());
}
protected void finished(Description description) {
logger.info("Finished test: " + description.getClass() + "." + description.getMethodName());
}
};
@BeforeClass
public static void beforeClass() throws ClassNotFoundException, IOException, PropertyVetoException {
URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties");
try {
configuration = new PropertiesConfiguration(sqlProperties);
if (!configuration.containsKey("jdbc.url")) {
throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url"));
}
} catch (ConfigurationException e) {
throw new RuntimeException(e);
}
}
@Before
public void before() throws Exception {
this.sqlgGraph = SqlgGraph.open(configuration);
SqlgUtil.dropDb(this.sqlgGraph);
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
this.sqlgGraph = SqlgGraph.open(configuration);
this.gt = this.sqlgGraph.traversal();
}
@After
public void after() throws Exception {
this.sqlgGraph.tx().onClose(Transaction.CLOSE_BEHAVIOR.ROLLBACK);
this.sqlgGraph.close();
}
// @Before
public void beforeOld() throws IOException {
SqlgDataSource sqlgDataSource = null;
SqlDialect sqlDialect;
try {
Class<?> sqlDialectClass = findSqlgDialect();
Constructor<?> constructor = sqlDialectClass.getConstructor(Configuration.class);
sqlDialect = (SqlDialect) constructor.newInstance(configuration);
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
sqlgDataSource = SqlgDataSource.setupDataSource(
sqlDialect.getJdbcDriver(),
configuration);
Connection conn;
try {
conn = sqlgDataSource.get(configuration.getString("jdbc.url")).getConnection();
DatabaseMetaData metadata = conn.getMetaData();
if (sqlDialect.supportsCascade()) {
String catalog = null;
String schemaPattern = null;
String tableNamePattern = "%";
String[] types = {"TABLE"};
ResultSet result = metadata.getTables(catalog, schemaPattern, tableNamePattern, types);
while (result.next()) {
String schema = result.getString(2);
String table = result.getString(3);
if (sqlDialect.getGisSchemas().contains(schema) || sqlDialect.getSpacialRefTable().contains(table)) {
continue;
}
StringBuilder sql = new StringBuilder("DROP TABLE ");
sql.append(sqlDialect.maybeWrapInQoutes(schema));
sql.append(".");
sql.append(sqlDialect.maybeWrapInQoutes(table));
sql.append(" CASCADE");
if (sqlDialect.needsSemicolon()) {
sql.append(";");
}
try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) {
preparedStatement.executeUpdate();
}
}
catalog = null;
schemaPattern = null;
result = metadata.getSchemas(catalog, schemaPattern);
while (result.next()) {
String schema = result.getString(1);
if (!sqlDialect.getDefaultSchemas().contains(schema) && !sqlDialect.getGisSchemas().contains(schema)) {
StringBuilder sql = new StringBuilder("DROP SCHEMA ");
sql.append(sqlDialect.maybeWrapInQoutes(schema));
sql.append(" CASCADE");
if (sqlDialect.needsSemicolon()) {
sql.append(";");
}
try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) {
preparedStatement.executeUpdate();
}
}
}
} else if (!sqlDialect.supportSchemas()) {
ResultSet result = metadata.getCatalogs();
while (result.next()) {
StringBuilder sql = new StringBuilder("DROP DATABASE ");
String database = result.getString(1);
if (!sqlDialect.getDefaultSchemas().contains(database)) {
sql.append(sqlDialect.maybeWrapInQoutes(database));
if (sqlDialect.needsSemicolon()) {
sql.append(";");
}
try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) {
preparedStatement.executeUpdate();
}
}
}
} else {
conn.setAutoCommit(false);
JDBC.dropSchema(metadata, "APP");
conn.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
} finally {
if (sqlgDataSource != null)
sqlgDataSource.close(configuration.getString("jdbc.url"));
}
this.sqlgGraph = SqlgGraph.open(configuration);
this.gt = this.sqlgGraph.traversal();
}
protected GraphTraversal<Vertex, Vertex> vertexTraversal(Vertex v) {
return this.sqlgGraph.traversal().V(v);
}
protected GraphTraversal<Vertex, Vertex> vertexTraversal2(Vertex v) {
return this.sqlgGraph.traversal().V(v);
}
protected GraphTraversal<Edge, Edge> edgeTraversal(Edge e) {
return this.sqlgGraph.traversal().E(e.id());
}
protected void assertDb(String table, int numberOfRows) {
Connection conn = null;
Statement stmt = null;
try {
conn = this.sqlgGraph.getSqlgDataSource().get(this.sqlgGraph.getJdbcUrl()).getConnection();
stmt = conn.createStatement();
StringBuilder sql = new StringBuilder("SELECT * FROM ");
sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(this.sqlgGraph.getSqlDialect().getPublicSchema()));
sql.append(".");
sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(table));
if (this.sqlgGraph.getSqlDialect().needsSemicolon()) {
sql.append(";");
}
if (logger.isDebugEnabled()) {
logger.debug(sql.toString());
}
ResultSet rs = stmt.executeQuery(sql.toString());
int countRows = 0;
while (rs.next()) {
countRows++;
}
assertEquals(numberOfRows, countRows);
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
fail(e.getMessage());
} finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
fail(se.getMessage());
}
}
}
private Class<?> findSqlgDialect() {
try {
return Class.forName("org.umlg.sqlg.sql.dialect.PostgresDialect");
} catch (ClassNotFoundException e) {
}
try {
return Class.forName("org.umlg.sqlg.sql.dialect.MariaDbDialect");
} catch (ClassNotFoundException e) {
}
try {
return Class.forName("org.umlg.sqlg.sql.dialect.HsqldbDialect");
} catch (ClassNotFoundException e) {
}
throw new IllegalStateException("No sqlg dialect found!");
}
public void printTraversalForm(final Traversal traversal) {
final boolean muted = Boolean.parseBoolean(System.getProperty("muteTestLogs", "false"));
if (!muted) System.out.println(" pre-strategy:" + traversal);
traversal.hasNext();
if (!muted) System.out.println(" post-strategy:" + traversal);
}
protected void loadModern(SqlgGraph sqlgGraph) {
Graph g = sqlgGraph;
final GraphReader initreader = GryoReader.build().create();
try (final InputStream stream = AbstractGremlinTest.class.getResourceAsStream("/org/apache/tinkerpop/gremlin/structure/io/gryo/tinkerpop-modern.kryo")) {
initreader.readGraph(stream, g);
} catch (IOException e) {
Assert.fail(e.getMessage());
}
}
protected void loadModern() {
loadModern(this.sqlgGraph);
}
protected void loadGratefulDead() {
try {
final InputStream stream = AbstractGremlinTest.class.getResourceAsStream("/org/apache/tinkerpop/gremlin/structure/io/gryo/grateful-dead.kryo");
final GraphReader gryoReader = GryoReader.build()
.mapper(this.sqlgGraph.io(GryoIo.build()).mapper().create())
.create();
gryoReader.readGraph(stream, this.sqlgGraph);
} catch (IOException e) {
Assert.fail(e.getMessage());
}
}
/**
* Looks up the identifier as generated by the current source graph being tested.
*
* @param vertexName a unique string that will identify a graph element within a graph
* @return the id as generated by the graph
*/
public Object convertToVertexId(final String vertexName) {
return convertToVertexId(this.sqlgGraph, vertexName);
}
/**
* Looks up the identifier as generated by the current source graph being tested.
*
* @param g the graph to get the element id from
* @param vertexName a unique string that will identify a graph element within a graph
* @return the id as generated by the graph
*/
public Object convertToVertexId(final Graph g, final String vertexName) {
return convertToVertex(g, vertexName).id();
}
public Vertex convertToVertex(final Graph graph, final String vertexName) {
// all test graphs have "name" as a unique id which makes it easy to hardcode this...works for now
return graph.traversal().V().has("name", vertexName).next();
}
// public Object convertToEdgeId(final String outVertexName, String edgeLabel, final String inVertexName) {
// return convertToEdgeId(graph, outVertexName, edgeLabel, inVertexName);
public Object convertToEdgeId(final Graph graph, final String outVertexName, String edgeLabel, final String inVertexName) {
return graph.traversal().V().has("name", outVertexName).outE(edgeLabel).as("e").inV().has("name", inVertexName).<Edge>select("e").next().id();
}
public static void assertModernGraph(final Graph g1, final boolean assertDouble, final boolean lossyForId) {
assertToyGraph(g1, assertDouble, lossyForId, true);
}
private static void assertToyGraph(final Graph g1, final boolean assertDouble, final boolean lossyForId, final boolean assertSpecificLabel) {
assertEquals(new Long(6), g1.traversal().V().count().next());
assertEquals(new Long(6), g1.traversal().E().count().next());
final Vertex v1 = (Vertex) g1.traversal().V().has("name", "marko").next();
assertEquals(29, v1.<Integer>value("age").intValue());
assertEquals(2, v1.keys().size());
assertEquals(assertSpecificLabel ? "person" : Vertex.DEFAULT_LABEL, v1.label());
assertId(g1, lossyForId, v1, 1);
final List<Edge> v1Edges = g1.traversal().V(v1.id()).bothE().toList();
assertEquals(3, v1Edges.size());
v1Edges.forEach(e -> {
if (g1.traversal().E(e.id()).inV().values("name").next().equals("vadas")) {
assertEquals("knows", e.label());
if (assertDouble)
assertEquals(0.5d, e.value("weight"), 0.0001d);
else
assertEquals(0.5f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 7);
} else if (g1.traversal().E(e.id()).inV().values("name").next().equals("josh")) {
assertEquals("knows", e.label());
if (assertDouble)
assertEquals(1.0, e.value("weight"), 0.0001d);
else
assertEquals(1.0f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 8);
} else if (g1.traversal().E(e.id()).inV().values("name").next().equals("lop")) {
assertEquals("created", e.label());
if (assertDouble)
assertEquals(0.4d, e.value("weight"), 0.0001d);
else
assertEquals(0.4f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 9);
} else {
fail("Edge not expected");
}
});
final Vertex v2 = (Vertex) g1.traversal().V().has("name", "vadas").next();
assertEquals(27, v2.<Integer>value("age").intValue());
assertEquals(2, v2.keys().size());
assertEquals(assertSpecificLabel ? "person" : Vertex.DEFAULT_LABEL, v2.label());
assertId(g1, lossyForId, v2, 2);
final List<Edge> v2Edges = g1.traversal().V(v2.id()).bothE().toList();
assertEquals(1, v2Edges.size());
v2Edges.forEach(e -> {
if (g1.traversal().E(e.id()).outV().values("name").next().equals("marko")) {
assertEquals("knows", e.label());
if (assertDouble)
assertEquals(0.5d, e.value("weight"), 0.0001d);
else
assertEquals(0.5f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 7);
} else {
fail("Edge not expected");
}
});
final Vertex v3 = (Vertex) g1.traversal().V().has("name", "lop").next();
assertEquals("java", v3.<String>value("lang"));
assertEquals(2, v2.keys().size());
assertEquals(assertSpecificLabel ? "software" : Vertex.DEFAULT_LABEL, v3.label());
assertId(g1, lossyForId, v3, 3);
final List<Edge> v3Edges = g1.traversal().V(v3.id()).bothE().toList();
assertEquals(3, v3Edges.size());
v3Edges.forEach(e -> {
if (g1.traversal().E(e.id()).outV().values("name").next().equals("peter")) {
assertEquals("created", e.label());
if (assertDouble)
assertEquals(0.2d, e.value("weight"), 0.0001d);
else
assertEquals(0.2f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 12);
} else if (g1.traversal().E(e.id()).outV().next().value("name").equals("josh")) {
assertEquals("created", e.label());
if (assertDouble)
assertEquals(0.4d, e.value("weight"), 0.0001d);
else
assertEquals(0.4f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 11);
} else if (g1.traversal().E(e.id()).outV().values("name").next().equals("marko")) {
assertEquals("created", e.label());
if (assertDouble)
assertEquals(0.4d, e.value("weight"), 0.0001d);
else
assertEquals(0.4f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 9);
} else {
fail("Edge not expected");
}
});
final Vertex v4 = (Vertex) g1.traversal().V().has("name", "josh").next();
assertEquals(32, v4.<Integer>value("age").intValue());
assertEquals(2, v4.keys().size());
assertEquals(assertSpecificLabel ? "person" : Vertex.DEFAULT_LABEL, v4.label());
assertId(g1, lossyForId, v4, 4);
final List<Edge> v4Edges = g1.traversal().V(v4.id()).bothE().toList();
assertEquals(3, v4Edges.size());
v4Edges.forEach(e -> {
if (e.inVertex().values("name").next().equals("ripple")) {
assertEquals("created", e.label());
if (assertDouble)
assertEquals(1.0d, e.value("weight"), 0.0001d);
else
assertEquals(1.0f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 10);
} else if (e.inVertex().values("name").next().equals("lop")) {
assertEquals("created", e.label());
if (assertDouble)
assertEquals(0.4d, e.value("weight"), 0.0001d);
else
assertEquals(0.4f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 11);
} else if (e.outVertex().values("name").next().equals("marko")) {
assertEquals("knows", e.label());
if (assertDouble)
assertEquals(1.0d, e.value("weight"), 0.0001d);
else
assertEquals(1.0f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 8);
} else {
fail("Edge not expected");
}
});
final Vertex v5 = (Vertex) g1.traversal().V().has("name", "ripple").next();
assertEquals("java", v5.<String>value("lang"));
assertEquals(2, v5.keys().size());
assertEquals(assertSpecificLabel ? "software" : Vertex.DEFAULT_LABEL, v5.label());
assertId(g1, lossyForId, v5, 5);
final List<Edge> v5Edges = IteratorUtils.list(v5.edges(Direction.BOTH));
assertEquals(1, v5Edges.size());
v5Edges.forEach(e -> {
if (e.outVertex().values("name").next().equals("josh")) {
assertEquals("created", e.label());
if (assertDouble)
assertEquals(1.0d, e.value("weight"), 0.0001d);
else
assertEquals(1.0f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 10);
} else {
fail("Edge not expected");
}
});
final Vertex v6 = (Vertex) g1.traversal().V().has("name", "peter").next();
assertEquals(35, v6.<Integer>value("age").intValue());
assertEquals(2, v6.keys().size());
assertEquals(assertSpecificLabel ? "person" : Vertex.DEFAULT_LABEL, v6.label());
assertId(g1, lossyForId, v6, 6);
final List<Edge> v6Edges = IteratorUtils.list(v6.edges(Direction.BOTH));
assertEquals(1, v6Edges.size());
v6Edges.forEach(e -> {
if (e.inVertex().values("name").next().equals("lop")) {
assertEquals("created", e.label());
if (assertDouble)
assertEquals(0.2d, e.value("weight"), 0.0001d);
else
assertEquals(0.2f, e.value("weight"), 0.0001f);
assertEquals(1, e.keys().size());
assertId(g1, lossyForId, e, 12);
} else {
fail("Edge not expected");
}
});
}
private static void assertId(final Graph g, final boolean lossyForId, final Element e, final Object expected) {
if (g.features().edge().supportsUserSuppliedIds()) {
if (lossyForId)
assertEquals(expected.toString(), e.id().toString());
else
assertEquals(expected, e.id());
}
}
}
|
package de.lmu.ifi.dbs.elki.algorithm.clustering;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.data.Cluster;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.data.model.OPTICSModel;
import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil;
import de.lmu.ifi.dbs.elki.database.ids.HashSetModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.ids.ModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.distance.distancevalue.NumberDistance;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.result.ClusterOrderEntry;
import de.lmu.ifi.dbs.elki.result.ClusterOrderResult;
import de.lmu.ifi.dbs.elki.result.IterableResult;
import de.lmu.ifi.dbs.elki.utilities.datastructures.hierarchy.HierarchyHashmapList;
import de.lmu.ifi.dbs.elki.utilities.datastructures.hierarchy.ModifiableHierarchy;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ClassParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter;
/**
* Class to handle OPTICS Xi extraction.
*
* @author Erich Schubert
*
* @apiviz.has SteepAreaResult
*
* @param <N> Number distance used by OPTICS
*/
public class OPTICSXi<N extends NumberDistance<N, ?>> extends AbstractAlgorithm<Clustering<OPTICSModel>> implements ClusteringAlgorithm<Clustering<OPTICSModel>> {
/**
* The logger for this class.
*/
private static final Logging logger = Logging.getLogger(OPTICSXi.class);
/**
* Parameter to specify the actual OPTICS algorithm to use.
*/
public static final OptionID XIALG_ID = OptionID.getOrCreateOptionID("opticsxi.algorithm", "The actual OPTICS-type algorithm to use.");
/**
* Parameter to specify the steepness threshold.
*/
public static final OptionID XI_ID = OptionID.getOrCreateOptionID("opticsxi.xi", "Threshold for the steepness requirement.");
/**
* The actual algorithm we use.
*/
OPTICSTypeAlgorithm<N> optics;
/**
* Xi parameter
*/
double xi;
/**
* Constructor.
*
* @param optics OPTICS algorithm to use
* @param xi Xi value
*/
public OPTICSXi(OPTICSTypeAlgorithm<N> optics, double xi) {
super();
this.optics = optics;
this.xi = xi;
}
public Clustering<OPTICSModel> run(Database database, Relation<?> relation) {
// TODO: ensure we are using the same relation?
ClusterOrderResult<N> opticsresult = optics.run(database);
if(!NumberDistance.class.isInstance(optics.getDistanceFactory())) {
logger.verbose("Xi cluster extraction only supported for number distances!");
return null;
}
if(logger.isVerbose()) {
logger.verbose("Extracting clusters with Xi: " + xi);
}
return extractClusters(opticsresult, relation, 1.0 - xi, optics.getMinPts());
}
/**
* Extract clusters from a cluster order result.
*
* @param clusterOrderResult cluster order result
* @param relation Relation
* @param ixi Parameter 1 - Xi
* @param minpts Parameter minPts
*/
// TODO: resolve handling of the last point in the cluster order
private Clustering<OPTICSModel> extractClusters(ClusterOrderResult<N> clusterOrderResult, Relation<?> relation, double ixi, int minpts) {
// TODO: add progress?
List<ClusterOrderEntry<N>> clusterOrder = clusterOrderResult.getClusterOrder();
double mib = 0.0;
// TODO: make it configurable to keep this list; this is mostly useful for
// visualization
List<SteepArea> salist = new ArrayList<SteepArea>();
List<SteepDownArea> sdaset = new java.util.Vector<SteepDownArea>();
ModifiableHierarchy<Cluster<OPTICSModel>> hier = new HierarchyHashmapList<Cluster<OPTICSModel>>();
HashSet<Cluster<OPTICSModel>> curclusters = new HashSet<Cluster<OPTICSModel>>();
HashSetModifiableDBIDs unclaimedids = DBIDUtil.newHashSet(relation.getDBIDs());
SteepScanPosition<N> scan = new SteepScanPosition<N>(clusterOrder);
while(scan.hasNext()) {
final int curpos = scan.index;
// Update maximum-inbetween
mib = Math.max(mib, scan.ecurr.getReachability().doubleValue());
// The last point cannot be the start of a steep area.
if(scan.esucc != null) {
// Xi-steep down area
if(scan.steepDown(ixi)) {
// Update mib values with current mib and filter
updateFilterSDASet(mib, sdaset, ixi);
final double startval = scan.ecurr.getReachability().doubleValue();
int startsteep = scan.index;
int endsteep = Math.min(scan.index + 1, clusterOrder.size());
{
while(scan.hasNext()) {
scan.next();
// not going downward at all - stop here.
if(!scan.steepDown(1.0)) {
break;
}
// still steep - continue.
if(scan.steepDown(ixi)) {
endsteep = Math.min(scan.index + 1, clusterOrder.size());
}
else {
// Stop looking after minpts "flat" steps.
if(scan.index - endsteep > minpts) {
break;
}
}
}
}
mib = clusterOrder.get(endsteep).getReachability().doubleValue();
final SteepDownArea sda = new SteepDownArea(startsteep, endsteep, startval, 0);
if(logger.isDebuggingFinest()) {
logger.debugFinest("Xi " + sda.toString());
}
sdaset.add(sda);
if(salist != null) {
salist.add(sda);
}
continue;
}
else
// Xi-steep up area
if(scan.steepUp(ixi)) {
// Update mib values with current mib and filter
updateFilterSDASet(mib, sdaset, ixi);
final SteepUpArea sua;
// Compute steep-up area
{
int startsteep = scan.index;
int endsteep = scan.index + 1;
mib = scan.ecurr.getReachability().doubleValue();
double esuccr = scan.esucc.getReachability().doubleValue();
// There is nothing higher than infinity
if(!Double.isInfinite(esuccr)) {
// find end of steep-up-area, eventually updating mib again
while(scan.hasNext()) {
scan.next();
// not going upward - stop here.
if(!scan.steepUp(1.0)) {
break;
}
// still steep - continue.
if(scan.steepUp(ixi)) {
endsteep = Math.min(scan.index + 1, clusterOrder.size() - 1);
mib = scan.ecurr.getReachability().doubleValue();
esuccr = scan.esucc.getReachability().doubleValue();
}
else {
// Stop looking after minpts non-up steps.
if(scan.index - endsteep > minpts) {
break;
}
}
}
}
sua = new SteepUpArea(startsteep, endsteep, esuccr);
if(logger.isDebuggingFinest()) {
logger.debugFinest("Xi " + sua.toString());
}
if(salist != null) {
salist.add(sua);
}
}
// Validate and computer clusters
// logger.debug("SDA size:"+sdaset.size()+" "+sdaset);
ListIterator<SteepDownArea> sdaiter = sdaset.listIterator(sdaset.size());
// Iterate backwards for correct hierarchy generation.
while(sdaiter.hasPrevious()) {
SteepDownArea sda = sdaiter.previous();
// logger.debug("Comparing: eU="+mib.doubleValue()+" SDA: "+sda.toString());
// Condition 3b: end-of-steep-up > maximum-in-between lower
if(mib * ixi < sda.getMib()) {
continue;
}
// By default, clusters cover both the steep up and steep down area
int cstart = sda.getStartIndex();
int cend = sua.getEndIndex();
// However, we sometimes have to adjust this (Condition 4):
{
// Case b)
if(sda.getMaximum() * ixi >= sua.getMaximum()) {
while(cstart < sda.getEndIndex()) {
if(clusterOrder.get(cstart + 1).getReachability().doubleValue() > sua.getMaximum()) {
cstart++;
}
else {
break;
}
}
}
// Case c)
else if(sua.getMaximum() * ixi >= sda.getMaximum()) {
while(cend > sua.getStartIndex()) {
if(clusterOrder.get(cend - 1).getReachability().doubleValue() > sda.getMaximum()) {
cend
}
else {
break;
}
}
}
// Case a) is the default
}
// Condition 3a: obey minpts
if(cend - cstart + 1 < minpts) {
continue;
}
// Build the cluster
ModifiableDBIDs dbids = DBIDUtil.newArray();
for(int idx = cstart; idx <= cend; idx++) {
final DBID dbid = clusterOrder.get(idx).getID();
// Collect only unclaimed IDs.
if(unclaimedids.remove(dbid)) {
dbids.add(dbid);
}
}
if(logger.isDebuggingFine()) {
logger.debugFine("Found cluster with " + dbids.size() + " new objects, length " + (cstart - cend + 1));
}
OPTICSModel model = new OPTICSModel(cstart, cend);
Cluster<OPTICSModel> cluster = new Cluster<OPTICSModel>("Cluster_" + cstart + "_" + cend, dbids, model, hier);
// Build the hierarchy
{
Iterator<Cluster<OPTICSModel>> iter = curclusters.iterator();
while(iter.hasNext()) {
Cluster<OPTICSModel> clus = iter.next();
OPTICSModel omodel = clus.getModel();
if(model.getStartIndex() <= omodel.getStartIndex() && omodel.getEndIndex() <= model.getEndIndex()) {
hier.add(cluster, clus);
iter.remove();
}
}
}
curclusters.add(cluster);
}
}
}
// Make sure to advance at least one step
if(curpos == scan.index) {
scan.next();
}
}
if(curclusters.size() > 0 || unclaimedids.size() > 0) {
final Clustering<OPTICSModel> clustering = new Clustering<OPTICSModel>("OPTICS Xi-Clusters", "optics");
if(unclaimedids.size() > 0) {
final Cluster<OPTICSModel> allcluster;
if(clusterOrder.get(clusterOrder.size() - 1).getReachability().isInfiniteDistance()) {
allcluster = new Cluster<OPTICSModel>("Noise", unclaimedids, true, new OPTICSModel(0, clusterOrder.size() - 1), hier);
}
else {
allcluster = new Cluster<OPTICSModel>("Cluster", unclaimedids, new OPTICSModel(0, clusterOrder.size() - 1), hier);
}
for(Cluster<OPTICSModel> cluster : curclusters) {
hier.add(allcluster, cluster);
}
clustering.addCluster(allcluster);
}
else {
for(Cluster<OPTICSModel> cluster : curclusters) {
clustering.addCluster(cluster);
}
}
clustering.addChildResult(clusterOrderResult);
if(salist != null) {
clusterOrderResult.addChildResult(new SteepAreaResult(salist));
}
return clustering;
}
return null;
}
/**
* Update the mib values of SteepDownAreas, and remove obsolete areas.
*
* @param mib Maximum in-between value
* @param sdaset Set of steep down areas.
*/
private static void updateFilterSDASet(double mib, List<SteepDownArea> sdaset, double ixi) {
Iterator<SteepDownArea> iter = sdaset.iterator();
while(iter.hasNext()) {
SteepDownArea sda = iter.next();
if(sda.getMaximum() * ixi <= mib) {
iter.remove();
}
else {
// Update
sda.setMib(Math.max(sda.getMib(), mib));
}
}
}
@Override
public TypeInformation[] getInputTypeRestriction() {
return optics.getInputTypeRestriction();
}
@Override
protected Logging getLogger() {
return logger;
}
/**
* Position when scanning for steep areas
*
* @author Erich Schubert
*
* @apiviz.exclude
*
* @param <N> Distance type
*/
private static class SteepScanPosition<N extends NumberDistance<N, ?>> {
/**
* Cluster order
*/
List<ClusterOrderEntry<N>> co;
/**
* Current position
*/
int index = 0;
/**
* Current entry
*/
ClusterOrderEntry<N> ecurr = null;
/**
* Next entry
*/
ClusterOrderEntry<N> esucc = null;
/**
* Constructor.
*
* @param co Cluster order
*/
public SteepScanPosition(List<ClusterOrderEntry<N>> co) {
super();
this.co = co;
this.ecurr = (co.size() >= 1) ? co.get(0) : null;
this.esucc = (co.size() >= 2) ? co.get(1) : null;
}
/**
* Advance to the next entry
*/
public void next() {
index++;
ecurr = esucc;
if(index + 1 < co.size()) {
esucc = co.get(index + 1);
}
}
/**
* Test whether there is a next value.
*
* @return end of cluster order
*/
public boolean hasNext() {
return index < co.size();
}
/**
* Test for a steep up point.
*
* @param ixi steepness factor (1-xi)
* @return truth value
*/
public boolean steepUp(double ixi) {
if(ecurr.getReachability().isInfiniteDistance()) {
return false;
}
if(esucc == null) {
return true;
}
return ecurr.getReachability().doubleValue() <= esucc.getReachability().doubleValue() * ixi;
}
/**
* Test for a steep down area.
*
* @param ixi Steepness factor (1-xi)
* @return truth value
*/
public boolean steepDown(double ixi) {
if(esucc == null) {
return false;
}
if(esucc.getReachability().isInfiniteDistance()) {
return false;
}
return ecurr.getReachability().doubleValue() * ixi >= esucc.getReachability().doubleValue();
}
}
/**
* Data structure to represent a steep-down-area for the xi method.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public abstract static class SteepArea {
/**
* Start index of down-area
*/
private int startindex;
/**
* End index of down-area
*/
private int endindex;
/**
* Maximum value
*/
private double maximum;
/**
* Constructor.
*
* @param startindex Start index
* @param endindex End index
* @param maximum Maximum value
*/
public SteepArea(int startindex, int endindex, double maximum) {
super();
this.startindex = startindex;
this.endindex = endindex;
this.maximum = maximum;
}
/**
* Start index
*
* @return the start index
*/
public int getStartIndex() {
return startindex;
}
/**
* End index
*
* @return the end index
*/
public int getEndIndex() {
return endindex;
}
/**
* Get the start value = maximum value
*
* @return the starting value
*/
public double getMaximum() {
return maximum;
}
}
/**
* Data structure to represent a steep-down-area for the xi method.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class SteepDownArea extends SteepArea {
/**
* Maximum in-between value
*/
private double mib;
/**
* Constructor
*
* @param startindex Start index
* @param endindex End index
* @param startDouble Start value (= maximum)
* @param mib Maximum inbetween value (for Xi extraction; modifiable)
*/
public SteepDownArea(int startindex, int endindex, double startDouble, double mib) {
super(startindex, endindex, startDouble);
this.mib = mib;
}
/**
* Get the maximum in-between value
*
* @return the mib value
*/
public double getMib() {
return mib;
}
/**
* Update the maximum in-between value
*
* @param mib the mib to set
*/
public void setMib(double mib) {
this.mib = mib;
}
@Override
public String toString() {
return "SteepDownArea(" + getStartIndex() + " - " + getEndIndex() + ", max=" + getMaximum() + ", mib=" + mib + ")";
}
}
/**
* Data structure to represent a steep-down-area for the xi method.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class SteepUpArea extends SteepArea {
/**
* Constructor
*
* @param startindex Starting index
* @param endindex End index
* @param endDouble End value (= maximum)
*/
public SteepUpArea(int startindex, int endindex, double endDouble) {
super(startindex, endindex, endDouble);
}
@Override
public String toString() {
return "SteepUpArea(" + getStartIndex() + " - " + getEndIndex() + ", max=" + getMaximum() + ")";
}
}
/**
* Result containing the chi-steep areas.
*
* @author Erich Schubert
*
* @apiviz.has SteepArea
*/
public static class SteepAreaResult implements IterableResult<SteepArea> {
/**
* Storage
*/
Collection<SteepArea> areas;
/**
* Constructor.
*
* @param areas Areas
*/
public SteepAreaResult(Collection<SteepArea> areas) {
super();
this.areas = areas;
}
@Override
public String getLongName() {
return "Xi-Steep areas";
}
@Override
public String getShortName() {
return "xi-steep-areas";
}
@Override
public Iterator<SteepArea> iterator() {
return areas.iterator();
}
}
/**
* Parameterization class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class Parameterizer<D extends NumberDistance<D, ?>> extends AbstractParameterizer {
protected OPTICSTypeAlgorithm<D> optics;
protected double xi = 0.0;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
DoubleParameter xiP = new DoubleParameter(XI_ID, true);
xiP.addConstraint(new IntervalConstraint(0.0, IntervalConstraint.IntervalBoundary.CLOSE, 1.0, IntervalConstraint.IntervalBoundary.OPEN));
if(config.grab(xiP)) {
xi = xiP.getValue();
}
ClassParameter<OPTICSTypeAlgorithm<D>> opticsP = new ClassParameter<OPTICSTypeAlgorithm<D>>(XIALG_ID, OPTICSTypeAlgorithm.class, OPTICS.class);
if(config.grab(opticsP)) {
optics = opticsP.instantiateClass(config);
}
}
@Override
protected OPTICSXi<D> makeInstance() {
return new OPTICSXi<D>(optics, xi);
}
}
}
|
package dev.kkorolyov.sqlob.connection;
import java.sql.*;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import dev.kkorolyov.sqlob.construct.Column;
import dev.kkorolyov.sqlob.construct.Results;
import dev.kkorolyov.sqlob.construct.RowEntry;
import dev.kkorolyov.sqlob.construct.statement.QueryStatement;
import dev.kkorolyov.sqlob.construct.statement.StatementFactory;
import dev.kkorolyov.sqlob.construct.statement.UpdateStatement;
import dev.kkorolyov.sqlob.logging.Logger;
import dev.kkorolyov.sqlob.logging.LoggerInterface;
/**
* A connection to a SQL database.
* Provides methods for SQL statement execution.
*/
public class DatabaseConnection implements AutoCloseable {
private static final LoggerInterface log = Logger.getLogger(DatabaseConnection.class.getName());
private final String database;
private final DatabaseType databaseType;
private Connection conn;
private Set<Statement> openStatements = new HashSet<>();
private StatementLog statementLog = new StatementLog();
private StatementFactory statementFactory = new StatementFactory(this);
/**
* Opens a new connection to the specified host and database residing on it.
* @param host IP or hostname of host to connect to
* @param database name of database to connect to
* @param databaseType type of database to connect to
* @param user user for database connection
* @param password password for database connection
* @throws SQLException if the URL specified is faulty or {@code null}
*/
public DatabaseConnection(String host, String database, DatabaseType databaseType, String user, String password) throws SQLException {
this.database = database;
this.databaseType = databaseType;
initDriver(databaseType);
String url = databaseType.getURL(host, database);
conn = DriverManager.getConnection(url, user, password);
log.debug("Successfully initialized " + databaseType + " " + getClass().getSimpleName() + ": " + hashCode() + " for database at: " + url);
}
private static void initDriver(DatabaseType type) {
try {
Class.forName(type.getDriverClassName());
} catch (ClassNotFoundException e) {
log.exception(e);
}
}
/**
* Connects to a table on this database, if it exists.
* @param table name of table to connect to
* @return connection to the table, if it exists, {@code null} if otherwise
* @throws ClosedException if called on a closed connection
*/
public TableConnection connect(String table) {
assertNotClosed();
return containsTable(table) ? new TableConnection(this, table) : null;
}
/**
* Closes this connection and releases all resources.
* Has no effect if called on a closed connection.
*/
public void close() {
if (isClosed()) // Already closed
return;
try {
conn.close(); // Release JDBC resources
} catch (SQLException e) {
log.exception(e); // Nothing to do for close() exception
}
conn = null;
log.debug("Closed " + databaseType + " " + getClass().getSimpleName() + ": " + hashCode());
}
/** @return {@code true} if this connection is closed */
public boolean isClosed() {
return (conn == null);
}
private void assertNotClosed() {
if (isClosed())
throw new ClosedException();
}
/**
* Executes and logs the specified statement.
* @param statement statement to execute
* @return results from statement execution, or {@code null} if the statement does not return results
* @throws UncheckedSQLException if the executed statement is invalid
* @throws ClosedException if called on a closed connection
*/
public Results execute(QueryStatement statement) {
assertNotClosed();
statementLog.add(statement);
return statement.execute();
}
/**
* Executes and logs the specified statement.
* @param statement statement to execute
* @return number of rows affected by statement execution
* @throws UncheckedSQLException if the executed statement is invalid
* @throws ClosedException if called on a closed connection
*/
public int execute(UpdateStatement statement) {
assertNotClosed();
statementLog.add(statement);
return statement.execute();
}
/**
* Executes a SQL statement with substituted parameters.
* @param baseStatement base SQL statement with '?' denoting an area for parameter substitution
* @param parameters parameters to substitute in order of declaration
* @return results of statement execution, or {@code null} if statement does not return results
*/
public Results execute(String baseStatement, RowEntry... parameters) {
assertNotClosed();
Results results = null;
try {
PreparedStatement s = buildStatement(baseStatement, parameters); // Remains open to not close results
openStatements.add(s);
if (s.execute())
results = new Results(s.getResultSet());
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
return results;
}
/**
* Executes a SQL statement with substituted parameters.
* @param baseStatement base SQL statement with '?' denoting an area for parameter substitution
* @param parameters parameters to substitute in order of declaration
* @return number of rows affected by statement execution
*/
public int update(String baseStatement, RowEntry... parameters) {
assertNotClosed();
closeAllStatements(); // Close open resources before modifying
int updated = 0;
try (PreparedStatement s = buildStatement(baseStatement, parameters)) {
if (!s.execute())
updated = s.getUpdateCount();
} catch(SQLException e) {
throw new UncheckedSQLException(e);
}
return updated;
}
private PreparedStatement buildStatement(String baseStatement, RowEntry[] parameters) throws SQLException { // Inserts appropriate type into statement
PreparedStatement statement = conn.prepareStatement(baseStatement);
if (parameters != null && parameters.length > 0) {
for (int i = 0; i < parameters.length; i++) { // Prepare with appropriate types
Object currentParameter = parameters[i].getValue();
if (currentParameter instanceof Boolean) // TODO Use something other than switching tree
statement.setBoolean(i + 1, (boolean) currentParameter);
else if (currentParameter instanceof Short)
statement.setShort(i + 1, (short) currentParameter);
else if (currentParameter instanceof Integer)
statement.setInt(i + 1, (int) currentParameter);
else if (currentParameter instanceof Long)
statement.setLong(i + 1, (long) currentParameter);
else if (currentParameter instanceof Float)
statement.setFloat(i + 1, (float) currentParameter);
else if (currentParameter instanceof Double)
statement.setDouble(i + 1, (double) currentParameter);
else if (currentParameter instanceof Character)
statement.setString(i + 1, String.valueOf((char) currentParameter));
else if (currentParameter instanceof String)
statement.setString(i + 1, (String) currentParameter);
log.debug("Adding parameter " + i + ": " + currentParameter.toString());
}
}
return statement;
}
/**
* Creates a table with the specifed name and columns.
* @param name new table name
* @param columns new table columns in the order they should appear
* @return connection to the created table
* @throws DuplicateTableException if a table of the specified name already exists
* @throws ClosedException if called on a closed connection
*/
public TableConnection createTable(String name, Column[] columns) throws DuplicateTableException {
assertNotClosed();
if (containsTable(name)) // Can't add a table of the same name
throw new DuplicateTableException(database, name);
execute(statementFactory.getCreateTable(name, columns));
return new TableConnection(this, name);
}
/**
* Drops a table of the specified name from the database.
* @param table name of table to drop
* @return {@code true} if table dropped successfully, {@code false} if drop failed or no such table
* @throws ClosedException if called on a closed connection
*/
public boolean dropTable(String table) {
assertNotClosed();
closeAllStatements();
boolean success = false;
if (containsTable(table)) {
execute(statementFactory.getDropTable(table));
success = true;
}
return success;
}
/**
* @param table name of table to search for
* @return {@code true} if the database contains a table of the specified name (ignoring case)
* @throws ClosedException if called on a closed connection
*/
public boolean containsTable(String table) {
assertNotClosed();
boolean contains = false;
for (String dbTable : getTables()) {
if (dbTable.equalsIgnoreCase(table)) {
contains = true;
break;
}
}
return contains;
}
/**
* @return names of all tables in the database.
* @throws ClosedException if called on a closed connection
*/
public String[] getTables() {
assertNotClosed();
List<String> tables = new LinkedList<>();
try (ResultSet tableSet = conn.getMetaData().getTables(null, null, "%", new String[]{"TABLE"})) {
while (tableSet.next()) {
tables.add(tableSet.getString(3));
}
tableSet.close();
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
return tables.toArray(new String[tables.size()]);
}
/**
* Returns the name of the database.
* May be called on a closed connection.
* @return name of database
*/
public String getDatabaseName() {
return database;
}
/**
* Returns the type of the database.
* May be called on a closed connection.
* @return type of database
*/
public DatabaseType getDatabaseType() {
return databaseType;
}
/**
* Returns the statement log associated with this connection.
* May be called on a closed connection.
* @return associated statement log
*/
public StatementLog getStatementLog() {
return statementLog;
}
/**
* @return a {@code StatementFactory} used to produce statements for execution by this connection
* @throws ClosedException if called on a closed connection
*/
public StatementFactory getStatementFactory() {
return statementFactory;
}
private void closeAllStatements() {
for (@SuppressWarnings("resource") Statement statement : openStatements) {
try {
statement.close();
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
openStatements.clear();
}
/**
* Represents a specific database type.
*/
public static enum DatabaseType {
/** The {@code PostgreSQL} database */
POSTGRESQL("org.postgresql.Driver", "jdbc:postgresql://" + Marker.HOST + "/" + Marker.DATABASE),
/** The {@code SQLite} database */
SQLITE("org.sqlite.JDBC", "jdbc:sqlite:" + Marker.DATABASE);
private String driverClassName,
baseURL;
private DatabaseType(String driverClassName, String header) {
this.driverClassName = driverClassName;
this.baseURL = header;
}
/**
* Returns a type-specific URL to a database.
* @param host hostname or address of database host, may be empty
* @param database database name
* @return appropriate URL
*/
public String getURL(String host, String database) {
return baseURL.replaceFirst(Marker.HOST, host).replaceFirst(Marker.DATABASE, database);
}
/** @return name of the JDBC driver class for this database type */
public String getDriverClassName() {
return driverClassName;
}
private static class Marker {
private static final String HOST = "<HOST>",
DATABASE = "<DATABASE>";
}
}
}
|
package com.tngtech.archunit.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.tngtech.archunit.core.BuilderWithBuildParameter.BuildFinisher.build;
import static com.tngtech.archunit.core.Guava.toGuava;
import static com.tngtech.archunit.core.JavaAnnotation.GET_TYPE_NAME;
import static com.tngtech.archunit.core.JavaClass.TypeAnalysisListener.NO_OP;
import static com.tngtech.archunit.core.ReflectionUtils.classForName;
public class JavaClass implements HasName {
private final TypeDetails typeDetails;
private final Set<JavaField> fields;
private final Set<JavaCodeUnit<?, ?>> codeUnits;
private final Set<JavaMethod> methods;
private final Set<JavaConstructor> constructors;
private final JavaStaticInitializer staticInitializer;
private Optional<JavaClass> superClass = Optional.absent();
private final Set<JavaClass> interfaces = new HashSet<>();
private final Set<JavaClass> subClasses = new HashSet<>();
private Optional<JavaClass> enclosingClass = Optional.absent();
private final Map<String, JavaAnnotation> annotations;
private JavaClass(Builder builder) {
typeDetails = checkNotNull(builder.typeDetails);
fields = build(builder.fieldBuilders, this);
methods = build(builder.methodBuilders, this);
constructors = build(builder.constructorBuilders, this);
staticInitializer = new JavaStaticInitializer.Builder().build(this);
codeUnits = ImmutableSet.<JavaCodeUnit<?, ?>>builder()
.addAll(methods).addAll(constructors).add(staticInitializer)
.build();
annotations = builder.annotations.build();
}
@Override
public String getName() {
return typeDetails.getName();
}
public String getSimpleName() {
return typeDetails.getSimpleName();
}
public String getPackage() {
return typeDetails.getPackage();
}
public boolean isInterface() {
return typeDetails.isInterface();
}
public boolean isAnnotatedWith(Class<? extends Annotation> annotation) {
return reflect().isAnnotationPresent(annotation);
}
public <A extends Annotation> A getReflectionAnnotation(Class<A> type) {
return getAnnotation(type).as(type);
}
public JavaAnnotation getAnnotation(Class<? extends Annotation> type) {
return tryGetAnnotation(type).getOrThrow(new IllegalArgumentException(
String.format("Type %s is not annotated with @%s", getSimpleName(), type.getSimpleName())));
}
/**
* @param type A given annotation type to match {@link JavaAnnotation JavaAnnotations} against
* @return An {@link Optional} containing a {@link JavaAnnotation} representing the given annotation type,
* if this class is annotated with the given type, otherwise Optional.absent()
* @see #isAnnotatedWith(Class)
* @see #getAnnotation(Class)
*/
public Optional<JavaAnnotation> tryGetAnnotation(Class<? extends Annotation> type) {
return Optional.fromNullable(annotations.get(type.getName()));
}
public Optional<JavaClass> getSuperClass() {
return superClass;
}
/**
* @return The complete class hierarchy, i.e. the class itself and the result of {@link #getAllSuperClasses()}
*/
public List<JavaClass> getClassHierarchy() {
ImmutableList.Builder<JavaClass> result = ImmutableList.builder();
result.add(this);
result.addAll(getAllSuperClasses());
return result.build();
}
/**
* @return All super classes sorted ascending by distance in the class hierarchy, i.e. first the direct super class,
* then the super class of the super class and so on. Includes Object.class in the result.
*/
public List<JavaClass> getAllSuperClasses() {
ImmutableList.Builder<JavaClass> result = ImmutableList.builder();
JavaClass current = this;
while (current.getSuperClass().isPresent()) {
current = current.getSuperClass().get();
result.add(current);
}
return result.build();
}
public Set<JavaClass> getSubClasses() {
return subClasses;
}
public Set<JavaClass> getInterfaces() {
return interfaces;
}
public Set<JavaClass> getAllInterfaces() {
ImmutableSet.Builder<JavaClass> result = ImmutableSet.builder();
for (JavaClass i : interfaces) {
result.add(i);
result.addAll(i.getAllInterfaces());
}
if (superClass.isPresent()) {
result.addAll(superClass.get().getAllInterfaces());
}
return result.build();
}
public Optional<JavaClass> getEnclosingClass() {
return enclosingClass;
}
public Set<JavaClass> getAllSubClasses() {
Set<JavaClass> result = new HashSet<>();
for (JavaClass subClass : subClasses) {
result.add(subClass);
result.addAll(subClass.getAllSubClasses());
}
return result;
}
public Set<JavaField> getFields() {
return fields;
}
public Set<JavaField> getAllFields() {
ImmutableSet.Builder<JavaField> result = ImmutableSet.builder();
for (JavaClass javaClass : getClassHierarchy()) {
result.addAll(javaClass.getFields());
}
return result.build();
}
public JavaField getField(String name) {
return tryGetField(name).getOrThrow(new IllegalArgumentException("No field with name '" + name + " in class " + getName()));
}
public Optional<JavaField> tryGetField(String name) {
for (JavaField field : fields) {
if (name.equals(field.getName())) {
return Optional.of(field);
}
}
return Optional.absent();
}
public Set<JavaCodeUnit<?, ?>> getCodeUnits() {
return codeUnits;
}
/**
* @param name The name of the code unit, can be a method name, but also
* {@link JavaConstructor#CONSTRUCTOR_NAME CONSTRUCTOR_NAME}
* or {@link JavaStaticInitializer#STATIC_INITIALIZER_NAME STATIC_INITIALIZER_NAME}
* @param parameters The parameter signature of the method
* @return A code unit (method, constructor or static initializer) with the given signature
*/
public JavaCodeUnit<?, ?> getCodeUnit(String name, TypeDetails... parameters) {
return getCodeUnit(name, ImmutableList.copyOf(parameters));
}
public JavaCodeUnit<?, ?> getCodeUnit(String name, List<TypeDetails> parameters) {
return findMatchingCodeUnit(codeUnits, name, parameters);
}
private <T extends JavaCodeUnit<?, ?>> T findMatchingCodeUnit(Set<T> codeUnits, String name, List<TypeDetails> parameters) {
return tryFindMatchingCodeUnit(codeUnits, name, parameters).getOrThrow(new IllegalArgumentException("No code unit with name '" + name + "' and parameters " + parameters +
" in codeUnits " + codeUnits + " of class " + getName()));
}
private <T extends JavaCodeUnit<?, ?>> Optional<T> tryFindMatchingCodeUnit(Set<T> codeUnits, String name, List<TypeDetails> parameters) {
for (T codeUnit : codeUnits) {
if (name.equals(codeUnit.getName()) && parameters.equals(codeUnit.getParameters())) {
return Optional.of(codeUnit);
}
}
return Optional.absent();
}
public JavaMethod getMethod(String name, Class<?>... parameters) {
return findMatchingCodeUnit(methods, name, TypeDetails.allOf(parameters));
}
public Set<JavaMethod> getMethods() {
return methods;
}
public Set<JavaMethod> getAllMethods() {
ImmutableSet.Builder<JavaMethod> result = ImmutableSet.builder();
for (JavaClass javaClass : getClassHierarchy()) {
result.addAll(javaClass.getMethods());
}
return result.build();
}
public JavaConstructor getConstructor(Class<?>... parameters) {
return findMatchingCodeUnit(constructors, JavaConstructor.CONSTRUCTOR_NAME, TypeDetails.allOf(parameters));
}
public Set<JavaConstructor> getConstructors() {
return constructors;
}
public Set<JavaConstructor> getAllConstructors() {
ImmutableSet.Builder<JavaConstructor> result = ImmutableSet.builder();
for (JavaClass javaClass : getClassHierarchy()) {
result.addAll(javaClass.getConstructors());
}
return result.build();
}
public JavaStaticInitializer getStaticInitializer() {
return staticInitializer;
}
public Set<JavaAccess<?>> getAccessesFromSelf() {
return Sets.union(getFieldAccessesFromSelf(), getCallsFromSelf());
}
/**
* @return Set of all {@link JavaAccess} in the class hierarchy, as opposed to the accesses this class directly performs.
*/
public Set<JavaAccess<?>> getAllAccessesFromSelf() {
ImmutableSet.Builder<JavaAccess<?>> result = ImmutableSet.builder();
for (JavaClass clazz : getClassHierarchy()) {
result.addAll(clazz.getAccessesFromSelf());
}
return result.build();
}
public Set<JavaFieldAccess> getFieldAccessesFromSelf() {
ImmutableSet.Builder<JavaFieldAccess> result = ImmutableSet.builder();
for (JavaCodeUnit<?, ?> codeUnit : codeUnits) {
result.addAll(codeUnit.getFieldAccesses());
}
return result.build();
}
/**
* Returns all calls of this class to methods or constructors.
*
* @see #getMethodCallsFromSelf()
* @see #getConstructorCallsFromSelf()
*/
public Set<JavaCall<?>> getCallsFromSelf() {
return Sets.union(getMethodCallsFromSelf(), getConstructorCallsFromSelf());
}
public Set<JavaMethodCall> getMethodCallsFromSelf() {
ImmutableSet.Builder<JavaMethodCall> result = ImmutableSet.builder();
for (JavaCodeUnit<?, ?> codeUnit : codeUnits) {
result.addAll(codeUnit.getMethodCallsFromSelf());
}
return result.build();
}
public Set<JavaConstructorCall> getConstructorCallsFromSelf() {
ImmutableSet.Builder<JavaConstructorCall> result = ImmutableSet.builder();
for (JavaCodeUnit<?, ?> codeUnit : codeUnits) {
result.addAll(codeUnit.getConstructorCallsFromSelf());
}
return result.build();
}
public Set<Dependency> getDirectDependencies() {
Set<Dependency> result = new HashSet<>();
for (JavaAccess<?> access : filterTargetNotSelf(getFieldAccessesFromSelf())) {
result.add(Dependency.from(access));
}
for (JavaAccess<?> call : filterTargetNotSelf(getCallsFromSelf())) {
result.add(Dependency.from(call));
}
return result;
}
private Set<JavaAccess<?>> filterTargetNotSelf(Set<? extends JavaAccess<?>> accesses) {
Set<JavaAccess<?>> result = new HashSet<>();
for (JavaAccess<?> access : accesses) {
if (!access.getTarget().getOwner().equals(this)) {
result.add(access);
}
}
return result;
}
public Set<JavaMethodCall> getMethodCallsToSelf() {
ImmutableSet.Builder<JavaMethodCall> result = ImmutableSet.builder();
for (JavaMethod method : methods) {
result.addAll(method.getCallsOfSelf());
}
return result.build();
}
public Set<JavaConstructorCall> getConstructorCallsToSelf() {
ImmutableSet.Builder<JavaConstructorCall> result = ImmutableSet.builder();
for (JavaConstructor constructor : constructors) {
result.addAll(constructor.getCallsOfSelf());
}
return result.build();
}
public Set<JavaAccess<?>> getAccessesToSelf() {
return ImmutableSet.<JavaAccess<?>>builder()
.addAll(getFieldAccessesToSelf())
.addAll(getMethodCallsToSelf())
.addAll(getConstructorCallsToSelf())
.build();
}
public Class<?> reflect() {
return classForName(getName());
}
void completeClassHierarchyFrom(ImportContext context) {
completeSuperClassFrom(context);
completeInterfacesFrom(context);
}
private void completeSuperClassFrom(ImportContext context) {
superClass = findClass(typeDetails.getSuperclass(), context);
if (superClass.isPresent()) {
superClass.get().subClasses.add(this);
}
}
private void completeInterfacesFrom(ImportContext context) {
for (TypeDetails i : typeDetails.getInterfaces()) {
interfaces.addAll(findClass(i, context).asSet());
}
for (JavaClass i : interfaces) {
i.subClasses.add(this);
}
}
private static Optional<JavaClass> findClass(TypeDetails type, ImportContext context) {
return context.tryGetJavaClassWithType(type.getName());
}
private static Optional<JavaClass> findClass(Optional<TypeDetails> type, ImportContext context) {
return type.isPresent() ? findClass(type.get(), context) : Optional.<JavaClass>absent();
}
CompletionProcess completeFrom(ImportContext context) {
enclosingClass = findClass(typeDetails.getEnclosingClass(), context);
return new CompletionProcess();
}
@Override
public String toString() {
return "JavaClass{name='" + typeDetails.getName() + "\'}";
}
public Set<JavaFieldAccess> getFieldAccessesToSelf() {
ImmutableSet.Builder<JavaFieldAccess> result = ImmutableSet.builder();
for (JavaField field : fields) {
result.addAll(field.getAccessesToSelf());
}
return result.build();
}
public static DescribedPredicate<JavaClass> withType(final Class<?> type) {
return DescribedPredicate.<Class<?>>equalTo(type).onResultOf(REFLECT).as("with type " + type.getName());
}
public static DescribedPredicate<Class<?>> reflectionAssignableTo(final Class<?> type) {
checkNotNull(type);
return new DescribedPredicate<Class<?>>("assignable to " + type.getName()) {
@Override
public boolean apply(Class<?> input) {
return type.isAssignableFrom(input);
}
};
}
public static DescribedPredicate<Class<?>> reflectionAssignableFrom(final Class<?> type) {
checkNotNull(type);
return new DescribedPredicate<Class<?>>("assignable from " + type.getName()) {
@Override
public boolean apply(Class<?> input) {
return input.isAssignableFrom(type);
}
};
}
public static DescribedPredicate<JavaClass> assignableTo(final Class<?> type) {
return reflectionAssignableTo(type).onResultOf(REFLECT);
}
public static DescribedPredicate<JavaClass> assignableFrom(final Class<?> type) {
return reflectionAssignableFrom(type).onResultOf(REFLECT);
}
public static final DescribedPredicate<JavaClass> INTERFACES = new DescribedPredicate<JavaClass>("interfaces") {
@Override
public boolean apply(JavaClass input) {
return input.isInterface();
}
};
public static final Function<JavaClass, Class<?>> REFLECT = new Function<JavaClass, Class<?>>() {
@Override
public Class<?> apply(JavaClass input) {
return input.reflect();
}
};
class CompletionProcess {
AccessCompletion.SubProcess completeCodeUnitsFrom(ImportContext context) {
AccessCompletion.SubProcess accessCompletionProcess = new AccessCompletion.SubProcess();
for (JavaCodeUnit<?, ?> codeUnit : codeUnits) {
accessCompletionProcess.mergeWith(codeUnit.completeFrom(context));
}
return accessCompletionProcess;
}
}
static final class Builder {
private TypeDetails typeDetails;
private final Set<BuilderWithBuildParameter<JavaClass, JavaField>> fieldBuilders = new HashSet<>();
private final Set<BuilderWithBuildParameter<JavaClass, JavaMethod>> methodBuilders = new HashSet<>();
private final Set<BuilderWithBuildParameter<JavaClass, JavaConstructor>> constructorBuilders = new HashSet<>();
private final ImmutableMap.Builder<String, JavaAnnotation> annotations = ImmutableMap.builder();
private final TypeAnalysisListener analysisListener;
Builder() {
this(NO_OP);
}
Builder(TypeAnalysisListener analysisListener) {
this.analysisListener = analysisListener;
}
@SuppressWarnings("unchecked")
Builder withType(TypeDetails typeDetails) {
this.typeDetails = typeDetails;
for (Field field : typeDetails.getDeclaredFields()) {
addField(new JavaField.Builder().withField(field));
}
for (Method method : typeDetails.getDeclaredMethods()) {
analysisListener.onMethodFound(method);
addMethod(new JavaMethod.Builder().withMethod(method));
}
for (Constructor<?> constructor : typeDetails.getDeclaredConstructors()) {
analysisListener.onConstructorFound(constructor);
addConstructor(new JavaConstructor.Builder().withConstructor(constructor));
}
annotations.putAll(FluentIterable.from(typeDetails.getAnnotations())
.uniqueIndex(toGuava(GET_TYPE_NAME)));
return this;
}
Builder addField(BuilderWithBuildParameter<JavaClass, JavaField> fieldBuilder) {
fieldBuilders.add(fieldBuilder);
return this;
}
Builder addMethod(BuilderWithBuildParameter<JavaClass, JavaMethod> methodBuilder) {
methodBuilders.add(methodBuilder);
return this;
}
Builder addConstructor(BuilderWithBuildParameter<JavaClass, JavaConstructor> constructorBuilder) {
constructorBuilders.add(constructorBuilder);
return this;
}
public JavaClass build() {
return new JavaClass(this);
}
}
interface TypeAnalysisListener {
void onMethodFound(Method method);
void onConstructorFound(Constructor<?> constructor);
TypeAnalysisListener NO_OP = new TypeAnalysisListener() {
@Override
public void onMethodFound(Method method) {
}
@Override
public void onConstructorFound(Constructor<?> constructor) {
}
};
}
}
|
package org.antlr.symtab;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
public class Utils {
/** Return first ancestor node up the chain towards the root that has ruleName.
* Search includes the current node.
*/
public static ParserRuleContext getAncestor(Parser parser, ParserRuleContext ctx, String ruleName) {
int ruleIndex = parser.getRuleIndex(ruleName);
return getAncestor(ctx, ruleIndex);
}
/** Return first ancestor node up the chain towards the root that has the rule index.
* Search includes the current node.
*/
public static ParserRuleContext getAncestor(ParserRuleContext t, int ruleIndex) {
while ( t!=null ) {
if ( t.getRuleIndex() == ruleIndex ) {
return t;
}
t = t.getParent();
}
return null;
}
/** Return first ancestor node up the chain towards the root that is clazz.
* Search includes the current node.
*/
public static ParserRuleContext getFirstAncestorOfType(ParserRuleContext t, Class<?> clazz) {
while ( t!=null ) {
if ( t.getClass()==clazz ) {
return t;
}
t = t.getParent();
}
return null;
}
public static Field[] getAllFields(Class<?> clazz) {
List<Field> fields = new ArrayList<>();
while ( clazz!=null && clazz != Object.class ) {
for (Field f : clazz.getDeclaredFields()) {
fields.add(f);
}
clazz = clazz.getSuperclass();
}
return fields.toArray(new Field[fields.size()]);
}
public static Field[] getAllAnnotatedFields(Class<?> clazz) {
List<Field> fields = new ArrayList<>();
while ( clazz!=null && clazz != Object.class ) {
for (Field f : clazz.getDeclaredFields()) {
if ( f.getAnnotations().length>0 ) {
fields.add(f);
}
}
clazz = clazz.getSuperclass();
}
return fields.toArray(new Field[fields.size()]);
}
public static void getAllNestedScopes(Scope scope, List<Scope> scopes) {
scopes.addAll(scope.getNestedScopes());
for (Scope s : scope.getNestedScopes()) {
getAllNestedScopes(s, scopes);
}
}
/** Return a string of scope names with the "stack" growing to the left
* E.g., myblock:mymethod:myclass.
* String includes arg scope in string.
*/
public static String toScopeStackString(Scope scope, String separator) {
List<Scope> scopes = scope.getEnclosingPathToRoot();
return joinScopeNames(scopes, separator);
}
/** Return a string of scope names with the "stack" growing to the right.
* E.g., myclass:mymethod:myblock.
* String includes arg scope in string.
*/
public static String toQualifierString(Scope scope, String separator) {
List<Scope> scopes = scope.getEnclosingPathToRoot();
Collections.reverse(scopes);
return joinScopeNames(scopes, separator);
}
public static String toString(Scope s, int level) {
StringBuilder buf = new StringBuilder();
buf.append(tab(level));
buf.append(s.getName());
buf.append("\n");
level++;
for (Symbol sym : s.getSymbols()) {
if ( !(sym instanceof Scope) ) {
buf.append(tab(level));
buf.append(sym);
buf.append("\n");
}
}
for (Scope nested : s.getNestedScopes()) {
buf.append(toString(nested, level));
}
return buf.toString();
}
public static String toString(Scope s) {
return toString(s, 0);
}
// Generic filtering, mapping, joining that should be in the standard library but aren't
public static <T> List<T> filter(List<T> data, Predicate<T> pred) {
List<T> output = new ArrayList<>();
for (T x : data) {
if ( pred.test(x) ) {
output.add(x);
}
}
return output;
}
public static <T> Set<T> filter(Collection<T> data, Predicate<T> pred) {
Set<T> output = new HashSet<>();
for (T x : data) {
if ( pred.test(x) ) {
output.add(x);
}
}
return output;
}
public static <T,R> List<R> map(Collection<T> data, Function<T,R> getter) {
List<R> output = new ArrayList<>();
for (T x : data) {
output.add(getter.apply(x));
}
return output;
}
public static <T,R> List<R> map(T[] data, Function<T,R> getter) {
List<R> output = new ArrayList<>();
for (T x : data) {
output.add(getter.apply(x));
}
return output;
}
public static <T> String join(Collection<T> data, String separator) {
return join(data.iterator(), separator, "", "");
}
public static <T> String join(Collection<T> data, String separator, String left, String right) {
return join(data.iterator(), separator, left, right);
}
public static <T> String join(Iterator<T> iter, String separator, String left, String right) {
StringBuilder buf = new StringBuilder();
while(iter.hasNext()) {
buf.append(iter.next());
if(iter.hasNext()) {
buf.append(separator);
}
}
return left+buf.toString()+right;
}
public static <T> String join(T[] array, String separator) {
StringBuilder builder = new StringBuilder();
for(int i = 0; i < array.length; ++i) {
builder.append(array[i]);
if(i < array.length - 1) {
builder.append(separator);
}
}
return builder.toString();
}
public static String tab(int n) {
StringBuilder buf = new StringBuilder();
for (int i=1; i<=n; i++) buf.append(" ");
return buf.toString();
}
public static String joinScopeNames(List<Scope> scopes, String separator) {
if ( scopes==null || scopes.size()==0 ) {
return "";
}
StringBuilder buf = new StringBuilder();
buf.append(scopes.get(0).getName());
for (int i = 1; i<scopes.size(); i++) {
Scope s = scopes.get(i);
buf.append(separator);
buf.append(s.getName());
}
return buf.toString();
}
}
|
package org.cryptonit;
import javacard.framework.APDU;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.Util;
public class IOBuffer {
private FileIndex index = null;
private byte [] buffer = null;
private short [] shorts = null;
final private byte SIZE = 0x0;
final private byte PATH = 0x1;
final private byte OFFSET = 0x2;
private boolean [] bools = null;
final private byte isLOADED = 0x0;
final private byte isFILE = 0x1;
public IOBuffer(FileIndex index) {
this.index = index;
this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT);
}
public void sendBuffer(byte[] buf, short length, APDU apdu) {
short le = apdu.setOutgoing(), r = 0;
if(le == 0) {
le = (short) (APDU.getOutBlockSize() - 2);
}
if(le > length) {
le = length;
}
if(le < length) {
r = (short) (length - le);
if(r > (short) this.buffer.length) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
this.bools[isLOADED] = true;
this.bools[isFILE] = false;
this.shorts[SIZE] = r;
}
apdu.setOutgoingLength(le);
apdu.sendBytesLong(buf, (short) 0, le);
if(r > 0) {
if (r >= (short) (APDU.getOutBlockSize() - 2)) {
r = 0;
}
Util.arrayCopy(buf, le, this.buffer, (short) 0, r);
}
}
}
|
package org.cryptonit;
import javacard.framework.APDU;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.Util;
/**
* @author Mathias Brossard
*/
public class IOBuffer {
private FileIndex index = null;
private byte[] buffer = null;
private short[] shorts = null;
final private byte SIZE = 0x0;
final private byte PATH = 0x1;
final private byte OFFSET = 0x2;
private boolean[] bools = null;
final private byte isLOADED = 0x0;
final private byte isFILE = 0x1;
public void clear() {
this.bools[isLOADED] = false;
}
public boolean isLoaded() {
return this.bools[isLOADED];
}
public IOBuffer(FileIndex index) {
this.index = index;
this.bools = JCSystem.makeTransientBooleanArray((short) 2,
JCSystem.CLEAR_ON_DESELECT);
this.buffer = JCSystem.makeTransientByteArray((short) 256,
JCSystem.CLEAR_ON_DESELECT);
this.shorts = JCSystem.makeTransientShortArray((short) 3,
JCSystem.CLEAR_ON_DESELECT);
}
public void sendBuffer(byte[] buf, short length, APDU apdu) {
short le = apdu.setOutgoing(), r = 0;
if (le == 0) {
le = (short) (APDU.getOutBlockSize() - 2);
}
if (le > length) {
le = length;
}
if (le < length) {
r = (short) (length - le);
if (r > (short) this.buffer.length) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
this.bools[isLOADED] = true;
this.bools[isFILE] = false;
this.shorts[SIZE] = r;
}
apdu.setOutgoingLength(le);
apdu.sendBytesLong(buf, (short) 0, le);
if (r > 0) {
if (r >= (short) (APDU.getOutBlockSize() - 2)) {
r = 0;
}
Util.arrayCopy(buf, le, this.buffer, (short) 0, r);
ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 | r));
} else {
clear();
}
}
public void sendFile(short id, APDU apdu, short offset) {
byte[] d = index.entries[id].content;
if (d == null) {
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
short le = apdu.setOutgoing(), r = 0;
if (le == 0) {
le = (short) (APDU.getOutBlockSize() - 2);
}
if ((short) (le + offset) > (short) d.length) {
le = (short) (d.length - offset);
}
if ((short) (le + offset) < (short) d.length) {
r = (short) (d.length - (le + offset));
this.bools[isLOADED] = true;
this.bools[isFILE] = true;
this.shorts[OFFSET] = (short) (le + offset);
this.shorts[PATH] = id;
}
apdu.setOutgoingLength(le);
apdu.sendBytesLong(d, offset, le);
if (r > 0) {
if (r >= (short) (APDU.getOutBlockSize() - 2)) {
r = 0;
}
ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 | r));
} else {
clear();
}
}
public void getResponse(APDU apdu) {
if (!this.bools[isLOADED]) {
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
if (this.bools[isFILE]) {
sendFile(this.shorts[PATH], apdu, this.shorts[OFFSET]);
} else {
sendBuffer(this.buffer, this.shorts[SIZE], apdu);
}
}
public void receiveBuffer(byte[] buf, short offset, short length) {
if (this.bools[isLOADED]) {
if (this.bools[isFILE]) {
ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
}
if ((short) (this.shorts[SIZE] + length) > this.buffer.length) {
ISOException.throwIt(ISO7816.SW_FILE_FULL);
}
Util.arrayCopy(buf, offset, this.buffer, this.shorts[SIZE], length);
this.shorts[SIZE] += length;
} else {
Util.arrayCopy(buf, offset, this.buffer, (short) 0, length);
this.shorts[SIZE] = length;
this.bools[isLOADED] = true;
this.bools[isFILE] = false;
}
}
public byte[] retrieveBuffer(byte[] buf, short offset, short length) {
if (!this.bools[isLOADED] || this.bools[isFILE]) {
ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
}
short l = (short) (this.shorts[SIZE] + length);
byte[] r = new byte[l];
Util.arrayCopy(this.buffer, (short) 0, r, (short) 0, this.shorts[SIZE]);
Util.arrayCopy(buf, offset, r, this.shorts[SIZE], length);
this.bools[isLOADED] = false;
return r;
}
public void createFile(short id, short length) {
}
public void receiveFile(byte[] buf, short offset, short length) {
}
}
|
package org.nutz.mvc;
import java.io.IOException;
import java.util.regex.Pattern;
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;
import org.nutz.lang.Strings;
import org.nutz.mvc.config.FilterNutConfig;
/**
* JSP/Serlvet
*
* @author zozoh(zozohtnt@gmail.com)
* @author juqkai(juqkai@gmail.com)
* @author wendal(wendal1985@gmail.com)
*/
public class NutFilter implements Filter {
private ActionHandler handler;
private static final String IGNORE = "^.+\\.(jsp|png|gif|jpg|js|css|jspx|jpeg|swf)$";
private Pattern ignorePtn;
private boolean skipMode;
public void init(FilterConfig conf) throws ServletException {
FilterNutConfig config = new FilterNutConfig(conf);
// Message Nutz.Mvc
// @see Issue 301
String skipMode = Strings.sNull(conf.getInitParameter("skip-mode"), "false").toLowerCase();
if (!"true".equals(skipMode)) {
handler = new ActionHandler(config);
String regx = Strings.sNull(config.getInitParameter("ignore"), IGNORE);
if (!"null".equalsIgnoreCase(regx)) {
ignorePtn = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);
}
} else
this.skipMode = true;
}
public void destroy() {
handler.depose();
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
if (!skipMode) {
RequestPath path = Mvcs.getRequestPathObject((HttpServletRequest) req);
if (null == ignorePtn || !ignorePtn.matcher(path.getUrl()).find()) {}
if (handler.handle((HttpServletRequest) req, (HttpServletResponse) resp))
return;
}
// Request
else {
Mvcs.updateRequestAttributes((HttpServletRequest) req);
}
chain.doFilter(req, resp);
}
}
|
package org.objectweb.asm;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* A Java type. This class can be used to make it easier to manipulate type and
* method descriptors.
*
* @author Eric Bruneton
* @author Chris Nokleberg
*/
public class Type {
/**
* The sort of the <tt>void</tt> type. See {@link #getSort getSort}.
*/
public final static int VOID = 0;
/**
* The sort of the <tt>boolean</tt> type. See {@link #getSort getSort}.
*/
public final static int BOOLEAN = 1;
/**
* The sort of the <tt>char</tt> type. See {@link #getSort getSort}.
*/
public final static int CHAR = 2;
/**
* The sort of the <tt>byte</tt> type. See {@link #getSort getSort}.
*/
public final static int BYTE = 3;
/**
* The sort of the <tt>short</tt> type. See {@link #getSort getSort}.
*/
public final static int SHORT = 4;
/**
* The sort of the <tt>int</tt> type. See {@link #getSort getSort}.
*/
public final static int INT = 5;
/**
* The sort of the <tt>float</tt> type. See {@link #getSort getSort}.
*/
public final static int FLOAT = 6;
/**
* The sort of the <tt>long</tt> type. See {@link #getSort getSort}.
*/
public final static int LONG = 7;
/**
* The sort of the <tt>double</tt> type. See {@link #getSort getSort}.
*/
public final static int DOUBLE = 8;
/**
* The sort of array reference types. See {@link #getSort getSort}.
*/
public final static int ARRAY = 9;
/**
* The sort of object reference type. See {@link #getSort getSort}.
*/
public final static int OBJECT = 10;
/**
* The <tt>void</tt> type.
*/
public final static Type VOID_TYPE = new Type(VOID);
/**
* The <tt>boolean</tt> type.
*/
public final static Type BOOLEAN_TYPE = new Type(BOOLEAN);
/**
* The <tt>char</tt> type.
*/
public final static Type CHAR_TYPE = new Type(CHAR);
/**
* The <tt>byte</tt> type.
*/
public final static Type BYTE_TYPE = new Type(BYTE);
/**
* The <tt>short</tt> type.
*/
public final static Type SHORT_TYPE = new Type(SHORT);
/**
* The <tt>int</tt> type.
*/
public final static Type INT_TYPE = new Type(INT);
/**
* The <tt>float</tt> type.
*/
public final static Type FLOAT_TYPE = new Type(FLOAT);
/**
* The <tt>long</tt> type.
*/
public final static Type LONG_TYPE = new Type(LONG);
/**
* The <tt>double</tt> type.
*/
public final static Type DOUBLE_TYPE = new Type(DOUBLE);
// Fields
/**
* The sort of this Java type.
*/
private final int sort;
/**
* A buffer containing the descriptor of this Java type. This field is only
* used for reference types.
*/
private char[] buf;
/**
* The offset of the descriptor of this Java type in {@link #buf buf}. This
* field is only used for reference types.
*/
private int off;
/**
* The length of the descriptor of this Java type.
*/
private int len;
// Constructors
/**
* Constructs a primitive type.
*
* @param sort the sort of the primitive type to be constructed.
*/
private Type(final int sort) {
this.sort = sort;
this.len = 1;
}
/**
* Constructs a reference type.
*
* @param sort the sort of the reference type to be constructed.
* @param buf a buffer containing the descriptor of the previous type.
* @param off the offset of this descriptor in the previous buffer.
* @param len the length of this descriptor.
*/
private Type(final int sort, final char[] buf, final int off, final int len)
{
this.sort = sort;
this.buf = buf;
this.off = off;
this.len = len;
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param typeDescriptor a type descriptor.
* @return the Java type corresponding to the given type descriptor.
*/
public static Type getType(final String typeDescriptor) {
return getType(typeDescriptor.toCharArray(), 0);
}
/**
* Returns the Java type corresponding to the given class.
*
* @param c a class.
* @return the Java type corresponding to the given class.
*/
public static Type getType(final Class c) {
if (c.isPrimitive()) {
if (c == Integer.TYPE) {
return INT_TYPE;
} else if (c == Void.TYPE) {
return VOID_TYPE;
} else if (c == Boolean.TYPE) {
return BOOLEAN_TYPE;
} else if (c == Byte.TYPE) {
return BYTE_TYPE;
} else if (c == Character.TYPE) {
return CHAR_TYPE;
} else if (c == Short.TYPE) {
return SHORT_TYPE;
} else if (c == Double.TYPE) {
return DOUBLE_TYPE;
} else if (c == Float.TYPE) {
return FLOAT_TYPE;
} else /* if (c == Long.TYPE) */{
return LONG_TYPE;
}
} else {
return getType(getDescriptor(c));
}
}
/**
* Returns the Java types corresponding to the argument types of the given
* method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the Java types corresponding to the argument types of the given
* method descriptor.
*/
public static Type[] getArgumentTypes(final String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
int off = 1;
int size = 0;
while (true) {
char car = buf[off++];
if (car == ')') {
break;
} else if (car == 'L') {
while (buf[off++] != ';') {
}
++size;
} else if (car != '[') {
++size;
}
}
Type[] args = new Type[size];
off = 1;
size = 0;
while (buf[off] != ')') {
args[size] = getType(buf, off);
off += args[size].len;
size += 1;
}
return args;
}
/**
* Returns the Java types corresponding to the argument types of the given
* method.
*
* @param method a method.
* @return the Java types corresponding to the argument types of the given
* method.
*/
public static Type[] getArgumentTypes(final Method method) {
Class[] classes = method.getParameterTypes();
Type[] types = new Type[classes.length];
for (int i = classes.length - 1; i >= 0; --i) {
types[i] = getType(classes[i]);
}
return types;
}
/**
* Returns the Java type corresponding to the return type of the given
* method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the Java type corresponding to the return type of the given
* method descriptor.
*/
public static Type getReturnType(final String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
return getType(buf, methodDescriptor.indexOf(')') + 1);
}
/**
* Returns the Java type corresponding to the return type of the given
* method.
*
* @param method a method.
* @return the Java type corresponding to the return type of the given
* method.
*/
public static Type getReturnType(final Method method) {
return getType(method.getReturnType());
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param buf a buffer containing a type descriptor.
* @param off the offset of this descriptor in the previous buffer.
* @return the Java type corresponding to the given type descriptor.
*/
private static Type getType(final char[] buf, final int off) {
int len;
switch (buf[off]) {
case 'V':
return VOID_TYPE;
case 'Z':
return BOOLEAN_TYPE;
case 'C':
return CHAR_TYPE;
case 'B':
return BYTE_TYPE;
case 'S':
return SHORT_TYPE;
case 'I':
return INT_TYPE;
case 'F':
return FLOAT_TYPE;
case 'J':
return LONG_TYPE;
case 'D':
return DOUBLE_TYPE;
case '[':
len = 1;
while (buf[off + len] == '[') {
++len;
}
if (buf[off + len] == 'L') {
++len;
while (buf[off + len] != ';') {
++len;
}
}
return new Type(ARRAY, buf, off, len + 1);
// case 'L':
default:
len = 1;
while (buf[off + len] != ';') {
++len;
}
return new Type(OBJECT, buf, off, len + 1);
}
}
// Accessors
/**
* Returns the sort of this Java type.
*
* @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN},
* {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT SHORT},
* {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG},
* {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY} or
* {@link #OBJECT OBJECT}.
*/
public int getSort() {
return sort;
}
/**
* Returns the number of dimensions of this array type. This method should
* only be used for an array type.
*
* @return the number of dimensions of this array type.
*/
public int getDimensions() {
int i = 1;
while (buf[off + i] == '[') {
++i;
}
return i;
}
/**
* Returns the type of the elements of this array type. This method should
* only be used for an array type.
*
* @return Returns the type of the elements of this array type.
*/
public Type getElementType() {
return getType(buf, off + getDimensions());
}
/**
* Returns the name of the class corresponding to this type.
*
* @return the fully qualified name of the class corresponding to this type.
*/
public String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuffer b = new StringBuffer(getElementType().getClassName());
for (int i = getDimensions(); i > 0; --i) {
b.append("[]");
}
return b.toString();
// case OBJECT:
default:
return new String(buf, off + 1, len - 2).replace('/', '.');
}
}
/**
* Returns the internal name of the class corresponding to this object type.
* The internal name of a class is its fully qualified name, where '.' are
* replaced by '/'. This method should only be used for an object type.
*
* @return the internal name of the class corresponding to this object type.
*/
public String getInternalName() {
return new String(buf, off + 1, len - 2);
}
// Conversion to type descriptors
/**
* Returns the descriptor corresponding to this Java type.
*
* @return the descriptor corresponding to this Java type.
*/
public String getDescriptor() {
StringBuffer buf = new StringBuffer();
getDescriptor(buf);
return buf.toString();
}
/**
* Returns the descriptor corresponding to the given argument and return
* types.
*
* @param returnType the return type of the method.
* @param argumentTypes the argument types of the method.
* @return the descriptor corresponding to the given argument and return
* types.
*/
public static String getMethodDescriptor(
final Type returnType,
final Type[] argumentTypes)
{
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < argumentTypes.length; ++i) {
argumentTypes[i].getDescriptor(buf);
}
buf.append(')');
returnType.getDescriptor(buf);
return buf.toString();
}
/**
* Appends the descriptor corresponding to this Java type to the given
* string buffer.
*
* @param buf the string buffer to which the descriptor must be appended.
*/
private void getDescriptor(final StringBuffer buf) {
switch (sort) {
case VOID:
buf.append('V');
return;
case BOOLEAN:
buf.append('Z');
return;
case CHAR:
buf.append('C');
return;
case BYTE:
buf.append('B');
return;
case SHORT:
buf.append('S');
return;
case INT:
buf.append('I');
return;
case FLOAT:
buf.append('F');
return;
case LONG:
buf.append('J');
return;
case DOUBLE:
buf.append('D');
return;
// case ARRAY:
// case OBJECT:
default:
buf.append(this.buf, off, len);
}
}
// Direct conversion from classes to type descriptors,
// without intermediate Type objects
/**
* Returns the internal name of the given class. The internal name of a
* class is its fully qualified name, where '.' are replaced by '/'.
*
* @param c an object class.
* @return the internal name of the given class.
*/
public static String getInternalName(final Class c) {
return c.getName().replace('.', '/');
}
/**
* Returns the descriptor corresponding to the given Java type.
*
* @param c an object class, a primitive class or an array class.
* @return the descriptor corresponding to the given class.
*/
public static String getDescriptor(final Class c) {
StringBuffer buf = new StringBuffer();
getDescriptor(buf, c);
return buf.toString();
}
/**
* Returns the descriptor corresponding to the given constructor.
*
* @param c a {@link Constructor Constructor} object.
* @return the descriptor of the given constructor.
*/
public static String getConstructorDescriptor(final Constructor c) {
Class[] parameters = c.getParameterTypes();
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < parameters.length; ++i) {
getDescriptor(buf, parameters[i]);
}
return buf.append(")V").toString();
}
/**
* Returns the descriptor corresponding to the given method.
*
* @param m a {@link Method Method} object.
* @return the descriptor of the given method.
*/
public static String getMethodDescriptor(final Method m) {
Class[] parameters = m.getParameterTypes();
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < parameters.length; ++i) {
getDescriptor(buf, parameters[i]);
}
buf.append(')');
getDescriptor(buf, m.getReturnType());
return buf.toString();
}
/**
* Appends the descriptor of the given class to the given string buffer.
*
* @param buf the string buffer to which the descriptor must be appended.
* @param c the class whose descriptor must be computed.
*/
private static void getDescriptor(final StringBuffer buf, final Class c) {
Class d = c;
while (true) {
if (d.isPrimitive()) {
char car;
if (d == Integer.TYPE) {
car = 'I';
} else if (d == Void.TYPE) {
car = 'V';
} else if (d == Boolean.TYPE) {
car = 'Z';
} else if (d == Byte.TYPE) {
car = 'B';
} else if (d == Character.TYPE) {
car = 'C';
} else if (d == Short.TYPE) {
car = 'S';
} else if (d == Double.TYPE) {
car = 'D';
} else if (d == Float.TYPE) {
car = 'F';
} else /* if (d == Long.TYPE) */{
car = 'J';
}
buf.append(car);
return;
} else if (d.isArray()) {
buf.append('[');
d = d.getComponentType();
} else {
buf.append('L');
String name = d.getName();
int len = name.length();
for (int i = 0; i < len; ++i) {
char car = name.charAt(i);
buf.append(car == '.' ? '/' : car);
}
buf.append(';');
return;
}
}
}
// Corresponding size and opcodes
/**
* Returns the size of values of this type.
*
* @return the size of values of this type, i.e., 2 for <tt>long</tt> and
* <tt>double</tt>, and 1 otherwise.
*/
public int getSize() {
return sort == LONG || sort == DOUBLE ? 2 : 1;
}
/**
* Returns a JVM instruction opcode adapted to this Java type.
*
* @param opcode a JVM instruction opcode. This opcode must be one of ILOAD,
* ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL,
* ISHR, IUSHR, IAND, IOR, IXOR and IRETURN.
* @return an opcode that is similar to the given opcode, but adapted to
* this Java type. For example, if this type is <tt>float</tt> and
* <tt>opcode</tt> is IRETURN, this method returns FRETURN.
*/
public int getOpcode(final int opcode) {
if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) {
switch (sort) {
case BOOLEAN:
case BYTE:
return opcode + 5;
case CHAR:
return opcode + 6;
case SHORT:
return opcode + 7;
case INT:
return opcode;
case FLOAT:
return opcode + 2;
case LONG:
return opcode + 1;
case DOUBLE:
return opcode + 3;
// case ARRAY:
// case OBJECT:
default:
return opcode + 4;
}
} else {
switch (sort) {
case VOID:
return opcode + 5;
case BOOLEAN:
case CHAR:
case BYTE:
case SHORT:
case INT:
return opcode;
case FLOAT:
return opcode + 2;
case LONG:
return opcode + 1;
case DOUBLE:
return opcode + 3;
// case ARRAY:
// case OBJECT:
default:
return opcode + 4;
}
}
}
// Equals, hashCode and toString
/**
* Tests if the given object is equal to this type.
*
* @param o the object to be compared to this type.
* @return <tt>true</tt> if the given object is equal to this type.
*/
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || !(o instanceof Type)) {
return false;
}
Type t = (Type) o;
if (sort != t.sort) {
return false;
}
if (sort == Type.OBJECT || sort == Type.ARRAY) {
if (len != t.len) {
return false;
}
for (int i = off, j = t.off, end = i + len; i < end; i++, j++) {
if (buf[i] != t.buf[j]) {
return false;
}
}
}
return true;
}
/**
* Returns a hash code value for this type.
*
* @return a hash code value for this type.
*/
public int hashCode() {
int hc = 13 * sort;
if (sort == Type.OBJECT || sort == Type.ARRAY) {
for (int i = off, end = i + len; i < end; i++) {
hc = 17 * (hc + buf[i]);
}
}
return hc;
}
/**
* Returns a string representation of this type.
*
* @return the descriptor of this type.
*/
public String toString() {
return getDescriptor();
}
}
|
package org.pi.litepost;
import java.io.File;
import java.sql.SQLException;
import java.time.LocalDateTime;
import org.pi.litepost.databaseAccess.*;
public class Seeder {
public static void seed() throws Exception{
File data = new File("res/litepost.db");
if (data.exists()) {
data.delete();
}
DatabaseConnector DbConnector = new DatabaseConnector("res/litepost.db");
DbConnector.connect();
DatabaseQueryManager dbQueryManager= new DatabaseQueryManager(DbConnector);
dbQueryManager.executeQuery("insertUser", "uhukoenig123", PasswordHash.createHash("troll22"), "Markus", "Cohenheim", "blubla@gmx.de");
dbQueryManager.executeQuery("insertUser", "uhuknig123", PasswordHash.createHash("troll22"), "Reiner", "Mahan", "Reiner_Mahan@gmx.de");
dbQueryManager.executeQuery("insertUser", "FRUITSPONGYSAMURAISAN", PasswordHash.createHash("troll22"), "Sebastian", "Rosenthal", "emo_lord89@gmx.de");
dbQueryManager.executeQuery("insertUser", "PakoElectronics", PasswordHash.createHash("troll222"), "Herbert", "Kranz", "PakoElectronixs@gmx.de");
dbQueryManager.executeQuery("insertPost", "Was ist Text?", "Text schmerz mich", LocalDateTime.of(2015, 2, 15, 5, 15), "0090/99913213", 1);
dbQueryManager.executeQuery("insertPost", "Mein supertolles neues Fahrrad", "Mir wurde zu Weihnachten ein supertolles neues Fahrrad geschenkt, welches ich aber nicht brauche, also wollte ich es verkaufen.", LocalDateTime.of(2015, 2, 15, 5, 20), "Schlachthausstrae 19", 3);
dbQueryManager.executeQuery("insertPost", "Gamer PC DDDDD FFFFF 00000 1 x 109191000hz TKraft 73", "", LocalDateTime.of(2015, 2, 15, 8, 1), "Burgumstrae 20", 4);
dbQueryManager.executeQuery("insertPost", "Schrfe-Wettessen", "Beispiel-Text zur Demonstration des Forums.", LocalDateTime.of(2015, 2, 15, 17, 15), "I-wo beliebiges", 2);
dbQueryManager.executeQuery("insertComment", 3, "nicht weiter!", LocalDateTime.of(2015, 2, 15, 5, 17), 0, 1);
dbQueryManager.executeQuery("insertComment", 1, "lol", LocalDateTime.of(2015, 2, 15, 5, 18), 1, 1);
DbConnector.close();
}
}
|
package org.supercsv.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.exception.SuperCSVException;
/**
* A utility class for various list/map operations. May be of use to the public as well as to BestCSV
*
* @author Kasper B. Graversen
*/
public abstract class Util {
/**
* Convert a map to a list
*
* @param source
* the map to create a list from
* @param nameMapping
* the keys of the map whose values will constitute the list
* @return a list
*/
public static List<? extends Object> map2List(final Map<String, ? extends Object> source, final String[] nameMapping) {
final List<? super Object> result = new ArrayList<Object>(nameMapping.length);
for( final String element : nameMapping ) {
result.add(source.get(element));
}
return result;
}
/**
* A function to convert a list to a map using a namemapper for defining the keys of the map.
*
* @param destination
* the resulting map instance. The map is cleared before populated
* @param nameMapper
* cannot contain duplicate names
* @param values
* A list of values TODO: see if using an iterator for the values is more efficient
*/
public static <T> void mapStringList(final Map<String, T> destination, final String[] nameMapper, final List<T> values) {
if( nameMapper.length != values.size() ) {
throw new SuperCSVException(
"The namemapper array and the value list must match in size. Number of columns mismatch number of entries for your map.");
}
destination.clear();
// map each element of the array
for( int i = 0; i < nameMapper.length; i++ ) {
final String key = nameMapper[i];
// null's in the name mapping means skip column
if( key == null ) {
continue;
}
// only perform safe inserts
if( destination.containsKey(key) ) {
throw new SuperCSVException("nameMapper array contains duplicate key \"" + key
+ "\" cannot map the list...");
}
destination.put(key, values.get(i));
}
}
/**
* A function which given a list of strings, process each cell using its corresponding processor-chain from the
* processor array and return the result as an arary Can be extended so the safety check is cached in case the same two
* arrays are used on several requests
*
* @param destination
* This list is emptied and then populated with the result from reading a line
* @param source
* Is an array of Strings/null's representing the soure elements
* @param processors
* an array of CellProcessors/null's enabling custom processing of each cellvalue specified in the cellValue
* array. The number of non-null entries in the cellValues array must match the number of processors/null
* given.
* @param lineNo
* the line number of the CSV source the processing is taking place on
* @param errorLog
* a builder of error messages. In case of an exception, this builder is populated with a message. All cells
* are attempted processed even in case one cell throws an exception.
*/
public static void processStringList(final List<? super Object> destination, final List<? extends Object> source,
final CellProcessor[] processors, final int lineNo) throws SuperCSVException {
if( source.size() != processors.length ) {
throw new SuperCSVException(
"The value array (size "
+ source.size()
+ ") must match the processors array (size "
+ processors.length
+ ")."
+ " You are probably reading a CSV line with a different number of columns than the number of cellprocessors specified...");
}
destination.clear();
final CSVContext context = new CSVContext();
context.lineSource = source;
for( int i = 0; i < source.size(); i++ ) {
// if no processor, just add the string
if( processors[i] == null ) {
destination.add(source.get(i));
}
else {
context.lineNumber = lineNo;
context.columnNumber = i;
destination.add(processors[i].execute(source.get(i), context)); // add
}
}
}
/**
* Convert a map to an array of objects
*
* @param values
* the values
* @param nameMapping
* the mapping defining the order of the value extract of the map
* @return the map unfolded as an array based on the nameMapping
*/
public static Object[] stringMap(final Map<String, ? extends Object> values, final String[] nameMapping) {
final Object[] res = new Object[nameMapping.length];
int i = 0;
for( final String name : nameMapping ) {
res[i++] = values.get(name);
}
return res;
}
}
|
package org.terifan.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import javax.swing.UIManager;
import javax.swing.border.Border;
import static org.terifan.ui.Anchor.CENTER;
import static org.terifan.ui.Anchor.EAST;
import static org.terifan.ui.Anchor.NORTH;
import static org.terifan.ui.Anchor.NORTH_EAST;
import static org.terifan.ui.Anchor.SOUTH;
import static org.terifan.ui.Anchor.SOUTH_EAST;
import org.terifan.util.log.Log;
public class TextBox implements Cloneable
{
private final static Insets ZERO_INSETS = new Insets(0,0,0,0);
private static FontRenderContext DEFAULT_RENDER_CONTEXT = new FontRenderContext(new AffineTransform(), true, false);
private static char[] DEFAULT_BREAK_CHARS = {' ', '.', ',', '-', '_'};
private String mText;
private Font mFont;
private Color mForeground;
private Color mBackground;
private Color mHighlight;
private Insets mMargins;
private Insets mPadding;
private Border mBorder;
private Border mTextBorder;
private Rectangle mBounds;
private Anchor mAnchor;
private int mLineSpacing;
private int mMaxLineCount;
private char[] mBreakChars;
private FontRenderContext mFontRenderContext;
private boolean mDirty;
private ArrayList<String> mTextLines;
private ArrayList<Rectangle> mTextBounds;
public TextBox()
{
this("");
}
public TextBox(String aText)
{
mText = aText;
mBounds = new Rectangle();
mMargins = new Insets(0, 0, 0, 0);
mPadding = new Insets(0, 0, 0, 0);
mForeground = Color.BLACK;
mAnchor = Anchor.NORTH_WEST;
mFont = UIManager.getDefaults().getFont("TextField.font");
mBreakChars = DEFAULT_BREAK_CHARS;
mFontRenderContext = DEFAULT_RENDER_CONTEXT;
mDirty = true;
}
public String getText()
{
return mText;
}
public TextBox setText(String aText)
{
if (aText == null)
{
throw new IllegalArgumentException("aText is null");
}
mText = aText;
mDirty = true;
return this;
}
public Font getFont()
{
return mFont;
}
public TextBox setFont(Font aFont)
{
if (aFont == null)
{
throw new IllegalArgumentException("aFont is null");
}
mFont = aFont;
mDirty = true;
return this;
}
public Color getForeground()
{
return mForeground;
}
public TextBox setForeground(Color aForeground)
{
if (aForeground == null)
{
throw new IllegalArgumentException("aForeground is null");
}
mForeground = aForeground;
return this;
}
public Color getBackground()
{
return mBackground;
}
public TextBox setBackground(Color aBackground)
{
mBackground = aBackground;
return this;
}
public Color getHighlight()
{
return mHighlight;
}
public TextBox setHighlight(Color aHighlight)
{
mHighlight = aHighlight;
return this;
}
public Insets getMargins()
{
return mMargins;
}
public TextBox setMargins(Insets aMargins)
{
if (aMargins == null)
{
throw new IllegalArgumentException("aMargins is null");
}
return setMargins(aMargins.top, aMargins.left, aMargins.bottom, aMargins.right);
}
public TextBox setMargins(int aTop, int aLeft, int Bottom, int aRight)
{
mMargins.set(aTop, aLeft, Bottom, aRight);
mDirty = true;
return this;
}
public Insets getPadding()
{
return mPadding;
}
public TextBox setPadding(Insets aPadding)
{
if (aPadding == null)
{
throw new IllegalArgumentException("aPadding is null");
}
return setPadding(aPadding.top, aPadding.left, aPadding.bottom, aPadding.right);
}
public TextBox setPadding(int aTop, int aLeft, int Bottom, int aRight)
{
mPadding.set(aTop, aLeft, Bottom, aRight);
mDirty = true;
return this;
}
public Border getBorder()
{
return mBorder;
}
public TextBox setBorder(Border aBorder)
{
mBorder = aBorder;
mDirty = true;
return this;
}
public Border getTextBorder()
{
return mTextBorder;
}
public TextBox setTextBorder(Border aBorder)
{
mTextBorder = aBorder;
mDirty = true;
return this;
}
public Rectangle getBounds()
{
return mBounds;
}
public TextBox setBounds(Rectangle aBounds)
{
if (aBounds == null)
{
throw new IllegalArgumentException("aBounds is null");
}
mBounds = new Rectangle(aBounds);
mDirty = true;
return this;
}
public TextBox setBounds(int aOffsetX, int aOffsetY, int aWidth, int aHeight)
{
mBounds.setBounds(aOffsetX, aOffsetY, aWidth, aHeight);
mDirty = true;
return this;
}
public TextBox setDimensions(Dimension aDimension)
{
if (aDimension == null)
{
throw new IllegalArgumentException("aDimension is null");
}
mBounds.setSize(aDimension);
mDirty = true;
return this;
}
public TextBox setDimensions(int aWidth, int aHeight)
{
mBounds.setSize(aWidth, aHeight);
mDirty = true;
return this;
}
public Anchor getAnchor()
{
return mAnchor;
}
public TextBox setAnchor(Anchor aAnchor)
{
if (aAnchor == null)
{
throw new IllegalArgumentException("aAnchor is null");
}
mAnchor = aAnchor;
mDirty = true;
return this;
}
public int getLineSpacing()
{
return mLineSpacing;
}
public TextBox setLineSpacing(int aLineSpacing)
{
mLineSpacing = aLineSpacing;
mDirty = true;
return this;
}
public int getMaxLineCount()
{
return mMaxLineCount;
}
public TextBox setMaxLineCount(int aLineCount)
{
mMaxLineCount = aLineCount;
mDirty = true;
return this;
}
public void translate(int aDeltaX, int aDeltaY)
{
mBounds.translate(aDeltaX, aDeltaY);
mDirty = true;
}
public int getWidth()
{
return mBounds.width;
}
public TextBox setWidth(int aWidth)
{
mBounds.width = aWidth;
return this;
}
public int getHeight()
{
return mBounds.height;
}
public TextBox setHeight(int aHeight)
{
mBounds.height = aHeight;
return this;
}
public int getX()
{
return mBounds.x;
}
public TextBox setX(int aOffsetX)
{
mBounds.x = aOffsetX;
return this;
}
public int getY()
{
return mBounds.y;
}
public TextBox setY(int aOffsetY)
{
mBounds.y = aOffsetY;
return this;
}
public TextBox pack()
{
setBounds(measure());
mDirty = false;
return this;
}
public TextBox setBreakChars(char[] aBreakChars)
{
if (aBreakChars == null)
{
aBreakChars = new char[0];
}
mBreakChars = aBreakChars.clone();
return this;
}
public char[] getBreakChars()
{
return mBreakChars.clone();
}
public Rectangle measure()
{
if (mBounds.isEmpty())
{
mBounds.setBounds(0, 0, Short.MAX_VALUE, Short.MAX_VALUE);
}
if (mDirty)
{
layout();
}
if (mTextBounds.isEmpty())
{
return new Rectangle();
}
Rectangle bounds = new Rectangle(mTextBounds.get(0));
for (int i = 1, sz = mTextBounds.size(); i < sz; i++)
{
bounds.add(mTextBounds.get(i));
}
if (mBorder != null)
{
Insets bi = mBorder.getBorderInsets(null);
bounds.x -= bi.left;
bounds.y -= bi.top;
bounds.width += bi.left + bi.right;
bounds.height += bi.top + bi.bottom;
}
if (mTextBorder != null)
{
Insets bi = mTextBorder.getBorderInsets(null);
bounds.x -= bi.left;
bounds.y -= bi.top;
bounds.width += bi.left + bi.right;
bounds.height += bi.top + bi.bottom;
}
bounds.x -= mMargins.left;
bounds.y -= mMargins.top;
bounds.width += mMargins.left + mMargins.right;
bounds.height += mMargins.top + mMargins.bottom;
return bounds;
}
@Override
public TextBox clone()
{
try
{
TextBox textBox = (TextBox)super.clone();
textBox.mAnchor = this.mAnchor;
textBox.mBackground = this.mBackground;
textBox.mBorder = this.mBorder;
textBox.mBounds = (Rectangle)this.mBounds.clone();
textBox.mBreakChars = this.mBreakChars == DEFAULT_BREAK_CHARS ? DEFAULT_BREAK_CHARS : this.mBreakChars.clone();
textBox.mDirty = this.mDirty;
textBox.mFont = this.mFont;
textBox.mFontRenderContext = this.mFontRenderContext;
textBox.mForeground = this.mForeground;
textBox.mHighlight = this.mHighlight;
textBox.mMaxLineCount = this.mMaxLineCount;
textBox.mLineSpacing = this.mLineSpacing;
textBox.mMargins = (Insets)mMargins.clone();
textBox.mPadding = (Insets)mPadding.clone();
textBox.mText = this.mText;
textBox.mTextBorder = this.mTextBorder;
textBox.mTextLines = this.mTextLines == null ? null : new ArrayList<>(this.mTextLines);
return textBox;
}
catch (CloneNotSupportedException e)
{
throw new Error();
}
}
public TextBox render(Graphics aGraphics)
{
return render(aGraphics, 0, 0);
}
public TextBox render(Graphics aGraphics, int aTranslateX, int aTranslateY)
{
if (mDirty)
{
layout();
}
aGraphics.translate(aTranslateX, aTranslateY);
if (aGraphics instanceof Graphics2D)
{
((Graphics2D)aGraphics).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
}
int boxX = mBounds.x;
int boxY = mBounds.y;
int boxW = mBounds.width;
int boxH = mBounds.height;
if (mBorder != null)
{
mBorder.paintBorder(null, aGraphics, boxX, boxY, boxW, boxH);
Insets bi = mBorder.getBorderInsets(null);
boxX += bi.left;
boxY += bi.top;
boxW -= bi.left + bi.right;
boxH -= bi.left + bi.bottom;
}
if (mBackground != null)
{
aGraphics.setColor(mBackground);
aGraphics.fillRect(boxX, boxY, boxW, boxH);
}
Insets ti = mTextBorder != null ? mTextBorder.getBorderInsets(null) : ZERO_INSETS;
LineMetrics lm = mFont.getLineMetrics("Adgj", mFontRenderContext);
aGraphics.setColor(mForeground);
aGraphics.setFont(mFont);
for (int i = 0, sz = mTextBounds.size(); i < sz; i++)
{
Rectangle r = mTextBounds.get(i);
if (mTextBorder != null)
{
mTextBorder.paintBorder(null, aGraphics, r.x - ti.left, r.y - ti.top, r.width + ti.left + ti.right, r.height + ti.top + ti.bottom);
}
drawSingleLine(aGraphics, mTextLines.get(i), lm, r.x, r.y, r.width, r.height);
}
aGraphics.translate(-aTranslateX, -aTranslateY);
return this;
}
private synchronized void layout()
{
if (mText == null)
{
throw new IllegalStateException("Text is null");
}
layoutLines();
layoutBounds();
mDirty = false;
}
private void layoutBounds()
{
ArrayList<Rectangle> list = new ArrayList<>();
int boxX = mBounds.x;
int boxY = mBounds.y;
int boxW = mBounds.width;
int boxH = mBounds.height;
if (mBorder != null)
{
Insets bi = mBorder.getBorderInsets(null);
boxX += bi.left;
boxY += bi.top;
boxW -= bi.left + bi.right;
boxH -= bi.left + bi.bottom;
}
boxX += mMargins.left;
boxY += mMargins.top;
boxW -= mMargins.left + mMargins.right;
boxH -= mMargins.top + mMargins.bottom;
int extraLineHeight = 0;
if (mTextBorder != null)
{
Insets bi = mTextBorder.getBorderInsets(null);
boxX += bi.left;
boxY += bi.top;
boxW -= bi.left + bi.right;
boxH -= bi.left + bi.bottom;
extraLineHeight = bi.top + bi.bottom;
}
LineMetrics lm = mFont.getLineMetrics("Adgj", mFontRenderContext);
int lineHeight = (int)lm.getHeight() + mPadding.top + mPadding.bottom;
if (boxH < lineHeight)
{
boxH = lineHeight;
}
int lineHeightExtra = lineHeight + mLineSpacing + extraLineHeight;
int boxHeightExtra = boxH + mLineSpacing + extraLineHeight;
int lineY = boxY;
int lineCount = Math.min(Math.min(mTextLines.size(), mMaxLineCount > 0 ? mMaxLineCount : Integer.MAX_VALUE), boxHeightExtra / lineHeightExtra);
switch (mAnchor)
{
case SOUTH_EAST:
case SOUTH:
case SOUTH_WEST:
lineY += Math.max(0, boxHeightExtra - lineCount * lineHeightExtra);
break;
case CENTER:
case WEST:
case EAST:
lineY += Math.max(0, (boxHeightExtra - lineCount * lineHeightExtra) / 2);
break;
}
for (int i = 0; i < lineCount; i++)
{
String str = mTextLines.get(i);
int lineX = boxX;
int lineW = getStringLength(str, mFont) + mPadding.left + mPadding.right;
switch (mAnchor)
{
case NORTH:
case CENTER:
case SOUTH:
lineX += (boxW - lineW) / 2;
break;
case NORTH_EAST:
case EAST:
case SOUTH_EAST:
lineX += boxW - lineW;
break;
}
list.add(new Rectangle(lineX, lineY, lineW, lineHeight));
lineY += lineHeightExtra;
}
mTextBounds = list;
}
private void layoutLines()
{
ArrayList<String> list = new ArrayList<>();
int boxW = mBounds.width - mMargins.left - mMargins.right;
if (mBorder != null)
{
Insets bi = mBorder.getBorderInsets(null);
boxW -= bi.left + bi.right;
}
if (mTextBorder != null)
{
Insets bi = mTextBorder.getBorderInsets(null);
boxW -= bi.left + bi.right;
}
boxW -= mPadding.left + mPadding.right;
if (boxW > 0)
{
for (String str : mText.split("\n"))
{
do
{
int w = getStringLength(str, mFont);
String tmp;
if (w > boxW)
{
int offset = Math.max(findStringLimit(str, boxW), 1);
int temp = offset;
outer: for (; temp > 1; temp
{
char c = str.charAt(temp - 1);
for (char d : mBreakChars)
{
if (c == d)
{
break outer;
}
}
}
if (temp > 1)
{
offset = temp;
}
tmp = str.substring(0, offset);
str = str.substring(offset).trim();
}
else
{
tmp = str;
str = "";
}
list.add(tmp.trim());
if (mMaxLineCount > 0 && list.size() >= mMaxLineCount)
{
break;
}
}
while (str.length() > 0);
if (mMaxLineCount > 0 && list.size() >= mMaxLineCount)
{
break;
}
}
}
mTextLines = list;
}
private int findStringLimit(String aString, int aWidth)
{
int min = 0;
int max = aString.length();
while (Math.abs(min - max) > 1)
{
int mid = (max + min) / 2;
int w = getStringLength(aString.substring(0, mid), mFont);
if (w > aWidth)
{
max = mid;
}
else
{
min = mid;
}
}
return min;
}
private int getStringLength(String aString, Font aFont)
{
return (int)Math.ceil(aFont.getStringBounds(aString, mFontRenderContext).getWidth());
}
private void drawSingleLine(Graphics aGraphics, String aText, LineMetrics aLineMetrics, int aOffsetX, int aOffsetY, int aWidth, int aHeight)
{
if (mHighlight != null)
{
aGraphics.setColor(mHighlight);
aGraphics.fillRect(aOffsetX, aOffsetY, aWidth, aHeight);
aGraphics.setColor(mForeground);
}
int adjust = (int)(aLineMetrics.getHeight() - aLineMetrics.getDescent());
aGraphics.drawString(aText, aOffsetX + mPadding.left, aOffsetY + adjust + mPadding.top);
}
static int getBaseLine(Font aFont, int aHeight)
{
LineMetrics lm = aFont.getLineMetrics("Adgj", DEFAULT_RENDER_CONTEXT);
return (int)(lm.getHeight() - lm.getDescent());
}
}
|
package dr.evolution.coalescent;
/**
*
* @version $Id: PiecewiseLinearPopulation.java,v 1.7 2005/05/24 20:25:56 rambaut Exp $
*
* @author Alexei Drummond
* @author Andrew Rambaut
*/
public class PiecewiseLinearPopulation extends PiecewiseConstantPopulation {
/**
* Construct demographic model with default settings
*/
public PiecewiseLinearPopulation(double[] intervals, double[] thetas, Type units) {
super(intervals, thetas, units);
}
// Implementation of abstract methods
/**
* @return the value of the demographic function for the given epoch and time relative to start of epoch.
*/
protected final double getDemographic(int epoch, double t) {
// if in last epoch then the population is flat.
if (epoch == (thetas.length - 1)) {
return getEpochDemographic(epoch);
}
double popSize1 = getEpochDemographic(epoch);
double popSize2 = getEpochDemographic(epoch+1);
double width = getEpochDuration(epoch);
return (popSize1 * (width-t) + (popSize2 * t)) / width;
}
public DemographicFunction getCopy() {
PiecewiseLinearPopulation df = new PiecewiseLinearPopulation(new double[intervals.length], new double[thetas.length], getUnits());
System.arraycopy(intervals, 0, df.intervals, 0, intervals.length);
System.arraycopy(thetas, 0, df.thetas, 0, thetas.length);
return df;
}
/**
* @return the value of the intensity function for the given epoch.
*/
protected final double getIntensity(int epoch) {
return 2.0 * getEpochDuration(epoch) / (getEpochDemographic(epoch) + getEpochDemographic(epoch+1));
}
/**
* @return the value of the intensity function for the given epoch and time relative to start of epoch.
*/
protected final double getIntensity(int epoch, double relativeTime) {
return 2.0 * relativeTime / (getEpochDemographic(epoch) + getDemographic(epoch, relativeTime));
}
}
|
package edu.washington.escience.myriad.operator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import edu.washington.escience.myriad.DbException;
import edu.washington.escience.myriad.MyriaConstants;
import edu.washington.escience.myriad.Schema;
import edu.washington.escience.myriad.TupleBatch;
import edu.washington.escience.myriad.TupleBatchBuffer;
import edu.washington.escience.myriad.Type;
import edu.washington.escience.myriad.parallel.Worker.QueryExecutionMode;
/**
* This is an implementation of hash equal join. The same as in DupElim, this implementation does not keep the
* references to the incoming TupleBatches in order to get better memory performance.
* */
public final class LocalJoin extends Operator {
/** Required for Java serialization. */
private static final long serialVersionUID = 1L;
/**
* The two children.
* */
private Operator child1, child2;
/**
* The result schema.
* */
private Schema outputSchema;
/**
* The column indices for comparing of child 1.
* */
private final int[] compareIndx1;
/**
* The column indices for comparing of child 2.
* */
private final int[] compareIndx2;
/**
* A hash table for tuples from child 1. {Hashcode -> List of tuple indices with the same hash code}
* */
private transient HashMap<Integer, List<Integer>> hashTable1Indices;
/**
* A hash table for tuples from child 2. {Hashcode -> List of tuple indices with the same hash code}
* */
private transient HashMap<Integer, List<Integer>> hashTable2Indices;
/**
* The buffer holding the valid tuples from child1.
* */
private transient TupleBatchBuffer hashTable1;
/**
* The buffer holding the valid tuples from child2.
* */
private transient TupleBatchBuffer hashTable2;
/**
* The buffer holding the results.
* */
private transient TupleBatchBuffer ans;
/** Which columns in the left child are to be output. */
private final int[] answerColumns1;
/** Which columns in the right child are to be output. */
private final int[] answerColumns2;
public LocalJoin(final Operator child1, final Operator child2, final int[] compareIndx1, final int[] compareIndx2) {
this(Schema.merge(child1.getSchema(), child2.getSchema()), child1, child2, compareIndx1, compareIndx2);
}
public LocalJoin(final Operator child1, final Operator child2, final int[] compareIndx1, final int[] compareIndx2,
final int[] answerColumns1, final int[] answerColumns2) {
this(mergeFilter(child1, child2, answerColumns1, answerColumns2), child1, child2, compareIndx1, compareIndx2,
answerColumns1, answerColumns2);
}
private LocalJoin(final Schema outputSchema, final Operator child1, final Operator child2, final int[] compareIndx1,
final int[] compareIndx2, final int[] answerColumns1, final int[] answerColumns2) {
this.outputSchema = outputSchema;
this.child1 = child1;
this.child2 = child2;
this.compareIndx1 = compareIndx1;
this.compareIndx2 = compareIndx2;
this.answerColumns1 = answerColumns1;
this.answerColumns2 = answerColumns2;
}
private LocalJoin(final Schema outputSchema, final Operator child1, final Operator child2, final int[] compareIndx1,
final int[] compareIndx2) {
this(outputSchema, child1, child2, compareIndx1, compareIndx2, range(child1.getSchema().numColumns()), range(child2
.getSchema().numColumns()));
}
/**
* Helper function that generates an array of the numbers 0..max-1.
*
* @param max the size of the array.
* @return an array of the numbers 0..max-1.
*/
private static int[] range(final int max) {
int[] ret = new int[max];
for (int i = 0; i < max; ++i) {
ret[i] = i;
}
return ret;
}
/**
* Helper function to generate the proper output schema merging two parts of two schemas.
*
* @param child1 the left child.
* @param child2 the right child.
* @param answerColumns1 the selected columns of the left schema.
* @param answerColumns2 the selected columns of the right schema.
* @return a schema that contains the chosen columns of the left and right schema.
*/
private static Schema mergeFilter(final Operator child1, final Operator child2, final int[] answerColumns1,
final int[] answerColumns2) {
if (child1 == null || child2 == null) {
return null;
}
ImmutableList.Builder<Type> types = ImmutableList.builder();
ImmutableList.Builder<String> names = ImmutableList.builder();
for (int i : answerColumns1) {
types.add(child1.getSchema().getColumnType(i));
names.add(child1.getSchema().getColumnName(i));
}
for (int i : answerColumns2) {
types.add(child2.getSchema().getColumnType(i));
names.add(child2.getSchema().getColumnName(i));
}
return new Schema(types, names);
}
/**
* @param cntTuple a list representation of a tuple
* @param hashTable the buffer holding the tuples to join against
* @param index the index of hashTable, which the cntTuple is to join with
* @param fromChild1 if the tuple is from child 1
*/
protected void addToAns(final List<Object> cntTuple, final TupleBatchBuffer hashTable, final int index,
final boolean fromChild1) {
if (fromChild1) {
for (int i = 0; i < answerColumns1.length; ++i) {
ans.put(i, cntTuple.get(answerColumns1[i]));
}
for (int i = 0; i < answerColumns2.length; ++i) {
ans.put(i + answerColumns1.length, hashTable.get(answerColumns2[i], index));
}
} else {
for (int i = 0; i < answerColumns1.length; ++i) {
ans.put(i, hashTable.get(answerColumns1[i], index));
}
for (int i = 0; i < answerColumns2.length; ++i) {
ans.put(i + answerColumns1.length, cntTuple.get(answerColumns2[i]));
}
}
}
@Override
protected void cleanup() throws DbException {
hashTable1 = null;
hashTable2 = null;
ans = null;
}
/**
* In blocking mode, asynchronous EOI semantic may make system hang. Only synchronous EOI semantic works.
*
* @return result TB.
* @throws DbException if any error occurs.
* */
private TupleBatch fetchNextReadySynchronousEOI() throws DbException {
TupleBatch nexttb = ans.popFilled();
while (nexttb == null) {
boolean hasnewtuple = false;
if (!child1.eos() && !childrenEOI[0]) {
TupleBatch tb = child1.nextReady();
if (tb != null) {
hasnewtuple = true;
processChildTB(tb, true);
} else {
if (child1.eoi()) {
child1.setEOI(false);
childrenEOI[0] = true;
}
}
}
if (!child2.eos() && !childrenEOI[1]) {
TupleBatch tb = child2.nextReady();
if (tb != null) {
hasnewtuple = true;
processChildTB(tb, false);
} else {
if (child2.eoi()) {
child2.setEOI(false);
childrenEOI[1] = true;
}
}
}
nexttb = ans.popFilled();
if (nexttb != null) {
return nexttb;
}
if (!hasnewtuple) {
break;
}
}
if (nexttb == null) {
if (ans.numTuples() > 0) {
nexttb = ans.popAny();
}
checkEOSAndEOI();
}
return nexttb;
}
@Override
public void checkEOSAndEOI() {
if (child1.eos() && child2.eos()) {
setEOS();
return;
}
// EOS could be used as an EOI
if ((childrenEOI[0] || child1.eos()) && (childrenEOI[1] || child2.eos())) {
setEOI(true);
Arrays.fill(childrenEOI, false);
}
}
/**
* Recording the EOI status of the children.
* */
private final boolean[] childrenEOI = new boolean[2];
@Override
protected TupleBatch fetchNextReady() throws DbException {
if (!nonBlocking) {
return fetchNextReadySynchronousEOI();
}
TupleBatch nexttb = ans.popFilled();
if (nexttb != null) {
return nexttb;
}
if (eoi()) {
return ans.popAny();
}
TupleBatch child1TB = null;
TupleBatch child2TB = null;
int numEOS = 0;
int numNoData = 0;
while (numEOS < 2 && numNoData < 2) {
numEOS = 0;
if (child1.eos()) {
numEOS += 1;
}
if (child2.eos()) {
numEOS += 1;
}
numNoData = numEOS;
child1TB = null;
child2TB = null;
if (!child1.eos()) {
child1TB = child1.nextReady();
if (child1TB != null) { // data
processChildTB(child1TB, true);
nexttb = ans.popFilled();
if (nexttb != null) {
return nexttb;
}
} else {
// eoi or eos or no data
if (child1.eoi()) {
child1.setEOI(false);
childrenEOI[0] = true;
checkEOSAndEOI();
if (eoi()) {
break;
}
} else if (child1.eos()) {
numEOS++;
} else {
numNoData++;
}
}
}
if (!child2.eos()) {
child2TB = child2.nextReady();
if (child2TB != null) {
processChildTB(child2TB, false);
nexttb = ans.popFilled();
if (nexttb != null) {
return nexttb;
}
} else {
if (child2.eoi()) {
child2.setEOI(false);
childrenEOI[1] = true;
checkEOSAndEOI();
if (eoi()) {
break;
}
} else if (child2.eos()) {
numEOS++;
} else {
numNoData++;
}
}
}
}
Preconditions.checkArgument(numEOS <= 2);
Preconditions.checkArgument(numNoData <= 2);
checkEOSAndEOI();
if (eoi() || eos()) {
nexttb = ans.popAny();
}
return nexttb;
}
@Override
public Operator[] getChildren() {
return new Operator[] { child1, child2 };
}
@Override
public Schema getSchema() {
return outputSchema;
}
@Override
public void init(final ImmutableMap<String, Object> execEnvVars) throws DbException {
hashTable1Indices = new HashMap<Integer, List<Integer>>();
hashTable2Indices = new HashMap<Integer, List<Integer>>();
hashTable1 = new TupleBatchBuffer(child1.getSchema());
hashTable2 = new TupleBatchBuffer(child2.getSchema());
ans = new TupleBatchBuffer(outputSchema);
QueryExecutionMode qem = (QueryExecutionMode) execEnvVars.get(MyriaConstants.EXEC_ENV_VAR_EXECUTION_MODE);
nonBlocking = qem == QueryExecutionMode.NON_BLOCKING;
}
/**
* The query execution mode is nonBlocking.
* */
private transient boolean nonBlocking = true;
/**
* Check if a tuple in uniqueTuples equals to the comparing tuple (cntTuple).
*
* @param hashTable the TupleBatchBuffer holding the tuples to compare against
* @param index the index in the hashTable
* @param cntTuple a list representation of a tuple
* @param compareIndx1 the comparing list of columns of cntTuple
* @param compareIndx2 the comparing list of columns of hashTable
* @return true if equals.
* */
private boolean tupleEquals(final List<Object> cntTuple, final TupleBatchBuffer hashTable, final int index,
final int[] compareIndx1, final int[] compareIndx2) {
if (compareIndx1.length != compareIndx2.length) {
return false;
}
for (int i = 0; i < compareIndx1.length; ++i) {
if (!cntTuple.get(compareIndx1[i]).equals(hashTable.get(compareIndx2[i], index))) {
return false;
}
}
return true;
}
/**
* @param tb the incoming TupleBatch for processing join.
* @param fromChild1 if the tb is from child1.
* */
protected void processChildTB(final TupleBatch tb, final boolean fromChild1) {
TupleBatchBuffer hashTable1Local = hashTable1;
TupleBatchBuffer hashTable2Local = hashTable2;
HashMap<Integer, List<Integer>> hashTable1IndicesLocal = hashTable1Indices;
HashMap<Integer, List<Integer>> hashTable2IndicesLocal = hashTable2Indices;
int[] compareIndx1Local = compareIndx1;
int[] compareIndx2Local = compareIndx2;
if (!fromChild1) {
hashTable1Local = hashTable2;
hashTable2Local = hashTable1;
hashTable1IndicesLocal = hashTable2Indices;
hashTable2IndicesLocal = hashTable1Indices;
compareIndx1Local = compareIndx2;
compareIndx2Local = compareIndx1;
}
for (int i = 0; i < tb.numTuples(); ++i) {
final List<Object> cntTuple = new ArrayList<Object>();
for (int j = 0; j < tb.numColumns(); ++j) {
cntTuple.add(tb.getObject(j, i));
}
final int nextIndex = hashTable1Local.numTuples();
final int cntHashCode = tb.hashCode(i, compareIndx1Local);
List<Integer> indexList = hashTable2IndicesLocal.get(cntHashCode);
if (indexList != null) {
for (final int index : indexList) {
if (tupleEquals(cntTuple, hashTable2Local, index, compareIndx1Local, compareIndx2Local)) {
addToAns(cntTuple, hashTable2Local, index, fromChild1);
}
}
}
if (hashTable1IndicesLocal.get(cntHashCode) == null) {
hashTable1IndicesLocal.put(cntHashCode, new ArrayList<Integer>());
}
hashTable1IndicesLocal.get(cntHashCode).add(nextIndex);
for (int j = 0; j < tb.numColumns(); ++j) {
hashTable1Local.put(j, cntTuple.get(j));
}
}
}
@Override
public void setChildren(final Operator[] children) {
Preconditions.checkNotNull(children, "LocalJoin.setChildren called with null argument.");
Preconditions.checkArgument(children.length == 2, "LocalJoin must have exactly 2 children.");
child1 = Objects.requireNonNull(children[0], "LocalJoin.setChildren called with null left child.");
child2 = Objects.requireNonNull(children[1], "LocalJoin.setChildren called with null right child.");
outputSchema = mergeFilter(child1, child2, answerColumns1, answerColumns2);
}
}
|
/**
* EditEntityScreen
*
* Class representing the screen that allows users to edit properties of
* grid entities, including triggers and appearance.
*
* @author Willy McHie
* Wheaton College, CSCI 335, Spring 2013
*/
package edu.wheaton.simulator.gui.screen;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import edu.wheaton.simulator.datastructure.ElementAlreadyContainedException;
import edu.wheaton.simulator.entity.Prototype;
import edu.wheaton.simulator.entity.Trigger;
import edu.wheaton.simulator.gui.BoxLayoutAxis;
import edu.wheaton.simulator.gui.Gui;
import edu.wheaton.simulator.gui.HorizontalAlignment;
import edu.wheaton.simulator.gui.IconGridPanel;
import edu.wheaton.simulator.gui.MaxSize;
import edu.wheaton.simulator.gui.PrefSize;
import edu.wheaton.simulator.gui.ScreenManager;
import edu.wheaton.simulator.gui.SimulatorFacade;
public class EditEntityScreen extends Screen {
private static final long serialVersionUID = 4021299442173260142L;
private Boolean editing;
private Prototype agent;
private JPanel cards;
private String currentCard;
private JPanel generalPanel;
private JTextField nameField;
private JColorChooser colorTool;
private ArrayList<JTextField> fieldNames;
private ArrayList<JTextField> fieldValues;
private ArrayList<JButton> fieldDeleteButtons;
private ArrayList<JPanel> fieldSubPanels;
private JButton addFieldButton;
private boolean[][] buttons;
private JPanel fieldListPanel;
private ArrayList<JTextField> triggerNames;
private ArrayList<JTextField> triggerPriorities;
private ArrayList<JTextField> triggerConditions;
private ArrayList<JTextField> triggerResults;
private ArrayList<JButton> triggerDeleteButtons;
private ArrayList<JPanel> triggerSubPanels;
private JButton addTriggerButton;
private JPanel triggerListPanel;
private HashSet<Integer> removedFields;
private HashSet<Integer> removedTriggers;
private JButton nextButton;
private JButton previousButton;
private JButton finishButton;
private GridBagConstraints c;
public EditEntityScreen(final SimulatorFacade gm) {
super(gm);
this.setLayout(new BorderLayout());
editing = false;
removedFields = new HashSet<Integer>();
removedTriggers = new HashSet<Integer>();
nameField = new JTextField(25);
//nameField.setPreferredSize(new Dimension(400, 40));
//nameField.setMinimumSize(new Dimension(200, 40));
colorTool = Gui.makeColorChooser();
fieldNames = new ArrayList<JTextField>();
fieldValues = new ArrayList<JTextField>();
fieldSubPanels = new ArrayList<JPanel>();
triggerSubPanels = new ArrayList<JPanel>();
triggerNames = new ArrayList<JTextField>();
triggerPriorities = new ArrayList<JTextField>();
triggerConditions = new ArrayList<JTextField>();
triggerResults = new ArrayList<JTextField>();
fieldDeleteButtons = new ArrayList<JButton>();
triggerDeleteButtons = new ArrayList<JButton>();
buttons = new boolean[7][7];
currentCard = "General";
fieldListPanel = Gui.makePanel(BoxLayoutAxis.Y_AXIS, MaxSize.NULL,
PrefSize.NULL);
triggerListPanel = Gui.makePanel(BoxLayoutAxis.Y_AXIS, MaxSize.NULL,
PrefSize.NULL);
cards = new JPanel(new CardLayout());
generalPanel = new JPanel(new GridBagLayout());
addFieldButton = Gui.makeButton("Add Field",null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addField();
}
});
addTriggerButton = Gui.makeButton("Add Trigger",null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addTrigger();
}
});
final IconGridPanel iconPanel = new IconGridPanel(gm);
iconPanel.setPreferredSize(new Dimension(500, 500));
//iconPanel.setAlignmentX(RIGHT_ALIGNMENT);
initIconDesignObject(iconPanel);
JPanel colorPanel = Gui.makeColorChooserPanel(colorTool);
Dimension maxSize = colorPanel.getMaximumSize();
maxSize.height += 50;
colorPanel.setMaximumSize(maxSize);
colorTool.getSelectionModel().addChangeListener( new ChangeListener(){
@Override
public void stateChanged(ChangeEvent ce) {
iconPanel.repaint();
}
});
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
generalPanel.add(
Gui.makeLabel("General Info",
new PrefSize(300,80),
HorizontalAlignment.CENTER),c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
generalPanel.add(
new JLabel("Agent Name: ",SwingConstants.RIGHT),c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 1;
c.ipadx = 250;
generalPanel.add(nameField, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
generalPanel.add(colorPanel, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0;
c.gridx = 2;
c.gridy = 2;
c.ipadx = 500;
c.ipady = 500;
c.gridwidth = 2;
generalPanel.add(iconPanel, c);
addField();
// TODO make sure components line up
fieldSubPanels.get(0).setLayout(
new BoxLayout(fieldSubPanels.get(0), BoxLayout.X_AXIS));
fieldSubPanels.get(0).add(fieldNames.get(0));
fieldSubPanels.get(0).add(fieldValues.get(0));
fieldSubPanels.get(0).add(fieldDeleteButtons.get(0));
fieldListPanel.add(fieldSubPanels.get(0));
fieldListPanel.add(addFieldButton);
fieldListPanel.add(Box.createVerticalGlue());
addTrigger();
triggerSubPanels.get(0).setLayout(
new BoxLayout(triggerSubPanels.get(0), BoxLayout.X_AXIS));
triggerSubPanels.get(0).add(triggerNames.get(0));
triggerSubPanels.get(0).add(triggerPriorities.get(0));
triggerSubPanels.get(0).add(triggerConditions.get(0));
triggerSubPanels.get(0).add(triggerResults.get(0));
triggerSubPanels.get(0).add(triggerDeleteButtons.get(0));
triggerSubPanels.get(0).setAlignmentX(CENTER_ALIGNMENT);
triggerListPanel.add(triggerSubPanels.get(0));
triggerListPanel.add(addTriggerButton);
triggerListPanel.add(Box.createVerticalGlue());
triggerListPanel.setPreferredSize(new Dimension(750, 350));
cards.add(generalPanel, "General");
cards.add(makeFieldMainPanel(fieldListPanel), "Fields");
cards.add(makeTriggerMainPanel(triggerListPanel), "Triggers");
finishButton = Gui.makeButton("Finish",null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (sendInfo()) {
Screen update = Gui.getScreenManager().getScreen("View Simulation");
update.load();
Gui.getScreenManager().update(update);
reset();
}
}
});
previousButton = Gui.makeButton("Previous", null,
new PreviousListener());
nextButton = Gui.makeButton("Next", null, new NextListener());
this.add(new JLabel("Edit Entities", SwingConstants.CENTER),
BorderLayout.NORTH);
this.add(cards, BorderLayout.CENTER);
this.add(Gui.makePanel(
previousButton,
Gui.makeButton("Cancel",null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ScreenManager sm = getScreenManager();
sm.update(sm.getScreen("View Simulation"));
if (!editing)
Prototype.removePrototype(nameField.getText());
reset();
}
}), finishButton, nextButton),
BorderLayout.SOUTH );
}
private void initIconDesignObject(IconGridPanel iconPanel){
//Creates the icon design object.
iconPanel.setIcon(buttons);
}
private static JPanel makeTriggerMainPanel(JPanel triggerListPanel) {
JPanel triggerLabelsPanel = Gui.makePanel(BoxLayoutAxis.X_AXIS,
MaxSize.NULL, PrefSize.NULL);
triggerLabelsPanel.add(Box.createHorizontalGlue());
triggerLabelsPanel.add(Gui.makeLabel("Trigger Name", new PrefSize(130,
30), HorizontalAlignment.LEFT));
triggerLabelsPanel.add(Gui.makeLabel("Trigger Priority", new PrefSize(
180, 30), null));
triggerLabelsPanel.add(Gui.makeLabel("Trigger Condition",
new PrefSize(300, 30), null));
triggerLabelsPanel.add(Gui.makeLabel("Trigger Result", new PrefSize(
300, 30), null));
triggerLabelsPanel.add(Box.createHorizontalGlue());
triggerLabelsPanel.setAlignmentX(CENTER_ALIGNMENT);
JPanel triggerBodyPanel = Gui.makePanel(BoxLayoutAxis.Y_AXIS,
MaxSize.NULL, PrefSize.NULL);
triggerBodyPanel.add(triggerLabelsPanel);
triggerBodyPanel.add(triggerListPanel);
JPanel triggerMainPanel = Gui.makePanel(new BorderLayout(),
MaxSize.NULL, PrefSize.NULL);
triggerMainPanel.add(Gui.makeLabel("Trigger Info", new PrefSize(300,
100), HorizontalAlignment.CENTER), BorderLayout.NORTH);
triggerMainPanel.add(triggerBodyPanel, BorderLayout.CENTER);
return triggerMainPanel;
}
private static JPanel makeFieldMainPanel(JPanel fieldListPanel){
JPanel fieldMainPanel = Gui.makePanel(new GridBagLayout(),MaxSize.NULL,PrefSize.NULL);
GridBagConstraints constraint = new GridBagConstraints();
constraint.gridx = 0;
constraint.gridy = 0;
constraint.gridwidth = 2;
fieldMainPanel.add(
Gui.makeLabel("Field Info",new PrefSize(300,100),HorizontalAlignment.CENTER),
constraint);
constraint = new GridBagConstraints();
constraint.gridx = 0;
constraint.gridy = 1;
constraint.gridwidth = 1;
JLabel fieldNameLabel = Gui.makeLabel("Field Name", new PrefSize(263,
30), HorizontalAlignment.LEFT);
fieldNameLabel.setAlignmentX(LEFT_ALIGNMENT);
fieldMainPanel.add(fieldNameLabel, constraint);
constraint.gridx = 1;
JLabel fieldValueLabel = Gui.makeLabel("Field Initial Value",
new PrefSize(263, 30), HorizontalAlignment.LEFT);
fieldValueLabel.setAlignmentX(LEFT_ALIGNMENT);
fieldMainPanel.add(fieldValueLabel, constraint);
constraint = new GridBagConstraints();
constraint.gridx = 0;
constraint.gridy = 2;
constraint.gridwidth = 3;
constraint.weighty = 1.0;
constraint.anchor = GridBagConstraints.PAGE_START;
fieldMainPanel.add(fieldListPanel, constraint);
return fieldMainPanel;
}
public void load(String str) {
reset();
agent = gm.getPrototype(str);
nameField.setText(agent.getName());
colorTool.setColor(agent.getColor());
byte[] designBytes = agent.getDesign();
byte byter = Byte.parseByte("0000001", 2);
for (int i = 0; i < 7; i++)
for (int j = 0; j < 7; j++)
if ((designBytes[i] & (byter << j)) != Byte.parseByte("0000000", 2))
buttons[i][6-j] = true;
Map<String, String> fields = agent.getCustomFieldMap();
int i = 0;
for (String s : fields.keySet()) {
addField();
fieldNames.get(i).setText(s);
fieldValues.get(i).setText(fields.get(s));
i++;
}
List<Trigger> triggers = agent.getTriggers();
int j = 0;
for (Trigger t : triggers) {
addTrigger();
triggerNames.get(j).setText(t.getName());
triggerConditions.get(j).setText(t.getConditions().toString());
triggerResults.get(j).setText(t.getBehavior().toString());
triggerPriorities.get(j).setText(t.getPriority() + "");
j++;
}
}
public void reset() {
agent = null;
currentCard = "General";
((CardLayout) cards.getLayout()).first(cards);
nameField.setText("");
colorTool.setColor(Color.WHITE);
for (int x = 0; x < 7; x++) {
for (int y = 0; y < 7; y++) {
buttons[x][y] = false;
}
}
fieldNames.clear();
fieldValues.clear();
fieldDeleteButtons.clear();
fieldSubPanels.clear();
removedFields.clear();
fieldListPanel.removeAll();
fieldListPanel.add(addFieldButton);
triggerNames.clear();
triggerPriorities.clear();
triggerConditions.clear();
triggerResults.clear();
triggerDeleteButtons.clear();
triggerSubPanels.clear();
removedTriggers.clear();
triggerListPanel.removeAll();
triggerListPanel.add(addTriggerButton);
previousButton.setEnabled(false);
//previousButton.setVisible(false);
nextButton.setEnabled(true);
//nextButton.setVisible(true);
finishButton.setEnabled(false);
//finishButton.setVisible(false);
}
public boolean sendInfo() {
sendGeneralInfo();
return (sendFieldInfo() && sendTriggerInfo());
}
public boolean sendGeneralInfo() {
boolean toReturn = false;
try {
if (nameField.getText().equals("")) {
throw new Exception("Please enter an Agent name");
}
if (!editing) {
//TODO signature of create prototype needs to not take a grid
gm.createPrototype(nameField.getText(), colorTool.getColor(), generateBytes());
agent = gm.getPrototype(nameField.getText());
} else {
agent.setPrototypeName(agent.getName(), nameField.getText());
agent.setColor(colorTool.getColor());
agent.setDesign(generateBytes());
Prototype.addPrototype(agent);
}
toReturn = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return toReturn;
}
public boolean sendFieldInfo() {
boolean toReturn = false;
try {
for (int i = 0; i < fieldNames.size(); i++)
if (!removedFields.contains(i)
&& (fieldNames.get(i).getText().equals("")
|| fieldValues.get(i).getText().equals("")))
throw new Exception("All fields must have input");
for (int i = 0; i < fieldNames.size(); i++) {
if (removedFields.contains(i)
&& (agent.hasField(fieldNames.get(i).getText())))
agent.removeField(fieldNames.get(i).toString());
else {
if (agent.hasField(fieldNames.get(i).getText()))
agent.updateField(fieldNames.get(i).getText(),
fieldValues.get(i).getText());
else {
try {
if (!removedFields.contains(i))
agent.addField(fieldNames.get(i).getText(),
fieldValues.get(i).getText());
} catch (ElementAlreadyContainedException e) {
e.printStackTrace();
}
}
}
}
toReturn = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return toReturn;
}
public boolean sendTriggerInfo() {
boolean toReturn = false;
try {
for (int j = 0; j < triggerNames.size(); j++) {
if (!removedTriggers.contains(j)
&& (triggerNames.get(j).getText().equals("")
|| triggerConditions.get(j).getText().equals("")
|| triggerResults.get(j).getText().equals("")))
throw new Exception("All fields must have input");
if (Integer.parseInt(triggerPriorities.get(j).getText()) < 0)
throw new Exception("Priority must be greater than 0");
}
for (int i = 0; i < triggerNames.size(); i++) {
if (removedTriggers.contains(i)
&& (agent.hasTrigger(triggerNames.get(i).getText())))
agent.removeTrigger(triggerNames.get(i).getText());
else {
if (agent.hasTrigger(triggerNames.get(i).getText()))
agent.updateTrigger(triggerNames.get(i).getText(),
generateTrigger(i));
else
agent.addTrigger(generateTrigger(i));
}
}
toReturn = true;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Priorities field must be an integer greater than 0.");
e.printStackTrace();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return toReturn;
}
public void setEditing(Boolean b) {
editing = b;
}
public Color getColor() {
return colorTool.getColor();
}
private void addField() {
JTextField newName = Gui.makeTextField(null,25,new MaxSize(300,40),null);
fieldNames.add(newName);
JTextField newValue = Gui.makeTextField(null,25,new MaxSize(300,40),null);
fieldValues.add(newValue);
JButton newButton = Gui.makeButton("Delete",null,
new DeleteFieldListener());
fieldDeleteButtons.add(newButton);
newButton.setActionCommand(fieldDeleteButtons.indexOf(newButton) + "");
JPanel newPanel = Gui.makePanel(BoxLayoutAxis.X_AXIS, null, null);
newPanel.add(newName);
newPanel.add(newValue);
newPanel.add(newButton);
fieldSubPanels.add(newPanel);
fieldListPanel.add(newPanel);
fieldListPanel.add(addFieldButton);
fieldListPanel.add(Box.createVerticalGlue());
validate();
repaint();
}
private void addTrigger() {
JTextField newName = Gui.makeTextField(null, 25, new MaxSize(200, 40),
null);
triggerNames.add(newName);
JTextField newPriority = Gui.makeTextField(null,15,new MaxSize(150,40),null);
triggerPriorities.add(newPriority);
JTextField newCondition = Gui.makeTextField(null,50,new MaxSize(300,40),null);
triggerConditions.add(newCondition);
JTextField newResult = Gui.makeTextField(null,50,new MaxSize(300,40),null);
triggerResults.add(newResult);
JButton newButton = Gui.makeButton("Delete",null,
new DeleteTriggerListener());
newButton.setActionCommand(triggerDeleteButtons.indexOf(newButton)
+ "");
triggerDeleteButtons.add(newButton);
JPanel newPanel = Gui.makePanel(BoxLayoutAxis.X_AXIS,null,null);
newPanel.add(newName);
newPanel.add(newPriority);
newPanel.add(newCondition);
newPanel.add(newResult);
newPanel.add(newButton);
triggerSubPanels.add(newPanel);
triggerListPanel.add(newPanel);
triggerListPanel.add(addTriggerButton);
triggerListPanel.add(Box.createVerticalGlue());
repaint();
}
private byte[] generateBytes() {
String str = "";
byte[] toReturn = new byte[7];
for (int column = 0; column < 7; column++) {
for (int row = 0; row < 7; row++) {
if (buttons[column][row] == true)
str += "1";
else
str += "0";
}
str += ":";
}
String[] byteStr = str.substring(0, str.lastIndexOf(':')).split(":");
for (int i = 0; i < 7; i++)
toReturn[i] = Byte.parseByte(byteStr[i], 2);
return toReturn;
}
private Trigger generateTrigger(int i) {
return new Trigger(triggerNames.get(i).getText(),
Integer.parseInt(triggerPriorities.get(i).getText()),
SimulatorFacade.makeExpression(triggerConditions.get(i).getText()),
SimulatorFacade.makeExpression(triggerResults.get(i).getText()));
}
private class DeleteFieldListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
removedFields.add(Integer.parseInt(e.getActionCommand()));
fieldListPanel.remove(fieldSubPanels.get(Integer.parseInt(e
.getActionCommand())));
validate();
}
}
private class DeleteTriggerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
removedTriggers.add(Integer.parseInt(e.getActionCommand()));
triggerListPanel.remove(triggerSubPanels.get(Integer.parseInt(e
.getActionCommand())));
validate();
}
}
private class NextListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout c1 = (CardLayout) cards.getLayout();
if (currentCard == "General") {
if (sendGeneralInfo()) {
previousButton.setEnabled(true);
//previousButton.setVisible(true);
c1.next(cards);
currentCard = "Fields";
}
} else if (currentCard == "Fields") {
if (sendFieldInfo()) {
c1.next(cards);
nextButton.setEnabled(false);
//nextButton.setVisible(false);
finishButton.setEnabled(true);
//finishButton.setVisible(true);
currentCard = "Triggers";
}
}
validate();
}
}
private class PreviousListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout c1 = (CardLayout) cards.getLayout();
if (currentCard == "Fields") {
previousButton.setEnabled(false);
//previousButton.setVisible(false);
c1.previous(cards);
currentCard = "General";
} else if (currentCard == "Triggers") {
c1.previous(cards);
nextButton.setEnabled(true);
//nextButton.setVisible(true);
currentCard = "Fields";
}
validate();
}
}
@Override
public void load() {
reset();
addField();
addTrigger();
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.RobotMap;
/**
* @author Team 2035 Programmers
*/
public class Pusher extends Subsystem {
private boolean frontGripDeployed1;
private boolean frontGripDeployed2;
private boolean rearGripDeployed;
private boolean frontGripContacted;
private boolean rearGripContacted;
private Solenoid frontSolenoid1;
private Solenoid frontSolenoid2;
private Solenoid rearSolenoid;
public Pusher() {
frontGripDeployed1 = false;
frontGripDeployed2 = false;
rearGripDeployed = false;
frontGripContacted = false;
rearGripContacted = false;
frontSolenoid1 = RobotMap.frontPusherFirst;
frontSolenoid2 = RobotMap.frontPusherSecond;
rearSolenoid = RobotMap.rearPusher;
}
/** The front Pusher has two air cylinders to have the option to extend 3 or 6 inches.
*
* @param position Either 0 for both off, 1 for a single extension, or 2 for double extension
*/
public void moveFrontPusher(int position) {
if(position == 1) {
frontSolenoid1.set(true);
frontGripDeployed1 = true;
frontSolenoid2.set(false);
frontGripDeployed2 = false;
}
if(position == 2) {
frontSolenoid2.set(true);
frontGripDeployed1 = true;
frontSolenoid2.set(true);
frontGripDeployed2 = true;
}
if(position == 0) {
frontSolenoid1.set(false);
frontGripDeployed1 = false;
frontSolenoid2.set(false);
frontGripDeployed2 = false;
}
}
/** The rear Pusher has only one cylinder to extend 3 inches.
*
* @param position Either 0 for off, or 1 for extension.
*/
public void moveRearPusher(int position) {
if(position == 1) {
rearSolenoid.set(true);
rearGripDeployed = true;
}
if(position == 0) {
rearSolenoid.set(false);
rearGripDeployed = false;
}
}
/** Returns the Solenoid position of the front Pusher.
*
* @return 0 for not deployed, 1 for extended 3 inches, 2 for extended 6 inches.
*/
public int getFrontPusherPosition() {
int position = 0;
if (frontGripDeployed1) {
position++;
}
if (frontGripDeployed2) {
position++;
}
return position;
}
/** Returns the Solenoid position of the rear Pusher.
*
* @return 0 for not deployed, 1 for extended 3 inches.
*/
public int getRearPusherPosition() {
int position = 0;
if (rearGripDeployed) {
position++;
}
return position;
}
public boolean isFrontContacting() {
frontGripContacted = RobotMap.pusherFrontSensor1.get();
return frontGripContacted;
}
public boolean isRearContacting() {
rearGripContacted = RobotMap.pusherRearSensor1.get();
return rearGripContacted;
}
public boolean checkFrontSensor1() {
return RobotMap.pusherFrontSensor1.get();
}
public boolean checkFrontSensor2() {
return RobotMap.pusherFrontSensor2.get();
}
public boolean checkRearSensor1() {
return RobotMap.pusherRearSensor1.get();
}
public boolean checkRearSensor2() {
return RobotMap.pusherRearSensor2.get();
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
}
|
package experimentalcode.lisa;
import java.util.Iterator;
import java.util.List;
import de.lmu.ifi.dbs.elki.algorithm.DistanceBasedAlgorithm;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.DistanceResultPair;
import de.lmu.ifi.dbs.elki.distance.Distance;
import de.lmu.ifi.dbs.elki.distance.DoubleDistance;
import de.lmu.ifi.dbs.elki.result.AnnotationsFromDatabase;
import de.lmu.ifi.dbs.elki.result.MultiResult;
import de.lmu.ifi.dbs.elki.result.OrderingFromAssociation;
import de.lmu.ifi.dbs.elki.result.ResultUtil;
import de.lmu.ifi.dbs.elki.utilities.Description;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.IntParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
public class KNNIntegralOutlierDetection <O extends DatabaseObject, D extends DoubleDistance> extends DistanceBasedAlgorithm<O , DoubleDistance , MultiResult> {
public static final OptionID K_ID = OptionID.getOrCreateOptionID(
"knnio.k",
"kth nearest neighbor"
);
public static final OptionID N_ID = OptionID.getOrCreateOptionID(
"knnio.n",
"number of outliers that are searched"
);
public static final AssociationID<Double> KNNIO_ODEGREE= AssociationID.getOrCreateAssociationID("knnio_odegree", Double.class);
public static final AssociationID<Double> KNNIO_MAXODEGREE = AssociationID.getOrCreateAssociationID("knnio_maxodegree", Double.class);
/**
* Parameter to specify the kth nearest neighbor,
*
* <p>Key: {@code -knnio.k} </p>
*/
private final IntParameter K_PARAM = new IntParameter(K_ID);
/**
* Parameter to specify the number of outliers
*
* <p>Key: {@code -knnio.n} </p>
*/
private final IntParameter N_PARAM = new IntParameter(N_ID);
/**
* Holds the value of {@link #K_PARAM}.
*/
private int k;
/**
* Holds the value of {@link #N_PARAM}.
*/
private int n;
/**
* Provides the result of the algorithm.
*/
MultiResult result;
/**
* Constructor, adding options to option handler.
*/
public KNNIntegralOutlierDetection() {
super();
// kth nearest neighbor
addOption(K_PARAM);
// number of outliers
addOption(N_PARAM);
}
/**
* Calls the super method
* and sets additionally the values of the parameter
* {@link #K_PARAM}, {@link #N_PARAM}
*/
@Override
public String[] setParameters(String[] args) throws ParameterException {
String[] remainingParameters = super.setParameters(args);
k = K_PARAM.getValue();
n = N_PARAM.getValue();
return remainingParameters;
}
/**
* Runs the algorithm in the timed evaluation part.
*/
@Override
protected MultiResult runInTime(Database<O> database) throws IllegalStateException {
getDistanceFunction().setDatabase(database, isVerbose(), isTime());
Iterator<Integer> iter = database.iterator();
Integer id;
//compute distance to the k nearest neighbor. n objects with the highest distance are flagged as outliers
while(iter.hasNext()){
id = iter.next();
//compute sum of the distances to the k nearest neighbors
List<DistanceResultPair<DoubleDistance>> knn = database.kNNQueryForID(id, k, getDistanceFunction());
DoubleDistance skn = knn.get(0).getFirst();
for (int i = 1; i< k; i++) {
skn = skn.plus(knn.get(i).getFirst());
}
debugFine(skn + " dkn");
double doubleSkn = skn.getValue();
database.associate(KNNIO_ODEGREE, id, doubleSkn);
}
AnnotationsFromDatabase<O, Double> res1 = new AnnotationsFromDatabase<O, Double>(database);
res1.addAssociation(KNNIO_ODEGREE);
// Ordering
OrderingFromAssociation<Double, O> res2 = new OrderingFromAssociation<Double, O>(database, KNNIO_ODEGREE, true);
// combine results.
//ResultUtil.setGlobalAssociation(result, KNNIO_MAXODEGREE, maxProb);
result = new MultiResult();
result.addResult(res1);
result.addResult(res2);
return result;
}
@Override
public Description getDescription() {
// TODO Auto-generated method stub
return null;
}
@Override
public MultiResult getResult() {
return result;
}}
|
package fi.bitrite.android.ws.auth.http;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.util.Log;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import fi.bitrite.android.ws.WSAndroidApplication;
import fi.bitrite.android.ws.auth.AuthenticationHelper;
import fi.bitrite.android.ws.auth.AuthenticationService;
import fi.bitrite.android.ws.util.http.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CircularRedirectException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Responsible for authenticating the user against the WarmShowers web service.
*/
public class HttpAuthenticator {
private static final String WARMSHOWERS_USER_AUTHENTICATION_URL = "https:
private static final String WARMSHOWERS_USER_AUTHENTICATION_TEST_URL = "https:
private String username;
private String authtoken;
/**
* Load a page in order to see if we are authenticated
*/
public boolean isAuthenticated() {
HttpClient client = HttpUtils.getDefaultClient();
int responseCode;
try {
String url = HttpUtils.encodeUrl(WARMSHOWERS_USER_AUTHENTICATION_TEST_URL);
HttpGet get = new HttpGet(url);
HttpContext context = HttpSessionContainer.INSTANCE.getSessionContext();
HttpResponse response = client.execute(get, context);
HttpEntity entity = response.getEntity();
responseCode = response.getStatusLine().getStatusCode();
EntityUtils.toString(entity, "UTF-8");
}
catch (Exception e) {
throw new HttpAuthenticationFailedException(e);
}
finally {
client.getConnectionManager().shutdown();
}
return (responseCode == HttpStatus.SC_OK);
}
public void authenticate() {
try {
getCredentialsFromAccount();
authenticate(username, authtoken);
}
catch (Exception e) {
throw new HttpAuthenticationFailedException(e);
}
}
private void getCredentialsFromAccount() throws OperationCanceledException, AuthenticatorException, IOException {
AccountManager accountManager = AccountManager.get(WSAndroidApplication.getAppContext());
Account account = AuthenticationHelper.getWarmshowersAccount();
authtoken = accountManager.blockingGetAuthToken(account, AuthenticationService.ACCOUNT_TYPE, true);
username = account.name;
}
/**
* Returns the user id after logging in or 0 if already logged in.
*/
public int authenticate(String username, String password) {
HttpClient client = HttpUtils.getDefaultClient();
HttpContext httpContext = HttpSessionContainer.INSTANCE.getSessionContext();
CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
cookieStore.clear();
int userId = 0;
try {
List<NameValuePair> credentials = generateCredentialsForPost(username, password);
HttpPost post = new HttpPost(WARMSHOWERS_USER_AUTHENTICATION_URL);
post.setEntity(new UrlEncodedFormEntity(credentials));
HttpResponse response = client.execute(post, httpContext);
HttpEntity entity = response.getEntity();
String rawJson = EntityUtils.toString(entity, "UTF-8");
if (rawJson.contains("Wrong username or password")) {
throw new HttpAuthenticationFailedException("Wrong username or password");
}
if (rawJson.contains("Already logged in")) {
return 0;
}
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject) parser.parse(rawJson);
String s = o.get("user").getAsJsonObject().get("uid").getAsString();
userId = Integer.valueOf(s);
}
catch (ClientProtocolException e) {
if (e.getCause() instanceof CircularRedirectException) {
// If we get this authentication has still been successful, so ignore it
} else {
throw new HttpAuthenticationFailedException(e);
}
}
catch (Exception e) {
throw new HttpAuthenticationFailedException(e);
}
finally {
client.getConnectionManager().shutdown();
}
if (!isAuthenticated()) {
throw new HttpAuthenticationFailedException("Invalid credentials");
}
return userId;
}
private List<NameValuePair> generateCredentialsForPost(String username, String password) {
List<NameValuePair> args = new ArrayList<NameValuePair>();
args.add(new BasicNameValuePair("username", username));
args.add(new BasicNameValuePair("password", password));
return args;
}
}
|
package fitnesse.testsystems.slim.tables;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import fitnesse.testsystems.slim.SlimTestContext;
import fitnesse.testsystems.slim.Table;
public class SlimTableFactory {
private static final Logger LOG = Logger.getLogger(SlimTableFactory.class.getName());
private static final Map<Class<? extends SlimTable>, Constructor<? extends SlimTable>> CONSTRUCTOR_MAP = new HashMap<Class<? extends SlimTable>, Constructor<? extends SlimTable>>();
private final Map<String, Class<? extends SlimTable>> tableTypes;
private final Map<String, String> tableTypeArrays;
private final Map<String, String> aliasArrays;
public SlimTableFactory() {
tableTypes = new HashMap<String, Class<? extends SlimTable>>(16);
tableTypeArrays = new HashMap<String, String>();
aliasArrays = new HashMap<String, String>();
addTableType("dt", DecisionTable.class);
addTableType("decision", DecisionTable.class);
addTableType("ddt", DynamicDecisionTable.class);
addTableType("dynamic decision", DynamicDecisionTable.class);
addTableType("ordered query", OrderedQueryTable.class);
addTableType("subset query", SubsetQueryTable.class);
addTableType("query", QueryTable.class);
addTableType("table", TableTable.class);
addTableType("script", ScriptTable.class);
addTableType("script:", ScriptTable.class);
addTableType("scenario", ScenarioTable.class);
addTableType("import", ImportTable.class);
addTableType("library", LibraryTable.class);
}
protected SlimTableFactory(Map<String, Class<? extends SlimTable>> tableTypes, Map<String, String> tableTypeArrays, Map<String, String> aliasArrays) {
this.tableTypes = tableTypes;
this.tableTypeArrays = tableTypeArrays;
this.aliasArrays = aliasArrays;
}
public void addTableType(String nameOrPrefix, Class<? extends SlimTable> tableClass) {
if (tableTypes.get(nameOrPrefix) != null) {
throw new IllegalStateException("A table type named '" + nameOrPrefix + "' already exists");
}
tableTypes.put(nameOrPrefix.toLowerCase().replaceAll(":", ""), tableClass);
}
public SlimTable makeSlimTable(Table table, String tableId, SlimTestContext slimTestContext) {
SlimTable newTable;
String tableType = getFullTableName(table.getCellContents(0, 0));
//table.substitute(0, 0, tableType);
// First the "exceptions to the rule"
if ( tableType.equalsIgnoreCase("define alias")) {
parseDefineAliasTable(table);
return null;
} else if (tableType.equalsIgnoreCase("define table type")) {
parseDefineTableTypeTable(table);
return null;
} else if (tableType.equalsIgnoreCase("comment") || tableType.startsWith("comment:")) {
return null;
}
Class<? extends SlimTable> tableClass = getTableType(tableType);
if (tableClass != null) {
newTable = newTableForType(tableClass, table, tableId, slimTestContext);
} else if (!hasColon(tableType)) {
newTable = new DecisionTable(table, tableId, slimTestContext);
}else {
newTable = new SlimErrorTable(table, tableId, slimTestContext);
}
newTable.setFixtureName(getRawFixtureName(tableType));
return newTable;
}
private boolean hasColon(String tableType) {
return tableType.contains(":");
}
public String getRawTableTypeName(String fullTableName) {
if (hasColon(fullTableName)) {
return fullTableName.substring(0, fullTableName.indexOf(':')).trim().toLowerCase();
}
return "";
}
public String getRawFixtureName(String fullTableName) {
if (hasColon(fullTableName)) {
return fullTableName.substring(fullTableName.indexOf(':') + 1).trim();
}
return fullTableName;
}
public Class<? extends SlimTable> getTableType(String tableType) {
if (hasColon(tableType)) {
tableType = tableType.substring(0, tableType.indexOf(':'));
}
return tableTypes.get(tableType.toLowerCase().trim());
}
private SlimTable newTableForType(Class<? extends SlimTable> tableClass,
Table table, String tableId, SlimTestContext slimTestContext) {
try {
return createTable(tableClass, table, tableId, slimTestContext);
} catch (Exception e) {
LOG.log(Level.WARNING, "Can not create new table instance for class " + tableClass, e);
return new SlimErrorTable(table, tableId, slimTestContext);
}
}
public static <T extends SlimTable> T createTable(Class<T> tableClass, Table table, String tableId, SlimTestContext slimTestContext) throws Exception {
Constructor<? extends SlimTable> constructor = CONSTRUCTOR_MAP.get(tableClass);
if (constructor == null) {
constructor = tableClass.getConstructor(Table.class, String.class, SlimTestContext.class);
CONSTRUCTOR_MAP.put(tableClass, constructor);
}
return (T) constructor.newInstance(table, tableId, slimTestContext);
}
private String getFullTableName(String tableName) {
String fixtureName=tableName;
String tableType;
String disgracedName = Disgracer.disgraceClassName(getRawFixtureName(tableName));
//check for an alias definition
if (aliasArrays.containsKey(disgracedName)) {
fixtureName = aliasArrays.get(disgracedName);
tableType = getRawTableTypeName(tableName);
if (hasColon(fixtureName)){
tableType = getRawTableTypeName(fixtureName);
fixtureName = getRawFixtureName(fixtureName);
if (tableType.isEmpty()) tableType = getRawTableTypeName(tableName);
if (fixtureName.isEmpty()) fixtureName = getRawFixtureName(tableName);
}
return tableType + ":" + fixtureName;
}else if (hasColon(tableName)) {
// a table type definition exits in the table
return tableName;
}
//check for a table type defined in a table type definition
else if (tableTypeArrays.containsKey(disgracedName)) {
return tableTypeArrays.get(disgracedName) + ":" + tableName;
}
return tableName;
}
private SlimTable parseDefineTableTypeTable(Table table) {
for (int rowIndex = 1; rowIndex < table.getRowCount(); rowIndex++)
parseDefineTableTypeRow(table, rowIndex);
return null;
}
private void parseDefineTableTypeRow(Table table, int rowIndex) {
if (table.getColumnCountInRow(rowIndex) >= 2) {
String fixtureName = table.getCellContents(0, rowIndex);
String fixture = Disgracer.disgraceClassName(fixtureName);
String tableSpecifier = table.getCellContents(1, rowIndex).toLowerCase();
tableTypeArrays.put(fixture, makeTableType(tableSpecifier));
}
}
public void addDefaultTableType(String fixture, String tableType) {
tableTypeArrays.put(fixture, tableType);
}
public void addAlias(String alias, String fixture) {
aliasArrays.put(alias, fixture);
}
private String makeTableType(String tableSpecifier) {
tableSpecifier = tableSpecifier.replace(':', ' ');
if (tableSpecifier.startsWith("as"))
tableSpecifier = tableSpecifier.substring(2);
return tableSpecifier.trim();
}
private SlimTable parseDefineAliasTable(Table table) {
for (int rowIndex = 1; rowIndex < table.getRowCount(); rowIndex++)
parseDefineAliasRow(table, rowIndex);
return null;
}
private void parseDefineAliasRow(Table table, int rowIndex) {
if (table.getColumnCountInRow(rowIndex) >= 2) {
String fixtureName = table.getCellContents(0, rowIndex);
String fixture = Disgracer.disgraceClassName(fixtureName);
String tableSpecifier = table.getCellContents(1, rowIndex).trim();
aliasArrays.put(fixture, tableSpecifier);
}
}
public SlimTableFactory copy() {
return new SlimTableFactory(new HashMap<String, Class<? extends SlimTable>>(tableTypes),
new HashMap<String, String>(tableTypeArrays),
new HashMap<String, String>(aliasArrays));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.